blob: de60942dee2074acc0ec25487342006df01be9f7 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080038#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039
Glenn Kastend3cee2f2012-03-13 17:55:35 -070040#undef ADD_BATTERY_DATA
41
42#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080043#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080044#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070045#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070046
47#include <private/media/AudioTrackShared.h>
48#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070049
Dima Zavin64760242011-05-11 14:15:23 -070050#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070051#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
53#include "AudioMixer.h"
54#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080055#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Mathias Agopian65ab4712010-07-14 17:59:35 -070057#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070058#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070059#include <audio_effects/effect_ns.h>
60#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061
Glenn Kasten3b21c502011-12-15 09:52:39 -080062#include <audio_utils/primitives.h>
63
Eric Laurentfeb0db62011-07-22 09:04:31 -070064#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080065
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070066// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080067#ifdef DEBUG_CPU_USAGE
68#include <cpustats/CentralTendencyStatistics.h>
69#include <cpustats/ThreadCpuUsage.h>
70#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070071
John Grossman4ff14ba2012-02-08 16:37:41 -080072#include <common_time/cc_helper.h>
73#include <common_time/local_clock.h>
74
Glenn Kasten58912562012-04-03 10:45:00 -070075#include "FastMixer.h"
76
77// NBAIO implementations
78#include "AudioStreamOutSink.h"
79#include "MonoPipe.h"
80#include "MonoPipeReader.h"
81#include "SourceAudioBufferProvider.h"
82
83#ifdef SOAKER
84#include "Soaker.h"
85#endif
86
Mathias Agopian65ab4712010-07-14 17:59:35 -070087// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070088
John Grossman1c345192012-03-27 14:00:17 -070089// Note: the following macro is used for extremely verbose logging message. In
90// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
91// 0; but one side effect of this is to turn all LOGV's as well. Some messages
92// are so verbose that we want to suppress them even when we have ALOG_ASSERT
93// turned on. Do not uncomment the #def below unless you really know what you
94// are doing and want to see all of the extremely verbose messages.
95//#define VERY_VERY_VERBOSE_LOGGING
96#ifdef VERY_VERY_VERBOSE_LOGGING
97#define ALOGVV ALOGV
98#else
99#define ALOGVV(a...) do { } while(0)
100#endif
Eric Laurentde070132010-07-13 04:45:46 -0700101
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102namespace android {
103
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800104static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
105static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700106
Mathias Agopian65ab4712010-07-14 17:59:35 -0700107static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800108static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109
110// retry counts for buffer fill timeout
111// 50 * ~20msecs = 1 second
112static const int8_t kMaxTrackRetries = 50;
113static const int8_t kMaxTrackStartupRetries = 50;
114// allow less retry attempts on direct output thread.
115// direct outputs can be a scarce resource in audio hardware and should
116// be released as quickly as possible.
117static const int8_t kMaxTrackRetriesDirect = 2;
118
119static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800120static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700121
Glenn Kasten7dede872011-12-13 11:04:14 -0800122// don't warn about blocked writes or record buffer overflows more often than this
123static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700124
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700125// RecordThread loop sleep time upon application overrun or audio HAL read error
126static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700127
Glenn Kasten7dede872011-12-13 11:04:14 -0800128// maximum time to wait for setParameters to complete
129static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700130
Eric Laurent7cafbb32011-11-22 18:50:29 -0800131// minimum sleep time for the mixer thread loop when tracks are active but in underrun
132static const uint32_t kMinThreadSleepTimeUs = 5000;
133// maximum divider applied to the active sleep time in the mixer thread loop
134static const uint32_t kMaxThreadSleepTimeShift = 2;
135
Glenn Kasten58912562012-04-03 10:45:00 -0700136// minimum normal mix buffer size, expressed in milliseconds rather than frames
137static const uint32_t kMinNormalMixBufferSizeMs = 20;
138
John Grossman4ff14ba2012-02-08 16:37:41 -0800139nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800140
Mathias Agopian65ab4712010-07-14 17:59:35 -0700141// ----------------------------------------------------------------------------
142
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700143#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800144// To collect the amplifier usage
145static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800146 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
147 if (service == NULL) {
148 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800149 return;
150 }
151
152 service->addBatteryData(params);
153}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700154#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800155
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700156static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700157{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700158 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700159 int rc;
160
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700161 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
162 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
163 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
164 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700165 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700166 }
167 rc = audio_hw_device_open(mod, dev);
168 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
169 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
170 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700171 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700172 }
173 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
174 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
175 rc = BAD_VALUE;
176 goto out;
177 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700178 return 0;
179
180out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700181 *dev = NULL;
182 return rc;
183}
184
Mathias Agopian65ab4712010-07-14 17:59:35 -0700185// ----------------------------------------------------------------------------
186
187AudioFlinger::AudioFlinger()
188 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800189 mPrimaryHardwareDev(NULL),
190 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
191 mMasterVolume(1.0f),
192 mMasterVolumeSupportLvl(MVS_NONE),
193 mMasterMute(false),
194 mNextUniqueId(1),
195 mMode(AUDIO_MODE_INVALID),
196 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700197{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700198}
199
200void AudioFlinger::onFirstRef()
201{
Dima Zavin799a70e2011-04-18 16:57:27 -0700202 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700203
Eric Laurent93575202011-01-18 18:39:02 -0800204 Mutex::Autolock _l(mLock);
205
Dima Zavin799a70e2011-04-18 16:57:27 -0700206 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800207 char val_str[PROPERTY_VALUE_MAX] = { 0 };
208 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
209 uint32_t int_val;
210 if (1 == sscanf(val_str, "%u", &int_val)) {
211 mStandbyTimeInNsecs = milliseconds(int_val);
212 ALOGI("Using %u mSec as standby time.", int_val);
213 } else {
214 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
215 ALOGI("Using default %u mSec as standby time.",
216 (uint32_t)(mStandbyTimeInNsecs / 1000000));
217 }
218 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700219
Eric Laurenta4c5a552012-03-29 10:12:40 -0700220 mMode = AUDIO_MODE_NORMAL;
221 mMasterVolumeSW = 1.0;
222 mMasterVolume = 1.0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800223 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700224}
225
226AudioFlinger::~AudioFlinger()
227{
Dima Zavin799a70e2011-04-18 16:57:27 -0700228
Mathias Agopian65ab4712010-07-14 17:59:35 -0700229 while (!mRecordThreads.isEmpty()) {
230 // closeInput() will remove first entry from mRecordThreads
231 closeInput(mRecordThreads.keyAt(0));
232 }
233 while (!mPlaybackThreads.isEmpty()) {
234 // closeOutput() will remove first entry from mPlaybackThreads
235 closeOutput(mPlaybackThreads.keyAt(0));
236 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700237
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800238 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
239 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700240 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
241 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700242 }
243}
244
Eric Laurenta4c5a552012-03-29 10:12:40 -0700245static const char * const audio_interfaces[] = {
246 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
247 AUDIO_HARDWARE_MODULE_ID_A2DP,
248 AUDIO_HARDWARE_MODULE_ID_USB,
249};
250#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
251
252audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, uint32_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700253{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700254 // if module is 0, the request comes from an old policy manager and we should load
255 // well known modules
256 if (module == 0) {
257 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
258 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
259 loadHwModule_l(audio_interfaces[i]);
260 }
261 } else {
262 // check a match for the requested module handle
263 AudioHwDevice *audioHwdevice = mAudioHwDevs.valueFor(module);
264 if (audioHwdevice != NULL) {
265 return audioHwdevice->hwDevice();
266 }
267 }
268 // then try to find a module supporting the requested device.
Dima Zavin799a70e2011-04-18 16:57:27 -0700269 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700270 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700271 if ((dev->get_supported_devices(dev) & devices) == devices)
272 return dev;
273 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700274
Dima Zavin799a70e2011-04-18 16:57:27 -0700275 return NULL;
276}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700277
278status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
279{
280 const size_t SIZE = 256;
281 char buffer[SIZE];
282 String8 result;
283
284 result.append("Clients:\n");
285 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800286 sp<Client> client = mClients.valueAt(i).promote();
287 if (client != 0) {
288 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
289 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700290 }
291 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700292
293 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800294 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700295 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
296 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800297 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700298 result.append(buffer);
299 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700300 write(fd, result.string(), result.size());
301 return NO_ERROR;
302}
303
304
305status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
306{
307 const size_t SIZE = 256;
308 char buffer[SIZE];
309 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800310 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700311
John Grossman4ff14ba2012-02-08 16:37:41 -0800312 snprintf(buffer, SIZE, "Hardware status: %d\n"
313 "Standby Time mSec: %u\n",
314 hardwareStatus,
315 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700316 result.append(buffer);
317 write(fd, result.string(), result.size());
318 return NO_ERROR;
319}
320
321status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
322{
323 const size_t SIZE = 256;
324 char buffer[SIZE];
325 String8 result;
326 snprintf(buffer, SIZE, "Permission Denial: "
327 "can't dump AudioFlinger from pid=%d, uid=%d\n",
328 IPCThreadState::self()->getCallingPid(),
329 IPCThreadState::self()->getCallingUid());
330 result.append(buffer);
331 write(fd, result.string(), result.size());
332 return NO_ERROR;
333}
334
335static bool tryLock(Mutex& mutex)
336{
337 bool locked = false;
338 for (int i = 0; i < kDumpLockRetries; ++i) {
339 if (mutex.tryLock() == NO_ERROR) {
340 locked = true;
341 break;
342 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800343 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700344 }
345 return locked;
346}
347
348status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
349{
Glenn Kasten44deb052012-02-05 18:09:08 -0800350 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700351 dumpPermissionDenial(fd, args);
352 } else {
353 // get state of hardware lock
354 bool hardwareLocked = tryLock(mHardwareLock);
355 if (!hardwareLocked) {
356 String8 result(kHardwareLockedString);
357 write(fd, result.string(), result.size());
358 } else {
359 mHardwareLock.unlock();
360 }
361
362 bool locked = tryLock(mLock);
363
364 // failed to lock - AudioFlinger is probably deadlocked
365 if (!locked) {
366 String8 result(kDeadlockedString);
367 write(fd, result.string(), result.size());
368 }
369
370 dumpClients(fd, args);
371 dumpInternals(fd, args);
372
373 // dump playback threads
374 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
375 mPlaybackThreads.valueAt(i)->dump(fd, args);
376 }
377
378 // dump record threads
379 for (size_t i = 0; i < mRecordThreads.size(); i++) {
380 mRecordThreads.valueAt(i)->dump(fd, args);
381 }
382
Dima Zavin799a70e2011-04-18 16:57:27 -0700383 // dump all hardware devs
384 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700385 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700386 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700387 }
388 if (locked) mLock.unlock();
389 }
390 return NO_ERROR;
391}
392
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800393sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
394{
395 // If pid is already in the mClients wp<> map, then use that entry
396 // (for which promote() is always != 0), otherwise create a new entry and Client.
397 sp<Client> client = mClients.valueFor(pid).promote();
398 if (client == 0) {
399 client = new Client(this, pid);
400 mClients.add(pid, client);
401 }
402
403 return client;
404}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700405
406// IAudioFlinger interface
407
408
409sp<IAudioTrack> AudioFlinger::createTrack(
410 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800411 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700412 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800413 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700414 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700415 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800416 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700417 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800418 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800419 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700420 int *sessionId,
421 status_t *status)
422{
423 sp<PlaybackThread::Track> track;
424 sp<TrackHandle> trackHandle;
425 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700426 status_t lStatus;
427 int lSessionId;
428
Glenn Kasten263709e2012-01-06 08:40:01 -0800429 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
430 // but if someone uses binder directly they could bypass that and cause us to crash
431 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000432 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700433 lStatus = BAD_VALUE;
434 goto Exit;
435 }
436
437 {
438 Mutex::Autolock _l(mLock);
439 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700440 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000442 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700443 lStatus = BAD_VALUE;
444 goto Exit;
445 }
446
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800447 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700448
Steve Block3856b092011-10-20 11:56:00 +0100449 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700450 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700451 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700452 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
453 if (mPlaybackThreads.keyAt(i) != output) {
454 // prevent same audio session on different output threads
455 uint32_t sessions = t->hasAudioSession(*sessionId);
456 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000457 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700458 lStatus = BAD_VALUE;
459 goto Exit;
460 }
461 // check if an effect with same session ID is waiting for a track to be created
462 if (sessions & PlaybackThread::EFFECT_SESSION) {
463 effectThread = t.get();
464 }
Eric Laurentde070132010-07-13 04:45:46 -0700465 }
466 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700467 lSessionId = *sessionId;
468 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700469 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700470 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700471 if (sessionId != NULL) {
472 *sessionId = lSessionId;
473 }
474 }
Steve Block3856b092011-10-20 11:56:00 +0100475 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700476
477 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800478 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700479
480 // move effect chain to this output thread if an effect on same session was waiting
481 // for a track to be created
482 if (lStatus == NO_ERROR && effectThread != NULL) {
483 Mutex::Autolock _dl(thread->mLock);
484 Mutex::Autolock _sl(effectThread->mLock);
485 moveEffectChain_l(lSessionId, effectThread, thread, true);
486 }
Eric Laurenta011e352012-03-29 15:51:43 -0700487
488 // Look for sync events awaiting for a session to be used.
489 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
490 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
491 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
492 track->setSyncEvent(mPendingSyncEvents[i]);
493 mPendingSyncEvents.removeAt(i);
494 i--;
495 }
496 }
497 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700498 }
499 if (lStatus == NO_ERROR) {
500 trackHandle = new TrackHandle(track);
501 } else {
502 // remove local strong reference to Client before deleting the Track so that the Client
503 // destructor is called by the TrackBase destructor with mLock held
504 client.clear();
505 track.clear();
506 }
507
508Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700509 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700510 *status = lStatus;
511 }
512 return trackHandle;
513}
514
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800515uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700516{
517 Mutex::Autolock _l(mLock);
518 PlaybackThread *thread = checkPlaybackThread_l(output);
519 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000520 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700521 return 0;
522 }
523 return thread->sampleRate();
524}
525
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800526int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700527{
528 Mutex::Autolock _l(mLock);
529 PlaybackThread *thread = checkPlaybackThread_l(output);
530 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000531 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700532 return 0;
533 }
534 return thread->channelCount();
535}
536
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800537audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700538{
539 Mutex::Autolock _l(mLock);
540 PlaybackThread *thread = checkPlaybackThread_l(output);
541 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000542 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800543 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700544 }
545 return thread->format();
546}
547
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800548size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700549{
550 Mutex::Autolock _l(mLock);
551 PlaybackThread *thread = checkPlaybackThread_l(output);
552 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000553 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700554 return 0;
555 }
Glenn Kasten58912562012-04-03 10:45:00 -0700556 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
557 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558 return thread->frameCount();
559}
560
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800561uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700562{
563 Mutex::Autolock _l(mLock);
564 PlaybackThread *thread = checkPlaybackThread_l(output);
565 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000566 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700567 return 0;
568 }
569 return thread->latency();
570}
571
572status_t AudioFlinger::setMasterVolume(float value)
573{
Eric Laurenta1884f92011-08-23 08:25:03 -0700574 status_t ret = initCheck();
575 if (ret != NO_ERROR) {
576 return ret;
577 }
578
Mathias Agopian65ab4712010-07-14 17:59:35 -0700579 // check calling permissions
580 if (!settingsAllowed()) {
581 return PERMISSION_DENIED;
582 }
583
John Grossman4ff14ba2012-02-08 16:37:41 -0800584 float swmv = value;
585
Eric Laurenta4c5a552012-03-29 10:12:40 -0700586 Mutex::Autolock _l(mLock);
587
Mathias Agopian65ab4712010-07-14 17:59:35 -0700588 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800589 if (MVS_NONE != mMasterVolumeSupportLvl) {
590 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
591 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700592 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
John Grossman4ff14ba2012-02-08 16:37:41 -0800593
594 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
595 if (NULL != dev->set_master_volume) {
596 dev->set_master_volume(dev, value);
597 }
598 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800599 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800600
601 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700602 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700603
John Grossman4ff14ba2012-02-08 16:37:41 -0800604 mMasterVolume = value;
605 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800606 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700607 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700608
609 return NO_ERROR;
610}
611
Glenn Kastenf78aee72012-01-04 11:00:47 -0800612status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700613{
Eric Laurenta1884f92011-08-23 08:25:03 -0700614 status_t ret = initCheck();
615 if (ret != NO_ERROR) {
616 return ret;
617 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700618
619 // check calling permissions
620 if (!settingsAllowed()) {
621 return PERMISSION_DENIED;
622 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800623 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000624 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700625 return BAD_VALUE;
626 }
627
628 { // scope for the lock
629 AutoMutex lock(mHardwareLock);
630 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700631 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700632 mHardwareStatus = AUDIO_HW_IDLE;
633 }
634
635 if (NO_ERROR == ret) {
636 Mutex::Autolock _l(mLock);
637 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800638 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700639 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700640 }
641
642 return ret;
643}
644
645status_t AudioFlinger::setMicMute(bool state)
646{
Eric Laurenta1884f92011-08-23 08:25:03 -0700647 status_t ret = initCheck();
648 if (ret != NO_ERROR) {
649 return ret;
650 }
651
Mathias Agopian65ab4712010-07-14 17:59:35 -0700652 // check calling permissions
653 if (!settingsAllowed()) {
654 return PERMISSION_DENIED;
655 }
656
657 AutoMutex lock(mHardwareLock);
658 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700659 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700660 mHardwareStatus = AUDIO_HW_IDLE;
661 return ret;
662}
663
664bool AudioFlinger::getMicMute() const
665{
Eric Laurenta1884f92011-08-23 08:25:03 -0700666 status_t ret = initCheck();
667 if (ret != NO_ERROR) {
668 return false;
669 }
670
Dima Zavinfce7a472011-04-19 22:30:36 -0700671 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800672 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700673 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700674 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700675 mHardwareStatus = AUDIO_HW_IDLE;
676 return state;
677}
678
679status_t AudioFlinger::setMasterMute(bool muted)
680{
681 // check calling permissions
682 if (!settingsAllowed()) {
683 return PERMISSION_DENIED;
684 }
685
Eric Laurent93575202011-01-18 18:39:02 -0800686 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800687 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700688 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800689 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700690 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700691
692 return NO_ERROR;
693}
694
695float AudioFlinger::masterVolume() const
696{
Glenn Kasten98067102011-12-13 11:47:54 -0800697 Mutex::Autolock _l(mLock);
698 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700699}
700
John Grossman4ff14ba2012-02-08 16:37:41 -0800701float AudioFlinger::masterVolumeSW() const
702{
703 Mutex::Autolock _l(mLock);
704 return masterVolumeSW_l();
705}
706
Mathias Agopian65ab4712010-07-14 17:59:35 -0700707bool AudioFlinger::masterMute() const
708{
Glenn Kasten98067102011-12-13 11:47:54 -0800709 Mutex::Autolock _l(mLock);
710 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700711}
712
John Grossman4ff14ba2012-02-08 16:37:41 -0800713float AudioFlinger::masterVolume_l() const
714{
715 if (MVS_FULL == mMasterVolumeSupportLvl) {
716 float ret_val;
717 AutoMutex lock(mHardwareLock);
718
719 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800720 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
721 (NULL != mPrimaryHardwareDev->get_master_volume),
722 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800723
724 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
725 mHardwareStatus = AUDIO_HW_IDLE;
726 return ret_val;
727 }
728
729 return mMasterVolume;
730}
731
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800732status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
733 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700734{
735 // check calling permissions
736 if (!settingsAllowed()) {
737 return PERMISSION_DENIED;
738 }
739
Glenn Kasten263709e2012-01-06 08:40:01 -0800740 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000741 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700742 return BAD_VALUE;
743 }
744
745 AutoMutex lock(mLock);
746 PlaybackThread *thread = NULL;
747 if (output) {
748 thread = checkPlaybackThread_l(output);
749 if (thread == NULL) {
750 return BAD_VALUE;
751 }
752 }
753
754 mStreamTypes[stream].volume = value;
755
756 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800757 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700758 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700759 }
760 } else {
761 thread->setStreamVolume(stream, value);
762 }
763
764 return NO_ERROR;
765}
766
Glenn Kastenfff6d712012-01-12 16:38:12 -0800767status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700768{
769 // check calling permissions
770 if (!settingsAllowed()) {
771 return PERMISSION_DENIED;
772 }
773
Glenn Kasten263709e2012-01-06 08:40:01 -0800774 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700775 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000776 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700777 return BAD_VALUE;
778 }
779
Eric Laurent93575202011-01-18 18:39:02 -0800780 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700781 mStreamTypes[stream].mute = muted;
782 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700783 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700784
785 return NO_ERROR;
786}
787
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800788float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700789{
Glenn Kasten263709e2012-01-06 08:40:01 -0800790 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700791 return 0.0f;
792 }
793
794 AutoMutex lock(mLock);
795 float volume;
796 if (output) {
797 PlaybackThread *thread = checkPlaybackThread_l(output);
798 if (thread == NULL) {
799 return 0.0f;
800 }
801 volume = thread->streamVolume(stream);
802 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800803 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700804 }
805
806 return volume;
807}
808
Glenn Kastenfff6d712012-01-12 16:38:12 -0800809bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810{
Glenn Kasten263709e2012-01-06 08:40:01 -0800811 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700812 return true;
813 }
814
Glenn Kasten6637baa2012-01-09 09:40:36 -0800815 AutoMutex lock(mLock);
816 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817}
818
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800819status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700820{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800821 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
823 // check calling permissions
824 if (!settingsAllowed()) {
825 return PERMISSION_DENIED;
826 }
827
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828 // ioHandle == 0 means the parameters are global to the audio hardware interface
829 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700830 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700831 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800832 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700833 AutoMutex lock(mHardwareLock);
834 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
835 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
836 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
837 status_t result = dev->set_parameters(dev, keyValuePairs.string());
838 final_result = result ?: final_result;
839 }
840 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800841 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700842 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
843 AudioParameter param = AudioParameter(keyValuePairs);
844 String8 value;
845 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700846 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
847 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700848 for (size_t i = 0; i < mRecordThreads.size(); i++) {
849 sp<RecordThread> thread = mRecordThreads.valueAt(i);
850 RecordThread::RecordTrack *track = thread->track();
851 if (track != NULL) {
852 audio_devices_t device = (audio_devices_t)(
853 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700854 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700855 thread->setEffectSuspended(FX_IID_AEC,
856 suspend,
857 track->sessionId());
858 thread->setEffectSuspended(FX_IID_NS,
859 suspend,
860 track->sessionId());
861 }
862 }
Eric Laurentbee53372011-08-29 12:42:48 -0700863 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700864 }
865 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700866 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700867 }
868
869 // hold a strong ref on thread in case closeOutput() or closeInput() is called
870 // and the thread is exited once the lock is released
871 sp<ThreadBase> thread;
872 {
873 Mutex::Autolock _l(mLock);
874 thread = checkPlaybackThread_l(ioHandle);
875 if (thread == NULL) {
876 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800877 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700878 // indicate output device change to all input threads for pre processing
879 AudioParameter param = AudioParameter(keyValuePairs);
880 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700881 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
882 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700883 for (size_t i = 0; i < mRecordThreads.size(); i++) {
884 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
885 }
886 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700887 }
888 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800889 if (thread != 0) {
890 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700891 }
892 return BAD_VALUE;
893}
894
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800895String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700896{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800897// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700898// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
899
Eric Laurenta4c5a552012-03-29 10:12:40 -0700900 Mutex::Autolock _l(mLock);
901
Mathias Agopian65ab4712010-07-14 17:59:35 -0700902 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700903 String8 out_s8;
904
Dima Zavin799a70e2011-04-18 16:57:27 -0700905 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800906 char *s;
907 {
908 AutoMutex lock(mHardwareLock);
909 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700910 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800911 s = dev->get_parameters(dev, keys.string());
912 mHardwareStatus = AUDIO_HW_IDLE;
913 }
John Grossmanef7740b2012-02-09 11:28:36 -0800914 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700915 free(s);
916 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700917 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700918 }
919
Mathias Agopian65ab4712010-07-14 17:59:35 -0700920 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
921 if (playbackThread != NULL) {
922 return playbackThread->getParameters(keys);
923 }
924 RecordThread *recordThread = checkRecordThread_l(ioHandle);
925 if (recordThread != NULL) {
926 return recordThread->getParameters(keys);
927 }
928 return String8("");
929}
930
Glenn Kastenf587ba52012-01-26 16:25:10 -0800931size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700932{
Eric Laurenta1884f92011-08-23 08:25:03 -0700933 status_t ret = initCheck();
934 if (ret != NO_ERROR) {
935 return 0;
936 }
937
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800938 AutoMutex lock(mHardwareLock);
939 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700940 struct audio_config config = {
941 sample_rate: sampleRate,
942 channel_mask: audio_channel_in_mask_from_count(channelCount),
943 format: format,
944 };
945 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800946 mHardwareStatus = AUDIO_HW_IDLE;
947 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700948}
949
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800950unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700951{
952 if (ioHandle == 0) {
953 return 0;
954 }
955
956 Mutex::Autolock _l(mLock);
957
958 RecordThread *recordThread = checkRecordThread_l(ioHandle);
959 if (recordThread != NULL) {
960 return recordThread->getInputFramesLost();
961 }
962 return 0;
963}
964
965status_t AudioFlinger::setVoiceVolume(float value)
966{
Eric Laurenta1884f92011-08-23 08:25:03 -0700967 status_t ret = initCheck();
968 if (ret != NO_ERROR) {
969 return ret;
970 }
971
Mathias Agopian65ab4712010-07-14 17:59:35 -0700972 // check calling permissions
973 if (!settingsAllowed()) {
974 return PERMISSION_DENIED;
975 }
976
977 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800978 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700979 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700980 mHardwareStatus = AUDIO_HW_IDLE;
981
982 return ret;
983}
984
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800985status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
986 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700987{
988 status_t status;
989
990 Mutex::Autolock _l(mLock);
991
992 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
993 if (playbackThread != NULL) {
994 return playbackThread->getRenderPosition(halFrames, dspFrames);
995 }
996
997 return BAD_VALUE;
998}
999
1000void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1001{
1002
1003 Mutex::Autolock _l(mLock);
1004
Glenn Kastenbb001922012-02-03 11:10:26 -08001005 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001006 if (mNotificationClients.indexOfKey(pid) < 0) {
1007 sp<NotificationClient> notificationClient = new NotificationClient(this,
1008 client,
1009 pid);
Steve Block3856b092011-10-20 11:56:00 +01001010 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001011
1012 mNotificationClients.add(pid, notificationClient);
1013
1014 sp<IBinder> binder = client->asBinder();
1015 binder->linkToDeath(notificationClient);
1016
1017 // the config change is always sent from playback or record threads to avoid deadlock
1018 // with AudioSystem::gLock
1019 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1020 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1021 }
1022
1023 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1024 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1025 }
1026 }
1027}
1028
1029void AudioFlinger::removeNotificationClient(pid_t pid)
1030{
1031 Mutex::Autolock _l(mLock);
1032
Glenn Kastena3b09252012-01-20 09:19:01 -08001033 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001034
Steve Block3856b092011-10-20 11:56:00 +01001035 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001036 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001037 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001038 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001039 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001040 ALOGV(" pid %d @ %d", ref->mPid, i);
1041 if (ref->mPid == pid) {
1042 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001043 mAudioSessionRefs.removeAt(i);
1044 delete ref;
1045 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001046 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001047 } else {
1048 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001049 }
1050 }
1051 if (removed) {
1052 purgeStaleEffects_l();
1053 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001054}
1055
1056// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001057void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058{
1059 size_t size = mNotificationClients.size();
1060 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001061 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1062 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001063 }
1064}
1065
1066// removeClient_l() must be called with AudioFlinger::mLock held
1067void AudioFlinger::removeClient_l(pid_t pid)
1068{
Steve Block3856b092011-10-20 11:56:00 +01001069 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001070 mClients.removeItem(pid);
1071}
1072
1073
1074// ----------------------------------------------------------------------------
1075
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001076AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1077 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001079 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001080 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001081 // mChannelMask
1082 mChannelCount(0),
1083 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1084 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001085 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001086 mDevice(device),
1087 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001088{
1089}
1090
1091AudioFlinger::ThreadBase::~ThreadBase()
1092{
1093 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001094 // do not lock the mutex in destructor
1095 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001096 if (mPowerManager != 0) {
1097 sp<IBinder> binder = mPowerManager->asBinder();
1098 binder->unlinkToDeath(mDeathRecipient);
1099 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001100}
1101
1102void AudioFlinger::ThreadBase::exit()
1103{
Steve Block3856b092011-10-20 11:56:00 +01001104 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001105 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001106 // This lock prevents the following race in thread (uniprocessor for illustration):
1107 // if (!exitPending()) {
1108 // // context switch from here to exit()
1109 // // exit() calls requestExit(), what exitPending() observes
1110 // // exit() calls signal(), which is dropped since no waiters
1111 // // context switch back from exit() to here
1112 // mWaitWorkCV.wait(...);
1113 // // now thread is hung
1114 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001115 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116 requestExit();
1117 mWaitWorkCV.signal();
1118 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001119 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1120 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001121 requestExitAndWait();
1122}
1123
Mathias Agopian65ab4712010-07-14 17:59:35 -07001124status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1125{
1126 status_t status;
1127
Steve Block3856b092011-10-20 11:56:00 +01001128 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001129 Mutex::Autolock _l(mLock);
1130
1131 mNewParameters.add(keyValuePairs);
1132 mWaitWorkCV.signal();
1133 // wait condition with timeout in case the thread loop has exited
1134 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001135 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001136 status = mParamStatus;
1137 mWaitWorkCV.signal();
1138 } else {
1139 status = TIMED_OUT;
1140 }
1141 return status;
1142}
1143
1144void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1145{
1146 Mutex::Autolock _l(mLock);
1147 sendConfigEvent_l(event, param);
1148}
1149
1150// sendConfigEvent_l() must be called with ThreadBase::mLock held
1151void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1152{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001153 ConfigEvent configEvent;
1154 configEvent.mEvent = event;
1155 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001156 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001157 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001158 mWaitWorkCV.signal();
1159}
1160
1161void AudioFlinger::ThreadBase::processConfigEvents()
1162{
1163 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001164 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001165 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001166 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001167 mConfigEvents.removeAt(0);
1168 // release mLock before locking AudioFlinger mLock: lock order is always
1169 // AudioFlinger then ThreadBase to avoid cross deadlock
1170 mLock.unlock();
1171 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001172 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001173 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001174 mLock.lock();
1175 }
1176 mLock.unlock();
1177}
1178
1179status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1180{
1181 const size_t SIZE = 256;
1182 char buffer[SIZE];
1183 String8 result;
1184
1185 bool locked = tryLock(mLock);
1186 if (!locked) {
1187 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1188 write(fd, buffer, strlen(buffer));
1189 }
1190
Eric Laurent612bbb52012-03-14 15:03:26 -07001191 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1192 result.append(buffer);
1193 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1194 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001195 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1196 result.append(buffer);
1197 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1198 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001199 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1200 result.append(buffer);
1201 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001202 result.append(buffer);
1203 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1204 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001205 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1206 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001207 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1208 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001209 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001210 result.append(buffer);
1211
1212 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1213 result.append(buffer);
1214 result.append(" Index Command");
1215 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1216 snprintf(buffer, SIZE, "\n %02d ", i);
1217 result.append(buffer);
1218 result.append(mNewParameters[i]);
1219 }
1220
1221 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1222 result.append(buffer);
1223 snprintf(buffer, SIZE, " Index event param\n");
1224 result.append(buffer);
1225 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001226 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001227 result.append(buffer);
1228 }
1229 result.append("\n");
1230
1231 write(fd, result.string(), result.size());
1232
1233 if (locked) {
1234 mLock.unlock();
1235 }
1236 return NO_ERROR;
1237}
1238
Eric Laurent1d2bff02011-07-24 17:49:51 -07001239status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1240{
1241 const size_t SIZE = 256;
1242 char buffer[SIZE];
1243 String8 result;
1244
1245 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1246 write(fd, buffer, strlen(buffer));
1247
1248 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1249 sp<EffectChain> chain = mEffectChains[i];
1250 if (chain != 0) {
1251 chain->dump(fd, args);
1252 }
1253 }
1254 return NO_ERROR;
1255}
1256
Eric Laurentfeb0db62011-07-22 09:04:31 -07001257void AudioFlinger::ThreadBase::acquireWakeLock()
1258{
1259 Mutex::Autolock _l(mLock);
1260 acquireWakeLock_l();
1261}
1262
1263void AudioFlinger::ThreadBase::acquireWakeLock_l()
1264{
1265 if (mPowerManager == 0) {
1266 // use checkService() to avoid blocking if power service is not up yet
1267 sp<IBinder> binder =
1268 defaultServiceManager()->checkService(String16("power"));
1269 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001270 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001271 } else {
1272 mPowerManager = interface_cast<IPowerManager>(binder);
1273 binder->linkToDeath(mDeathRecipient);
1274 }
1275 }
1276 if (mPowerManager != 0) {
1277 sp<IBinder> binder = new BBinder();
1278 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1279 binder,
1280 String16(mName));
1281 if (status == NO_ERROR) {
1282 mWakeLockToken = binder;
1283 }
Steve Block3856b092011-10-20 11:56:00 +01001284 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001285 }
1286}
1287
1288void AudioFlinger::ThreadBase::releaseWakeLock()
1289{
1290 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001291 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001292}
1293
1294void AudioFlinger::ThreadBase::releaseWakeLock_l()
1295{
1296 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001297 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001298 if (mPowerManager != 0) {
1299 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1300 }
1301 mWakeLockToken.clear();
1302 }
1303}
1304
1305void AudioFlinger::ThreadBase::clearPowerManager()
1306{
1307 Mutex::Autolock _l(mLock);
1308 releaseWakeLock_l();
1309 mPowerManager.clear();
1310}
1311
1312void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1313{
1314 sp<ThreadBase> thread = mThread.promote();
1315 if (thread != 0) {
1316 thread->clearPowerManager();
1317 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001318 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001319}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001320
Eric Laurent59255e42011-07-27 19:49:51 -07001321void AudioFlinger::ThreadBase::setEffectSuspended(
1322 const effect_uuid_t *type, bool suspend, int sessionId)
1323{
1324 Mutex::Autolock _l(mLock);
1325 setEffectSuspended_l(type, suspend, sessionId);
1326}
1327
1328void AudioFlinger::ThreadBase::setEffectSuspended_l(
1329 const effect_uuid_t *type, bool suspend, int sessionId)
1330{
Glenn Kasten090f0192012-01-30 13:00:02 -08001331 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001332 if (chain != 0) {
1333 if (type != NULL) {
1334 chain->setEffectSuspended_l(type, suspend);
1335 } else {
1336 chain->setEffectSuspendedAll_l(suspend);
1337 }
1338 }
1339
1340 updateSuspendedSessions_l(type, suspend, sessionId);
1341}
1342
1343void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1344{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001345 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001346 if (index < 0) {
1347 return;
1348 }
1349
1350 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1351 mSuspendedSessions.editValueAt(index);
1352
1353 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001354 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001355 for (int j = 0; j < desc->mRefCount; j++) {
1356 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1357 chain->setEffectSuspendedAll_l(true);
1358 } else {
Steve Block3856b092011-10-20 11:56:00 +01001359 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001360 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001361 chain->setEffectSuspended_l(&desc->mType, true);
1362 }
1363 }
1364 }
1365}
1366
Eric Laurent59255e42011-07-27 19:49:51 -07001367void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1368 bool suspend,
1369 int sessionId)
1370{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001371 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001372
1373 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1374
1375 if (suspend) {
1376 if (index >= 0) {
1377 sessionEffects = mSuspendedSessions.editValueAt(index);
1378 } else {
1379 mSuspendedSessions.add(sessionId, sessionEffects);
1380 }
1381 } else {
1382 if (index < 0) {
1383 return;
1384 }
1385 sessionEffects = mSuspendedSessions.editValueAt(index);
1386 }
1387
1388
1389 int key = EffectChain::kKeyForSuspendAll;
1390 if (type != NULL) {
1391 key = type->timeLow;
1392 }
1393 index = sessionEffects.indexOfKey(key);
1394
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001395 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001396 if (suspend) {
1397 if (index >= 0) {
1398 desc = sessionEffects.valueAt(index);
1399 } else {
1400 desc = new SuspendedSessionDesc();
1401 if (type != NULL) {
1402 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1403 }
1404 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001405 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001406 }
1407 desc->mRefCount++;
1408 } else {
1409 if (index < 0) {
1410 return;
1411 }
1412 desc = sessionEffects.valueAt(index);
1413 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001414 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001415 sessionEffects.removeItemsAt(index);
1416 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001417 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001418 sessionId);
1419 mSuspendedSessions.removeItem(sessionId);
1420 }
1421 }
1422 }
1423 if (!sessionEffects.isEmpty()) {
1424 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1425 }
1426}
1427
1428void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1429 bool enabled,
1430 int sessionId)
1431{
1432 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001433 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1434}
Eric Laurent59255e42011-07-27 19:49:51 -07001435
Eric Laurenta85a74a2011-10-19 11:44:54 -07001436void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1437 bool enabled,
1438 int sessionId)
1439{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001440 if (mType != RECORD) {
1441 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1442 // another session. This gives the priority to well behaved effect control panels
1443 // and applications not using global effects.
1444 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1445 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1446 }
1447 }
Eric Laurent59255e42011-07-27 19:49:51 -07001448
1449 sp<EffectChain> chain = getEffectChain_l(sessionId);
1450 if (chain != 0) {
1451 chain->checkSuspendOnEffectEnabled(effect, enabled);
1452 }
1453}
1454
Mathias Agopian65ab4712010-07-14 17:59:35 -07001455// ----------------------------------------------------------------------------
1456
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001457AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1458 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001459 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001460 uint32_t device,
1461 type_t type)
1462 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001463 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1464 // Assumes constructor is called by AudioFlinger with it's mLock held,
1465 // but it would be safer to explicitly pass initial masterMute as parameter
1466 mMasterMute(audioFlinger->masterMute_l()),
1467 // mStreamTypes[] initialized in constructor body
1468 mOutput(output),
1469 // Assumes constructor is called by AudioFlinger with it's mLock held,
1470 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001471 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001472 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001473 mMixerStatus(MIXER_IDLE),
Glenn Kasten66fcab92012-02-24 14:59:21 -08001474 mPrevMixerStatus(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001475 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
1476 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1477 mFastTrackNewMask(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001478{
Glenn Kasten58912562012-04-03 10:45:00 -07001479#if !LOG_NDEBUG
1480 memset(mFastTrackNewArray, 0, sizeof(mFastTrackNewArray));
1481#endif
Glenn Kasten480b4682012-02-28 12:30:08 -08001482 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001483
Mathias Agopian65ab4712010-07-14 17:59:35 -07001484 readOutputParameters();
1485
Glenn Kasten263709e2012-01-06 08:40:01 -08001486 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001487 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1488 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1489 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001490 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1491 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001492 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001493 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1494 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001495}
1496
1497AudioFlinger::PlaybackThread::~PlaybackThread()
1498{
1499 delete [] mMixBuffer;
1500}
1501
1502status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1503{
1504 dumpInternals(fd, args);
1505 dumpTracks(fd, args);
1506 dumpEffectChains(fd, args);
1507 return NO_ERROR;
1508}
1509
1510status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1511{
1512 const size_t SIZE = 256;
1513 char buffer[SIZE];
1514 String8 result;
1515
Glenn Kasten58912562012-04-03 10:45:00 -07001516 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1517 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1518 const stream_type_t *st = &mStreamTypes[i];
1519 if (i > 0) {
1520 result.appendFormat(", ");
1521 }
1522 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1523 if (st->mute) {
1524 result.append("M");
1525 }
1526 }
1527 result.append("\n");
1528 write(fd, result.string(), result.length());
1529 result.clear();
1530
Mathias Agopian65ab4712010-07-14 17:59:35 -07001531 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1532 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001533 result.append(" Name Client Type Fmt Chn mask Session Frames S M F SRate L dB R dB "
1534 "Server User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001535 for (size_t i = 0; i < mTracks.size(); ++i) {
1536 sp<Track> track = mTracks[i];
1537 if (track != 0) {
1538 track->dump(buffer, SIZE);
1539 result.append(buffer);
1540 }
1541 }
1542
1543 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1544 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001545 result.append(" Name Client Type Fmt Chn mask Session Frames S M F SRate L dB R dB "
1546 "Server User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001547 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001548 sp<Track> track = mActiveTracks[i].promote();
1549 if (track != 0) {
1550 track->dump(buffer, SIZE);
1551 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001552 }
1553 }
1554 write(fd, result.string(), result.size());
1555 return NO_ERROR;
1556}
1557
Mathias Agopian65ab4712010-07-14 17:59:35 -07001558status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1559{
1560 const size_t SIZE = 256;
1561 char buffer[SIZE];
1562 String8 result;
1563
1564 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1565 result.append(buffer);
1566 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1567 result.append(buffer);
1568 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1569 result.append(buffer);
1570 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1571 result.append(buffer);
1572 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1573 result.append(buffer);
1574 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1575 result.append(buffer);
1576 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1577 result.append(buffer);
1578 write(fd, result.string(), result.size());
1579
1580 dumpBase(fd, args);
1581
1582 return NO_ERROR;
1583}
1584
1585// Thread virtuals
1586status_t AudioFlinger::PlaybackThread::readyToRun()
1587{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001588 status_t status = initCheck();
1589 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001590 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001591 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001592 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001593 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001594 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001595}
1596
1597void AudioFlinger::PlaybackThread::onFirstRef()
1598{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001599 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600}
1601
1602// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001603sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001604 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001605 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001606 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001607 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001608 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609 int frameCount,
1610 const sp<IMemory>& sharedBuffer,
1611 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001612 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001613 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614 status_t *status)
1615{
1616 sp<Track> track;
1617 status_t lStatus;
1618
Glenn Kasten73d22752012-03-19 13:38:30 -07001619 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1620
1621 // client expresses a preference for FAST, but we get the final say
1622 if ((flags & IAudioFlinger::TRACK_FAST) &&
1623 !(
1624 // not timed
1625 (!isTimed) &&
1626 // either of these use cases:
1627 (
1628 // use case 1: shared buffer with any frame count
1629 (
1630 (sharedBuffer != 0)
1631 ) ||
Glenn Kasten58912562012-04-03 10:45:00 -07001632 // use case 2: callback handler and frame count at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001633 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001634 (tid != -1) &&
Glenn Kasten73d22752012-03-19 13:38:30 -07001635 // FIXME supported frame counts should not be hard-coded
Glenn Kasten58912562012-04-03 10:45:00 -07001636 frameCount >= (int) mFrameCount // FIXME int cast is due to wrong parameter type
Glenn Kasten73d22752012-03-19 13:38:30 -07001637 )
1638 ) &&
1639 // PCM data
1640 audio_is_linear_pcm(format) &&
1641 // mono or stereo
1642 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1643 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001644#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001645 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001646 (sampleRate == mSampleRate) &&
1647#endif
1648 // normal mixer has an associated fast mixer
1649 hasFastMixer() &&
1650 // there are sufficient fast track slots available
1651 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001652 // FIXME test that MixerThread for this fast track has a capable output HAL
1653 // FIXME add a permission test also?
1654 ) ) {
Glenn Kasten58912562012-04-03 10:45:00 -07001655 ALOGW("AUDIO_POLICY_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1656 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1657 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1658 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1659 audio_is_linear_pcm(format),
1660 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001661 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten58912562012-04-03 10:45:00 -07001662 if (0 < frameCount && frameCount < (int) mNormalFrameCount) {
1663 frameCount = mNormalFrameCount;
1664 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001665 }
1666
Mathias Agopian65ab4712010-07-14 17:59:35 -07001667 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001668 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1669 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001670 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001671 "for output %p with format %d",
1672 sampleRate, format, channelMask, mOutput, mFormat);
1673 lStatus = BAD_VALUE;
1674 goto Exit;
1675 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001676 }
1677 } else {
1678 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1679 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001680 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001681 lStatus = BAD_VALUE;
1682 goto Exit;
1683 }
1684 }
1685
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001686 lStatus = initCheck();
1687 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001688 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001689 goto Exit;
1690 }
1691
1692 { // scope for mLock
1693 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001694
1695 // all tracks in same audio session must share the same routing strategy otherwise
1696 // conflicts will happen when tracks are moved from one output to another by audio policy
1697 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001698 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001699 for (size_t i = 0; i < mTracks.size(); ++i) {
1700 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001701 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001702 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001703 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001704 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001705 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001706 lStatus = BAD_VALUE;
1707 goto Exit;
1708 }
1709 }
1710 }
1711
John Grossman4ff14ba2012-02-08 16:37:41 -08001712 if (!isTimed) {
1713 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001714 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001715 } else {
1716 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1717 channelMask, frameCount, sharedBuffer, sessionId);
1718 }
1719 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001720 lStatus = NO_MEMORY;
1721 goto Exit;
1722 }
1723 mTracks.add(track);
1724
1725 sp<EffectChain> chain = getEffectChain_l(sessionId);
1726 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001727 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001729 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001730 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001731 }
1732 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001733
1734#ifdef HAVE_REQUEST_PRIORITY
1735 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1736 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1737 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1738 // so ask activity manager to do this on our behalf
1739 int err = requestPriority(callingPid, tid, 1);
1740 if (err != 0) {
1741 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1742 1, callingPid, tid, err);
1743 }
1744 }
1745#endif
1746
Mathias Agopian65ab4712010-07-14 17:59:35 -07001747 lStatus = NO_ERROR;
1748
1749Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001750 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001751 *status = lStatus;
1752 }
1753 return track;
1754}
1755
1756uint32_t AudioFlinger::PlaybackThread::latency() const
1757{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001758 Mutex::Autolock _l(mLock);
1759 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001760 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001761 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001762 return 0;
1763 }
1764}
1765
Glenn Kasten6637baa2012-01-09 09:40:36 -08001766void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001767{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001768 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001770}
1771
Glenn Kasten6637baa2012-01-09 09:40:36 -08001772void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001774 Mutex::Autolock _l(mLock);
1775 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776}
1777
Glenn Kasten6637baa2012-01-09 09:40:36 -08001778void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001780 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001781 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001782}
1783
Glenn Kasten6637baa2012-01-09 09:40:36 -08001784void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001785{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001786 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001787 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001788}
1789
Glenn Kastenfff6d712012-01-12 16:38:12 -08001790float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001791{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001792 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001793 return mStreamTypes[stream].volume;
1794}
1795
Mathias Agopian65ab4712010-07-14 17:59:35 -07001796// addTrack_l() must be called with ThreadBase::mLock held
1797status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1798{
1799 status_t status = ALREADY_EXISTS;
1800
1801 // set retry count for buffer fill
1802 track->mRetryCount = kMaxTrackStartupRetries;
1803 if (mActiveTracks.indexOf(track) < 0) {
1804 // the track is newly added, make sure it fills up all its
1805 // buffers before playing. This is to ensure the client will
1806 // effectively get the latency it requested.
1807 track->mFillingUpStatus = Track::FS_FILLING;
1808 track->mResetDone = false;
1809 mActiveTracks.add(track);
1810 if (track->mainBuffer() != mMixBuffer) {
1811 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1812 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001813 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001814 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001815 }
1816 }
1817
1818 status = NO_ERROR;
1819 }
1820
Steve Block3856b092011-10-20 11:56:00 +01001821 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001822 mWaitWorkCV.broadcast();
1823
1824 return status;
1825}
1826
1827// destroyTrack_l() must be called with ThreadBase::mLock held
1828void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1829{
1830 track->mState = TrackBase::TERMINATED;
1831 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001832 removeTrack_l(track);
1833 }
1834}
1835
1836void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1837{
1838 mTracks.remove(track);
1839 deleteTrackName_l(track->name());
1840 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1841 if (chain != 0) {
1842 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843 }
1844}
1845
1846String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1847{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001848 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001849 char *s;
1850
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001851 Mutex::Autolock _l(mLock);
1852 if (initCheck() != NO_ERROR) {
1853 return out_s8;
1854 }
1855
Dima Zavin799a70e2011-04-18 16:57:27 -07001856 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001857 out_s8 = String8(s);
1858 free(s);
1859 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001860}
1861
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001862// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1864 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001865 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001866
Steve Block3856b092011-10-20 11:56:00 +01001867 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868
1869 switch (event) {
1870 case AudioSystem::OUTPUT_OPENED:
1871 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001872 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001873 desc.samplingRate = mSampleRate;
1874 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001875 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001876 desc.latency = latency();
1877 param2 = &desc;
1878 break;
1879
1880 case AudioSystem::STREAM_CONFIG_CHANGED:
1881 param2 = &param;
1882 case AudioSystem::OUTPUT_CLOSED:
1883 default:
1884 break;
1885 }
1886 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1887}
1888
1889void AudioFlinger::PlaybackThread::readOutputParameters()
1890{
Dima Zavin799a70e2011-04-18 16:57:27 -07001891 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001892 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1893 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001894 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001895 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001896 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001897 if (mFrameCount & 15) {
1898 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1899 mFrameCount);
1900 }
1901
1902 // Calculate size of normal mix buffer
1903 if (mType == MIXER) {
1904 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1905 mNormalFrameCount = ((minNormalFrameCount + mFrameCount - 1) / mFrameCount) * mFrameCount;
1906 if (mNormalFrameCount & 15) {
1907 ALOGW("Normal mix buffer size is %u frames but AudioMixer requires multiples of 16 "
1908 "frames", mNormalFrameCount);
1909 }
1910 } else {
1911 mNormalFrameCount = mFrameCount;
1912 }
1913 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001914
1915 // FIXME - Current mixer implementation only supports stereo output: Always
1916 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001917 delete[] mMixBuffer;
Glenn Kasten58912562012-04-03 10:45:00 -07001918 mMixBuffer = new int16_t[mNormalFrameCount * 2];
1919 memset(mMixBuffer, 0, mNormalFrameCount * 2 * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001920
Eric Laurentde070132010-07-13 04:45:46 -07001921 // force reconfiguration of effect chains and engines to take new buffer size and audio
1922 // parameters into account
1923 // Note that mLock is not held when readOutputParameters() is called from the constructor
1924 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1925 // matter.
1926 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1927 Vector< sp<EffectChain> > effectChains = mEffectChains;
1928 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001929 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001930 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001931}
1932
1933status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1934{
Glenn Kastena0d68332012-01-27 16:47:15 -08001935 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001936 return BAD_VALUE;
1937 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001938 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001939 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001940 return INVALID_OPERATION;
1941 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001942 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001943
Dima Zavin799a70e2011-04-18 16:57:27 -07001944 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001945}
1946
Eric Laurent39e94f82010-07-28 01:32:47 -07001947uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001948{
1949 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001950 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001952 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001953 }
1954
1955 for (size_t i = 0; i < mTracks.size(); ++i) {
1956 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001957 if (sessionId == track->sessionId() &&
1958 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001959 result |= TRACK_SESSION;
1960 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001961 }
1962 }
1963
Eric Laurent39e94f82010-07-28 01:32:47 -07001964 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001965}
1966
Eric Laurentde070132010-07-13 04:45:46 -07001967uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1968{
Dima Zavinfce7a472011-04-19 22:30:36 -07001969 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001970 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001971 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1972 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001973 }
1974 for (size_t i = 0; i < mTracks.size(); i++) {
1975 sp<Track> track = mTracks[i];
1976 if (sessionId == track->sessionId() &&
1977 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001978 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001979 }
1980 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001981 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001982}
1983
Mathias Agopian65ab4712010-07-14 17:59:35 -07001984
Glenn Kastenaed850d2012-01-26 09:46:34 -08001985AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001986{
1987 Mutex::Autolock _l(mLock);
1988 return mOutput;
1989}
1990
1991AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1992{
1993 Mutex::Autolock _l(mLock);
1994 AudioStreamOut *output = mOutput;
1995 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07001996 // FIXME FastMixer might also have a raw ptr to mOutputSink;
1997 // must push a NULL and wait for ack
1998 mOutputSink.clear();
1999 mPipeSink.clear();
2000 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002001 return output;
2002}
2003
2004// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002005audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002006{
2007 if (mOutput == NULL) {
2008 return NULL;
2009 }
2010 return &mOutput->stream->common;
2011}
2012
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002013uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002014{
2015 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
2016 // decoding and transfer time. So sleeping for half of the latency would likely cause
2017 // underruns
2018 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002019 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002020 } else {
2021 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
2022 }
2023}
2024
Eric Laurenta011e352012-03-29 15:51:43 -07002025status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2026{
2027 if (!isValidSyncEvent(event)) {
2028 return BAD_VALUE;
2029 }
2030
2031 Mutex::Autolock _l(mLock);
2032
2033 for (size_t i = 0; i < mTracks.size(); ++i) {
2034 sp<Track> track = mTracks[i];
2035 if (event->triggerSession() == track->sessionId()) {
2036 track->setSyncEvent(event);
2037 return NO_ERROR;
2038 }
2039 }
2040
2041 return NAME_NOT_FOUND;
2042}
2043
2044bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2045{
2046 switch (event->type()) {
2047 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2048 return true;
2049 default:
2050 break;
2051 }
2052 return false;
2053}
2054
Mathias Agopian65ab4712010-07-14 17:59:35 -07002055// ----------------------------------------------------------------------------
2056
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002057AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002058 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002059 : PlaybackThread(audioFlinger, output, id, device, type),
2060 // mAudioMixer below
2061#ifdef SOAKER
2062 mSoaker(NULL),
2063#endif
2064 // mFastMixer below
2065 mFastMixerFutex(0)
2066 // mOutputSink below
2067 // mPipeSink below
2068 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002069{
Glenn Kasten58912562012-04-03 10:45:00 -07002070 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2071 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2072 "mFrameCount=%d, mNormalFrameCount=%d",
2073 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2074 mNormalFrameCount);
2075 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2076
Mathias Agopian65ab4712010-07-14 17:59:35 -07002077 // FIXME - Current mixer implementation only supports stereo output
2078 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002079 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002080 }
Glenn Kasten58912562012-04-03 10:45:00 -07002081
2082 // create an NBAIO sink for the HAL output stream, and negotiate
2083 mOutputSink = new AudioStreamOutSink(output->stream);
2084 size_t numCounterOffers = 0;
2085 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2086 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2087 ALOG_ASSERT(index == 0);
2088
2089 // initialize fast mixer if needed
2090 if (mFrameCount < mNormalFrameCount) {
2091
2092 // create a MonoPipe to connect our submix to FastMixer
2093 NBAIO_Format format = mOutputSink->format();
2094 // frame count will be rounded up to a power of 2, so this formula should work well
2095 MonoPipe *monoPipe = new MonoPipe((mNormalFrameCount * 3) / 2, format,
2096 true /*writeCanBlock*/);
2097 const NBAIO_Format offers[1] = {format};
2098 size_t numCounterOffers = 0;
2099 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2100 ALOG_ASSERT(index == 0);
2101 mPipeSink = monoPipe;
2102
2103#ifdef SOAKER
2104 // create a soaker as workaround for governor issues
2105 mSoaker = new Soaker();
2106 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE
2107 mSoaker->run("Soaker", PRIORITY_LOWEST);
2108#endif
2109
2110 // create fast mixer and configure it initially with just one fast track for our submix
2111 mFastMixer = new FastMixer();
2112 FastMixerStateQueue *sq = mFastMixer->sq();
2113 FastMixerState *state = sq->begin();
2114 FastTrack *fastTrack = &state->mFastTracks[0];
2115 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2116 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2117 fastTrack->mVolumeProvider = NULL;
2118 fastTrack->mGeneration++;
2119 state->mFastTracksGen++;
2120 state->mTrackMask = 1;
2121 // fast mixer will use the HAL output sink
2122 state->mOutputSink = mOutputSink.get();
2123 state->mOutputSinkGen++;
2124 state->mFrameCount = mFrameCount;
2125 state->mCommand = FastMixerState::COLD_IDLE;
2126 // already done in constructor initialization list
2127 //mFastMixerFutex = 0;
2128 state->mColdFutexAddr = &mFastMixerFutex;
2129 state->mColdGen++;
2130 state->mDumpState = &mFastMixerDumpState;
2131 sq->end();
2132 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2133
2134 // start the fast mixer
2135 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2136#ifdef HAVE_REQUEST_PRIORITY
2137 pid_t tid = mFastMixer->getTid();
2138 int err = requestPriority(getpid_cached, tid, 2);
2139 if (err != 0) {
2140 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2141 2, getpid_cached, tid, err);
2142 }
2143#endif
2144
2145 } else {
2146 mFastMixer = NULL;
2147 }
2148 mNormalSink = mOutputSink;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002149}
2150
2151AudioFlinger::MixerThread::~MixerThread()
2152{
Glenn Kasten58912562012-04-03 10:45:00 -07002153 if (mFastMixer != NULL) {
2154 FastMixerStateQueue *sq = mFastMixer->sq();
2155 FastMixerState *state = sq->begin();
2156 if (state->mCommand == FastMixerState::COLD_IDLE) {
2157 int32_t old = android_atomic_inc(&mFastMixerFutex);
2158 if (old == -1) {
2159 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2160 }
2161 }
2162 state->mCommand = FastMixerState::EXIT;
2163 sq->end();
2164 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2165 mFastMixer->join();
2166 // Though the fast mixer thread has exited, it's state queue is still valid.
2167 // We'll use that extract the final state which contains one remaining fast track
2168 // corresponding to our sub-mix.
2169 state = sq->begin();
2170 ALOG_ASSERT(state->mTrackMask == 1);
2171 FastTrack *fastTrack = &state->mFastTracks[0];
2172 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2173 delete fastTrack->mBufferProvider;
2174 sq->end(false /*didModify*/);
2175 delete mFastMixer;
2176#ifdef SOAKER
2177 if (mSoaker != NULL) {
2178 mSoaker->requestExitAndWait();
2179 }
2180 delete mSoaker;
2181#endif
2182 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002183 delete mAudioMixer;
2184}
2185
Glenn Kasten83efdd02012-02-24 07:21:32 -08002186class CpuStats {
2187public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002188 CpuStats();
2189 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002190#ifdef DEBUG_CPU_USAGE
2191private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002192 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2193 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2194
2195 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2196
2197 int mCpuNum; // thread's current CPU number
2198 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002199#endif
2200};
2201
Glenn Kasten190a46f2012-03-06 11:27:10 -08002202CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002203#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002204 : mCpuNum(-1), mCpukHz(-1)
2205#endif
2206{
2207}
2208
2209void CpuStats::sample(const String8 &title) {
2210#ifdef DEBUG_CPU_USAGE
2211 // get current thread's delta CPU time in wall clock ns
2212 double wcNs;
2213 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2214
2215 // record sample for wall clock statistics
2216 if (valid) {
2217 mWcStats.sample(wcNs);
2218 }
2219
2220 // get the current CPU number
2221 int cpuNum = sched_getcpu();
2222
2223 // get the current CPU frequency in kHz
2224 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2225
2226 // check if either CPU number or frequency changed
2227 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2228 mCpuNum = cpuNum;
2229 mCpukHz = cpukHz;
2230 // ignore sample for purposes of cycles
2231 valid = false;
2232 }
2233
2234 // if no change in CPU number or frequency, then record sample for cycle statistics
2235 if (valid && mCpukHz > 0) {
2236 double cycles = wcNs * cpukHz * 0.000001;
2237 mHzStats.sample(cycles);
2238 }
2239
2240 unsigned n = mWcStats.n();
2241 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002242 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002243 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002244 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2245 double perLoop = elapsed / (double) n;
2246 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002247 double perLoop1k = perLoop * 0.001;
2248 double mean = mWcStats.mean();
2249 double stddev = mWcStats.stddev();
2250 double minimum = mWcStats.minimum();
2251 double maximum = mWcStats.maximum();
2252 double meanCycles = mHzStats.mean();
2253 double stddevCycles = mHzStats.stddev();
2254 double minCycles = mHzStats.minimum();
2255 double maxCycles = mHzStats.maximum();
2256 mCpuUsage.resetElapsed();
2257 mWcStats.reset();
2258 mHzStats.reset();
2259 ALOGD("CPU usage for %s over past %.1f secs\n"
2260 " (%u mixer loops at %.1f mean ms per loop):\n"
2261 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2262 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2263 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2264 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002265 elapsed * .000000001, n, perLoop * .000001,
2266 mean * .001,
2267 stddev * .001,
2268 minimum * .001,
2269 maximum * .001,
2270 mean / perLoop100,
2271 stddev / perLoop100,
2272 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002273 maximum / perLoop100,
2274 meanCycles / perLoop1k,
2275 stddevCycles / perLoop1k,
2276 minCycles / perLoop1k,
2277 maxCycles / perLoop1k);
2278
Glenn Kasten83efdd02012-02-24 07:21:32 -08002279 }
2280 }
2281#endif
2282};
2283
Glenn Kasten37d825e2012-02-24 07:21:48 -08002284void AudioFlinger::PlaybackThread::checkSilentMode_l()
2285{
2286 if (!mMasterMute) {
2287 char value[PROPERTY_VALUE_MAX];
2288 if (property_get("ro.audio.silent", value, "0") > 0) {
2289 char *endptr;
2290 unsigned long ul = strtoul(value, &endptr, 0);
2291 if (*endptr == '\0' && ul != 0) {
2292 ALOGD("Silence is golden");
2293 // The setprop command will not allow a property to be changed after
2294 // the first time it is set, so we don't have to worry about un-muting.
2295 setMasterMute_l(true);
2296 }
2297 }
2298 }
2299}
2300
Glenn Kasten000f0e32012-03-01 17:10:56 -08002301bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002302{
2303 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002304
Glenn Kasten000f0e32012-03-01 17:10:56 -08002305 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002306
2307 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002308 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002309if (mType == MIXER) {
2310 longStandbyExit = false;
2311}
Glenn Kasten688a6402012-02-29 07:57:06 -08002312
Glenn Kasten000f0e32012-03-01 17:10:56 -08002313 // DUPLICATING
2314 // FIXME could this be made local to while loop?
2315 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002316
Glenn Kasten66fcab92012-02-24 14:59:21 -08002317 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002318 sleepTime = idleSleepTime;
2319
2320if (mType == MIXER) {
2321 sleepTimeShift = 0;
2322}
2323
Glenn Kasten83efdd02012-02-24 07:21:32 -08002324 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002325 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002326
Eric Laurentfeb0db62011-07-22 09:04:31 -07002327 acquireWakeLock();
2328
Mathias Agopian65ab4712010-07-14 17:59:35 -07002329 while (!exitPending())
2330 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002331 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002332
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002333 Vector< sp<EffectChain> > effectChains;
2334
Mathias Agopian65ab4712010-07-14 17:59:35 -07002335 processConfigEvents();
2336
Mathias Agopian65ab4712010-07-14 17:59:35 -07002337 { // scope for mLock
2338
2339 Mutex::Autolock _l(mLock);
2340
2341 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002342 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002343 }
2344
Glenn Kastenfa26a852012-03-06 11:28:04 -08002345 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002346
Mathias Agopian65ab4712010-07-14 17:59:35 -07002347 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002348 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002349 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002350 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002351
2352 threadLoop_standby();
2353
Mathias Agopian65ab4712010-07-14 17:59:35 -07002354 mStandby = true;
2355 mBytesWritten = 0;
2356 }
2357
Glenn Kasten3e074702012-02-28 18:40:35 -08002358 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002359 // we're about to wait, flush the binder command buffer
2360 IPCThreadState::self()->flushCommands();
2361
Glenn Kastenfa26a852012-03-06 11:28:04 -08002362 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002363
Mathias Agopian65ab4712010-07-14 17:59:35 -07002364 if (exitPending()) break;
2365
Eric Laurentfeb0db62011-07-22 09:04:31 -07002366 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002367 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002368 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002369 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002370 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002371 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002372
Eric Laurent27741442012-01-17 19:20:12 -08002373 mPrevMixerStatus = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002374
Glenn Kasten37d825e2012-02-24 07:21:48 -08002375 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002376
Glenn Kasten000f0e32012-03-01 17:10:56 -08002377 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002378 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002379 if (mType == MIXER) {
2380 sleepTimeShift = 0;
2381 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002382
Mathias Agopian65ab4712010-07-14 17:59:35 -07002383 continue;
2384 }
2385 }
2386
Glenn Kastenfec279f2012-03-08 07:47:15 -08002387 mixer_state newMixerStatus = prepareTracks_l(&tracksToRemove);
2388 // Shift in the new status; this could be a queue if it's
2389 // useful to filter the mixer status over several cycles.
2390 mPrevMixerStatus = mMixerStatus;
2391 mMixerStatus = newMixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002392
2393 // prevent any changes in effect chain list and in each effect chain
2394 // during mixing and effect process as the audio buffers could be deleted
2395 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002396 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002397 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002398
Glenn Kastenfec279f2012-03-08 07:47:15 -08002399 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002400 threadLoop_mix();
2401 } else {
2402 threadLoop_sleepTime();
2403 }
2404
2405 if (mSuspended > 0) {
2406 sleepTime = suspendSleepTimeUs();
2407 }
2408
2409 // only process effects if we're going to write
2410 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002411 for (size_t i = 0; i < effectChains.size(); i ++) {
2412 effectChains[i]->process_l();
2413 }
2414 }
2415
2416 // enable changes in effect chain
2417 unlockEffectChains(effectChains);
2418
2419 // sleepTime == 0 means we must write to audio hardware
2420 if (sleepTime == 0) {
2421
2422 threadLoop_write();
2423
2424if (mType == MIXER) {
2425 // write blocked detection
2426 nsecs_t now = systemTime();
2427 nsecs_t delta = now - mLastWriteTime;
2428 if (!mStandby && delta > maxPeriod) {
2429 mNumDelayedWrites++;
2430 if ((now - lastWarning) > kWarningThrottleNs) {
2431 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2432 ns2ms(delta), mNumDelayedWrites, this);
2433 lastWarning = now;
2434 }
2435 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2436 // a different threshold. Or completely removed for what it is worth anyway...
2437 if (mStandby) {
2438 longStandbyExit = true;
2439 }
2440 }
2441}
2442
2443 mStandby = false;
2444 } else {
2445 usleep(sleepTime);
2446 }
2447
Glenn Kasten58912562012-04-03 10:45:00 -07002448 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002449 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002450 // same lock. This will also mutate and push a new fast mixer state.
2451 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002452 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002453
Glenn Kastenfa26a852012-03-06 11:28:04 -08002454 // FIXME I don't understand the need for this here;
2455 // it was in the original code but maybe the
2456 // assignment in saveOutputTracks() makes this unnecessary?
2457 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002458
2459 // Effect chains will be actually deleted here if they were removed from
2460 // mEffectChains list during mixing or effects processing
2461 effectChains.clear();
2462
2463 // FIXME Note that the above .clear() is no longer necessary since effectChains
2464 // is now local to this block, but will keep it for now (at least until merge done).
2465 }
2466
2467if (mType == MIXER || mType == DIRECT) {
2468 // put output stream into standby mode
2469 if (!mStandby) {
2470 mOutput->stream->common.standby(&mOutput->stream->common);
2471 }
2472}
2473if (mType == DUPLICATING) {
2474 // for DuplicatingThread, standby mode is handled by the outputTracks
2475}
2476
2477 releaseWakeLock();
2478
2479 ALOGV("Thread %p type %d exiting", this, mType);
2480 return false;
2481}
2482
Glenn Kasten58912562012-04-03 10:45:00 -07002483// FIXME This method needs a better name.
2484// It pushes a new fast mixer state and returns (via tracksToRemove) a set of tracks to remove.
2485void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2486{
2487 // were any of the removed tracks also fast tracks?
2488 unsigned removedMask = 0;
2489 for (size_t i = 0; i < tracksToRemove.size(); ++i) {
2490 if (tracksToRemove[i]->isFastTrack()) {
2491 int j = tracksToRemove[i]->mFastIndex;
2492 ALOG_ASSERT(0 < j && j < FastMixerState::kMaxFastTracks);
2493 removedMask |= 1 << j;
2494 }
2495 }
2496 Track* newArray[FastMixerState::kMaxFastTracks];
2497 unsigned newMask;
2498 {
2499 AutoMutex _l(mLock);
2500 mFastTrackAvailMask |= removedMask;
2501 newMask = mFastTrackNewMask;
2502 if (newMask) {
2503 mFastTrackNewMask = 0;
2504 memcpy(newArray, mFastTrackNewArray, sizeof(mFastTrackNewArray));
2505#if !LOG_NDEBUG
2506 memset(mFastTrackNewArray, 0, sizeof(mFastTrackNewArray));
2507#endif
2508 }
2509 }
2510 unsigned changedMask = newMask | removedMask;
2511 // are there any newly added or removed fast tracks?
2512 if (changedMask) {
2513
2514 // This assert would be incorrect because it's theoretically possible (though unlikely)
2515 // for a track to be created and then removed within the same normal mix cycle:
2516 // ALOG_ASSERT(!(newMask & removedMask));
2517 // The converse, of removing a track and then creating a new track at the identical slot
2518 // within the same normal mix cycle, is impossible because the slot isn't marked available.
2519
2520 // prepare a new state to push
2521 FastMixerStateQueue *sq = mFastMixer->sq();
2522 FastMixerState *state = sq->begin();
2523 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2524 while (changedMask) {
2525 int j = __builtin_ctz(changedMask);
2526 ALOG_ASSERT(0 < j && j < FastMixerState::kMaxFastTracks);
2527 changedMask &= ~(1 << j);
2528 FastTrack *fastTrack = &state->mFastTracks[j];
2529 // must first do new tracks, then removed tracks, in case same track in both
2530 if (newMask & (1 << j)) {
2531 ALOG_ASSERT(!(state->mTrackMask & (1 << j)));
2532 ALOG_ASSERT(fastTrack->mBufferProvider == NULL &&
2533 fastTrack->mVolumeProvider == NULL);
2534 Track *track = newArray[j];
2535 AudioBufferProvider *abp = track;
2536 VolumeProvider *vp = track;
2537 fastTrack->mBufferProvider = abp;
2538 fastTrack->mVolumeProvider = vp;
2539 fastTrack->mSampleRate = track->mSampleRate;
2540 fastTrack->mChannelMask = track->mChannelMask;
2541 state->mTrackMask |= 1 << j;
2542 }
2543 if (removedMask & (1 << j)) {
2544 ALOG_ASSERT(state->mTrackMask & (1 << j));
2545 ALOG_ASSERT(fastTrack->mBufferProvider != NULL &&
2546 fastTrack->mVolumeProvider != NULL);
2547 fastTrack->mBufferProvider = NULL;
2548 fastTrack->mVolumeProvider = NULL;
2549 fastTrack->mSampleRate = mSampleRate;
2550 fastTrack->mChannelMask = AUDIO_CHANNEL_OUT_STEREO;
2551 state->mTrackMask &= ~(1 << j);
2552 }
2553 fastTrack->mGeneration++;
2554 }
2555 state->mFastTracksGen++;
2556 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
2557 if (state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
2558 state->mCommand = FastMixerState::COLD_IDLE;
2559 state->mColdFutexAddr = &mFastMixerFutex;
2560 state->mColdGen++;
2561 mFastMixerFutex = 0;
2562 mNormalSink = mOutputSink;
2563 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2564 }
2565 sq->end();
2566 // If any fast tracks were removed, we must wait for acknowledgement
2567 // because we're about to decrement the last sp<> on those tracks.
2568 // Similarly if we put it into cold idle, need to wait for acknowledgement
2569 // so that it stops doing I/O.
2570 if (removedMask) {
2571 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2572 }
2573 sq->push(block);
2574 }
2575 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2576}
2577
2578void AudioFlinger::MixerThread::threadLoop_write()
2579{
2580 // FIXME we should only do one push per cycle; confirm this is true
2581 // Start the fast mixer if it's not already running
2582 if (mFastMixer != NULL) {
2583 FastMixerStateQueue *sq = mFastMixer->sq();
2584 FastMixerState *state = sq->begin();
2585 if (state->mCommand != FastMixerState::MIX_WRITE && state->mTrackMask > 1) {
2586 if (state->mCommand == FastMixerState::COLD_IDLE) {
2587 int32_t old = android_atomic_inc(&mFastMixerFutex);
2588 if (old == -1) {
2589 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2590 }
2591 }
2592 state->mCommand = FastMixerState::MIX_WRITE;
2593 sq->end();
2594 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2595 mNormalSink = mPipeSink;
2596 } else {
2597 sq->end(false /*didModify*/);
2598 }
2599 }
2600 PlaybackThread::threadLoop_write();
2601}
2602
Glenn Kasten000f0e32012-03-01 17:10:56 -08002603// shared by MIXER and DIRECT, overridden by DUPLICATING
2604void AudioFlinger::PlaybackThread::threadLoop_write()
2605{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002606 // FIXME rewrite to reduce number of system calls
2607 mLastWriteTime = systemTime();
2608 mInWrite = true;
Glenn Kasten58912562012-04-03 10:45:00 -07002609 int bytesWritten;
2610
2611 // If an NBAIO sink is present, use it to write the normal mixer's submix
2612 if (mNormalSink != 0) {
2613#define mBitShift 2 // FIXME
2614 size_t count = mixBufferSize >> mBitShift;
2615 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
2616 if (framesWritten > 0) {
2617 bytesWritten = framesWritten << mBitShift;
2618 } else {
2619 bytesWritten = framesWritten;
2620 }
2621
2622 // otherwise use the HAL / AudioStreamOut directly
2623 } else {
2624 // FIXME legacy, remove
2625 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2626 }
2627
2628 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002629 mNumWrites++;
2630 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002631}
2632
Glenn Kasten58912562012-04-03 10:45:00 -07002633void AudioFlinger::MixerThread::threadLoop_standby()
2634{
2635 // Idle the fast mixer if it's currently running
2636 if (mFastMixer != NULL) {
2637 FastMixerStateQueue *sq = mFastMixer->sq();
2638 FastMixerState *state = sq->begin();
2639 if (!(state->mCommand & FastMixerState::IDLE)) {
2640 state->mCommand = FastMixerState::COLD_IDLE;
2641 state->mColdFutexAddr = &mFastMixerFutex;
2642 state->mColdGen++;
2643 mFastMixerFutex = 0;
2644 sq->end();
2645 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2646 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2647 mNormalSink = mOutputSink;
2648 } else {
2649 sq->end(false /*didModify*/);
2650 }
2651 }
2652 PlaybackThread::threadLoop_standby();
2653}
2654
Glenn Kasten000f0e32012-03-01 17:10:56 -08002655// shared by MIXER and DIRECT, overridden by DUPLICATING
2656void AudioFlinger::PlaybackThread::threadLoop_standby()
2657{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002658 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2659 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002660}
2661
2662void AudioFlinger::MixerThread::threadLoop_mix()
2663{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002664 // obtain the presentation timestamp of the next output buffer
2665 int64_t pts;
2666 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002667
Glenn Kasten952eeb22012-03-06 11:30:57 -08002668 if (NULL != mOutput->stream->get_next_write_timestamp) {
2669 status = mOutput->stream->get_next_write_timestamp(
2670 mOutput->stream, &pts);
2671 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002672
Glenn Kasten952eeb22012-03-06 11:30:57 -08002673 if (status != NO_ERROR) {
2674 pts = AudioBufferProvider::kInvalidPTS;
2675 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002676
Glenn Kasten952eeb22012-03-06 11:30:57 -08002677 // mix buffers...
2678 mAudioMixer->process(pts);
2679 // increase sleep time progressively when application underrun condition clears.
2680 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2681 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2682 // such that we would underrun the audio HAL.
2683 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2684 sleepTimeShift--;
2685 }
2686 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002687 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002688 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002689}
2690
2691void AudioFlinger::MixerThread::threadLoop_sleepTime()
2692{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002693 // If no tracks are ready, sleep once for the duration of an output
2694 // buffer size, then write 0s to the output
2695 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002696 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002697 sleepTime = activeSleepTime >> sleepTimeShift;
2698 if (sleepTime < kMinThreadSleepTimeUs) {
2699 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002700 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002701 // reduce sleep time in case of consecutive application underruns to avoid
2702 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2703 // duration we would end up writing less data than needed by the audio HAL if
2704 // the condition persists.
2705 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2706 sleepTimeShift++;
2707 }
2708 } else {
2709 sleepTime = idleSleepTime;
2710 }
2711 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002712 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002713 memset (mMixBuffer, 0, mixBufferSize);
2714 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002715 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002716 }
2717 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002718}
2719
2720// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002721AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002722 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002723{
2724
Glenn Kasten29c23c32012-01-26 13:37:52 -08002725 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002726 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002727 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002728 size_t mixedTracks = 0;
2729 size_t tracksWithEffect = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07002730 size_t fastTracks = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002731
2732 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002733 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002734
Eric Laurent571d49c2010-08-11 05:20:11 -07002735 if (masterMute) {
2736 masterVolume = 0;
2737 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002738 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002739 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002740 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002741 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002742 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002743 masterVolume = (float)((v + (1 << 23)) >> 24);
2744 chain.clear();
2745 }
2746
2747 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002748 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002749 if (t == 0) continue;
2750
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002751 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002752 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002753
2754 if (track->isFastTrack()) {
2755 // cache the combined master volume and stream type volume for fast mixer;
2756 // this lacks any synchronization or barrier so VolumeProvider may read a stale value
2757 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
2758 ++fastTracks;
2759 if (track->isTerminated()) {
2760 tracksToRemove->add(track);
2761 }
2762 continue;
2763 }
2764
2765 { // local variable scope to avoid goto warning
2766
Mathias Agopian65ab4712010-07-14 17:59:35 -07002767 audio_track_cblk_t* cblk = track->cblk();
2768
2769 // The first time a track is added we wait
2770 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002771 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002772 // make sure that we have enough frames to mix one full buffer.
2773 // enforce this condition only once to enable draining the buffer in case the client
2774 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002775 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002776 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002777 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002778 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002779 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002780 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07002781 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07002782 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002783 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07002784 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08002785 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07002786 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08002787 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2788 // the minimum track buffer size is normally twice the number of frames necessary
2789 // to fill one buffer and the resampler should not leave more than one buffer worth
2790 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002791 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002792 }
2793 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002794 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002795 !track->isPaused() && !track->isTerminated())
2796 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002797 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002798
2799 mixedTracks++;
2800
2801 // track->mainBuffer() != mMixBuffer means there is an effect chain
2802 // connected to the track
2803 chain.clear();
2804 if (track->mainBuffer() != mMixBuffer) {
2805 chain = getEffectChain_l(track->sessionId());
2806 // Delegate volume control to effect in track effect chain if needed
2807 if (chain != 0) {
2808 tracksWithEffect++;
2809 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002810 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002811 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002812 }
2813 }
2814
2815
2816 int param = AudioMixer::VOLUME;
2817 if (track->mFillingUpStatus == Track::FS_FILLED) {
2818 // no ramp for the first volume setting
2819 track->mFillingUpStatus = Track::FS_ACTIVE;
2820 if (track->mState == TrackBase::RESUMING) {
2821 track->mState = TrackBase::ACTIVE;
2822 param = AudioMixer::RAMP_VOLUME;
2823 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002824 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002825 } else if (cblk->server != 0) {
2826 // If the track is stopped before the first frame was mixed,
2827 // do not apply ramp
2828 param = AudioMixer::RAMP_VOLUME;
2829 }
2830
2831 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002832 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002833 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002834 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002835 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002836 if (track->isPausing()) {
2837 track->setPaused();
2838 }
2839 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002840
Mathias Agopian65ab4712010-07-14 17:59:35 -07002841 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002842 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002843 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002844 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002845 vl = vlr & 0xFFFF;
2846 vr = vlr >> 16;
2847 // track volumes come from shared memory, so can't be trusted and must be clamped
2848 if (vl > MAX_GAIN_INT) {
2849 ALOGV("Track left volume out of range: %04X", vl);
2850 vl = MAX_GAIN_INT;
2851 }
2852 if (vr > MAX_GAIN_INT) {
2853 ALOGV("Track right volume out of range: %04X", vr);
2854 vr = MAX_GAIN_INT;
2855 }
2856 // now apply the master volume and stream type volume
2857 vl = (uint32_t)(v * vl) << 12;
2858 vr = (uint32_t)(v * vr) << 12;
2859 // assuming master volume and stream type volume each go up to 1.0,
2860 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002861
Glenn Kasten05632a52012-01-03 14:22:33 -08002862 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2863 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002864 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002865 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002866 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002867 }
2868 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002869 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002870 // Delegate volume control to effect in track effect chain if needed
2871 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2872 // Do not ramp volume if volume is controlled by effect
2873 param = AudioMixer::VOLUME;
2874 track->mHasVolumeController = true;
2875 } else {
2876 // force no volume ramp when volume controller was just disabled or removed
2877 // from effect chain to avoid volume spike
2878 if (track->mHasVolumeController) {
2879 param = AudioMixer::VOLUME;
2880 }
2881 track->mHasVolumeController = false;
2882 }
2883
2884 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002885 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002886 vl = (vl + (1 << 11)) >> 12;
2887 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2888 vr = (vr + (1 << 11)) >> 12;
2889 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002890
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002891 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 -07002892
Mathias Agopian65ab4712010-07-14 17:59:35 -07002893 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002894 mAudioMixer->setBufferProvider(name, track);
2895 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002896
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002897 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2898 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2899 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002900 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002901 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002902 AudioMixer::TRACK,
2903 AudioMixer::FORMAT, (void *)track->format());
2904 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002905 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002906 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002907 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002908 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002909 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002910 AudioMixer::RESAMPLE,
2911 AudioMixer::SAMPLE_RATE,
2912 (void *)(cblk->sampleRate));
2913 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002914 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002915 AudioMixer::TRACK,
2916 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2917 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002918 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002919 AudioMixer::TRACK,
2920 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2921
2922 // reset retry count
2923 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002924
Eric Laurent27741442012-01-17 19:20:12 -08002925 // If one track is ready, set the mixer ready if:
2926 // - the mixer was not ready during previous round OR
2927 // - no other track is not ready
2928 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2929 mixerStatus != MIXER_TRACKS_ENABLED) {
2930 mixerStatus = MIXER_TRACKS_READY;
2931 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002932 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002933 //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 -07002934 if (track->isStopped()) {
2935 track->reset();
2936 }
2937 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2938 // We have consumed all the buffers of this track.
2939 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07002940 // TODO: use actual buffer filling status instead of latency when available from
2941 // audio HAL
2942 size_t audioHALFrames =
2943 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2944 size_t framesWritten =
2945 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2946 if (track->presentationComplete(framesWritten, audioHALFrames)) {
2947 tracksToRemove->add(track);
2948 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002949 } else {
2950 // No buffers for this track. Give it a few chances to
2951 // fill a buffer, then remove it from active list.
2952 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002953 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002954 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002955 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002956 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002957 // If one track is not ready, mark the mixer also not ready if:
2958 // - the mixer was ready during previous round OR
2959 // - no other track is ready
2960 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2961 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002962 mixerStatus = MIXER_TRACKS_ENABLED;
2963 }
2964 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002965 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002966 }
Glenn Kasten58912562012-04-03 10:45:00 -07002967
2968 } // local variable scope to avoid goto warning
2969track_is_ready: ;
2970
Mathias Agopian65ab4712010-07-14 17:59:35 -07002971 }
2972
Glenn Kasten58912562012-04-03 10:45:00 -07002973 // FIXME Here is where we would push the new FastMixer state if necessary
2974
Mathias Agopian65ab4712010-07-14 17:59:35 -07002975 // remove all the tracks that need to be...
2976 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002977 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002978 for (size_t i=0 ; i<count ; i++) {
2979 const sp<Track>& track = tracksToRemove->itemAt(i);
2980 mActiveTracks.remove(track);
2981 if (track->mainBuffer() != mMixBuffer) {
2982 chain = getEffectChain_l(track->sessionId());
2983 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002984 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002985 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002986 }
2987 }
2988 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002989 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002990 }
2991 }
2992 }
2993
2994 // mix buffer must be cleared if all tracks are connected to an
2995 // effect chain as in this case the mixer will not write to
2996 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07002997 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
2998 // FIXME as a performance optimization, should remember previous zero status
2999 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003000 }
3001
Glenn Kasten58912562012-04-03 10:45:00 -07003002 // if any fast tracks, then status is ready
3003 if (fastTracks > 0) {
3004 mixerStatus = MIXER_TRACKS_READY;
3005 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003006 return mixerStatus;
3007}
3008
Glenn Kasten66fcab92012-02-24 14:59:21 -08003009/*
3010The derived values that are cached:
3011 - mixBufferSize from frame count * frame size
3012 - activeSleepTime from activeSleepTimeUs()
3013 - idleSleepTime from idleSleepTimeUs()
3014 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3015 - maxPeriod from frame count and sample rate (MIXER only)
3016
3017The parameters that affect these derived values are:
3018 - frame count
3019 - frame size
3020 - sample rate
3021 - device type: A2DP or not
3022 - device latency
3023 - format: PCM or not
3024 - active sleep time
3025 - idle sleep time
3026*/
3027
3028void AudioFlinger::PlaybackThread::cacheParameters_l()
3029{
Glenn Kasten58912562012-04-03 10:45:00 -07003030 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003031 activeSleepTime = activeSleepTimeUs();
3032 idleSleepTime = idleSleepTimeUs();
3033}
3034
Glenn Kastenfff6d712012-01-12 16:38:12 -08003035void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003036{
Steve Block3856b092011-10-20 11:56:00 +01003037 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003038 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003039 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003040
Mathias Agopian65ab4712010-07-14 17:59:35 -07003041 size_t size = mTracks.size();
3042 for (size_t i = 0; i < size; i++) {
3043 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003044 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003045 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003046 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003047 }
3048 }
3049}
3050
Mathias Agopian65ab4712010-07-14 17:59:35 -07003051// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003052int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003053{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003054 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003055}
3056
3057// deleteTrackName_l() must be called with ThreadBase::mLock held
3058void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3059{
Steve Block3856b092011-10-20 11:56:00 +01003060 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003061 mAudioMixer->deleteTrackName(name);
3062}
3063
3064// checkForNewParameters_l() must be called with ThreadBase::mLock held
3065bool AudioFlinger::MixerThread::checkForNewParameters_l()
3066{
Glenn Kasten58912562012-04-03 10:45:00 -07003067 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3068 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003069 bool reconfig = false;
3070
3071 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003072
3073 if (mFastMixer != NULL) {
3074 FastMixerStateQueue *sq = mFastMixer->sq();
3075 FastMixerState *state = sq->begin();
3076 if (!(state->mCommand & FastMixerState::IDLE)) {
3077 previousCommand = state->mCommand;
3078 state->mCommand = FastMixerState::HOT_IDLE;
3079 sq->end();
3080 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3081 } else {
3082 sq->end(false /*didModify*/);
3083 }
3084 }
3085
Mathias Agopian65ab4712010-07-14 17:59:35 -07003086 status_t status = NO_ERROR;
3087 String8 keyValuePair = mNewParameters[0];
3088 AudioParameter param = AudioParameter(keyValuePair);
3089 int value;
3090
3091 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3092 reconfig = true;
3093 }
3094 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003095 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003096 status = BAD_VALUE;
3097 } else {
3098 reconfig = true;
3099 }
3100 }
3101 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003102 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003103 status = BAD_VALUE;
3104 } else {
3105 reconfig = true;
3106 }
3107 }
3108 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3109 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003110 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003111 // if frame count is changed after track creation
3112 if (!mTracks.isEmpty()) {
3113 status = INVALID_OPERATION;
3114 } else {
3115 reconfig = true;
3116 }
3117 }
3118 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003119#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003120 // when changing the audio output device, call addBatteryData to notify
3121 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003122 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003123 uint32_t params = 0;
3124 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003125 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003126 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3127 }
3128
3129 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003130 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003131 // check if any other device (except speaker) is on
3132 if (value & deviceWithoutSpeaker ) {
3133 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3134 }
3135
3136 if (params != 0) {
3137 addBatteryData(params);
3138 }
3139 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003140#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003141
Mathias Agopian65ab4712010-07-14 17:59:35 -07003142 // forward device change to effects that have requested to be
3143 // aware of attached audio device.
3144 mDevice = (uint32_t)value;
3145 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003146 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003147 }
3148 }
3149
3150 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003151 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003152 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003154 mOutput->stream->common.standby(&mOutput->stream->common);
3155 mStandby = true;
3156 mBytesWritten = 0;
3157 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003158 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003159 }
3160 if (status == NO_ERROR && reconfig) {
3161 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003162 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3163 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003164 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003165 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003166 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003167 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003168 if (name < 0) break;
3169 mTracks[i]->mName = name;
3170 // limit track sample rate to 2 x new output sample rate
3171 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3172 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3173 }
3174 }
3175 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3176 }
3177 }
3178
3179 mNewParameters.removeAt(0);
3180
3181 mParamStatus = status;
3182 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003183 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3184 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003185 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003186 }
Glenn Kasten58912562012-04-03 10:45:00 -07003187
3188 if (!(previousCommand & FastMixerState::IDLE)) {
3189 ALOG_ASSERT(mFastMixer != NULL);
3190 FastMixerStateQueue *sq = mFastMixer->sq();
3191 FastMixerState *state = sq->begin();
3192 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3193 state->mCommand = previousCommand;
3194 sq->end();
3195 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3196 }
3197
Mathias Agopian65ab4712010-07-14 17:59:35 -07003198 return reconfig;
3199}
3200
3201status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3202{
3203 const size_t SIZE = 256;
3204 char buffer[SIZE];
3205 String8 result;
3206
3207 PlaybackThread::dumpInternals(fd, args);
3208
3209 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3210 result.append(buffer);
3211 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003212
3213 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3214 FastMixerDumpState copy = mFastMixerDumpState;
3215 copy.dump(fd);
3216
Mathias Agopian65ab4712010-07-14 17:59:35 -07003217 return NO_ERROR;
3218}
3219
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003220uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003221{
Glenn Kasten58912562012-04-03 10:45:00 -07003222 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003223}
3224
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003225uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003226{
Glenn Kasten58912562012-04-03 10:45:00 -07003227 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003228}
3229
Glenn Kasten66fcab92012-02-24 14:59:21 -08003230void AudioFlinger::MixerThread::cacheParameters_l()
3231{
3232 PlaybackThread::cacheParameters_l();
3233
3234 // FIXME: Relaxed timing because of a certain device that can't meet latency
3235 // Should be reduced to 2x after the vendor fixes the driver issue
3236 // increase threshold again due to low power audio mode. The way this warning
3237 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003238 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003239}
3240
Mathias Agopian65ab4712010-07-14 17:59:35 -07003241// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003242AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3243 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003244 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003245 // mLeftVolFloat, mRightVolFloat
3246 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07003247{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003248}
3249
3250AudioFlinger::DirectOutputThread::~DirectOutputThread()
3251{
3252}
3253
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003254AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3255 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003256)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003257{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003258 sp<Track> trackToRemove;
3259
Glenn Kastenfec279f2012-03-08 07:47:15 -08003260 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003261
Glenn Kasten952eeb22012-03-06 11:30:57 -08003262 // find out which tracks need to be processed
3263 if (mActiveTracks.size() != 0) {
3264 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003265 // The track died recently
3266 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003267
Glenn Kasten952eeb22012-03-06 11:30:57 -08003268 Track* const track = t.get();
3269 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003270
Glenn Kasten952eeb22012-03-06 11:30:57 -08003271 // The first time a track is added we wait
3272 // for all its buffers to be filled before processing it
3273 if (cblk->framesReady() && track->isReady() &&
3274 !track->isPaused() && !track->isTerminated())
3275 {
3276 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003277
Glenn Kasten952eeb22012-03-06 11:30:57 -08003278 if (track->mFillingUpStatus == Track::FS_FILLED) {
3279 track->mFillingUpStatus = Track::FS_ACTIVE;
3280 mLeftVolFloat = mRightVolFloat = 0;
3281 mLeftVolShort = mRightVolShort = 0;
3282 if (track->mState == TrackBase::RESUMING) {
3283 track->mState = TrackBase::ACTIVE;
3284 rampVolume = true;
3285 }
3286 } else if (cblk->server != 0) {
3287 // If the track is stopped before the first frame was mixed,
3288 // do not apply ramp
3289 rampVolume = true;
3290 }
3291 // compute volume for this track
3292 float left, right;
3293 if (track->isMuted() || mMasterMute || track->isPausing() ||
3294 mStreamTypes[track->streamType()].mute) {
3295 left = right = 0;
3296 if (track->isPausing()) {
3297 track->setPaused();
3298 }
3299 } else {
3300 float typeVolume = mStreamTypes[track->streamType()].volume;
3301 float v = mMasterVolume * typeVolume;
3302 uint32_t vlr = cblk->getVolumeLR();
3303 float v_clamped = v * (vlr & 0xFFFF);
3304 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3305 left = v_clamped/MAX_GAIN;
3306 v_clamped = v * (vlr >> 16);
3307 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3308 right = v_clamped/MAX_GAIN;
3309 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003310
Glenn Kasten952eeb22012-03-06 11:30:57 -08003311 if (left != mLeftVolFloat || right != mRightVolFloat) {
3312 mLeftVolFloat = left;
3313 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003314
Glenn Kasten952eeb22012-03-06 11:30:57 -08003315 // If audio HAL implements volume control,
3316 // force software volume to nominal value
3317 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
3318 left = 1.0f;
3319 right = 1.0f;
3320 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003321
Glenn Kasten952eeb22012-03-06 11:30:57 -08003322 // Convert volumes from float to 8.24
3323 uint32_t vl = (uint32_t)(left * (1 << 24));
3324 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003325
Glenn Kasten952eeb22012-03-06 11:30:57 -08003326 // Delegate volume control to effect in track effect chain if needed
3327 // only one effect chain can be present on DirectOutputThread, so if
3328 // there is one, the track is connected to it
3329 if (!mEffectChains.isEmpty()) {
3330 // Do not ramp volume if volume is controlled by effect
3331 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332 rampVolume = false;
3333 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003334 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003335
Glenn Kasten952eeb22012-03-06 11:30:57 -08003336 // Convert volumes from 8.24 to 4.12 format
3337 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
3338 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3339 leftVol = (uint16_t)v_clamped;
3340 v_clamped = (vr + (1 << 11)) >> 12;
3341 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3342 rightVol = (uint16_t)v_clamped;
3343 } else {
3344 leftVol = mLeftVolShort;
3345 rightVol = mRightVolShort;
3346 rampVolume = false;
3347 }
3348
3349 // reset retry count
3350 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003351 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003352 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003353 } else {
3354 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
3355 if (track->isStopped()) {
3356 track->reset();
3357 }
3358 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
3359 // We have consumed all the buffers of this track.
3360 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003361 // TODO: implement behavior for compressed audio
3362 size_t audioHALFrames =
3363 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3364 size_t framesWritten =
3365 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3366 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3367 trackToRemove = track;
3368 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003369 } else {
3370 // No buffers for this track. Give it a few chances to
3371 // fill a buffer, then remove it from active list.
3372 if (--(track->mRetryCount) <= 0) {
3373 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3374 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003375 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003376 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003377 }
3378 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003379 }
3380 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003381
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003382 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003383 // remove all the tracks that need to be...
3384 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003385 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003386 mActiveTracks.remove(trackToRemove);
3387 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003388 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003389 trackToRemove->sessionId());
3390 mEffectChains[0]->decActiveTrackCnt();
3391 }
3392 if (trackToRemove->isTerminated()) {
3393 removeTrack_l(trackToRemove);
3394 }
3395 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003396
Glenn Kastenfec279f2012-03-08 07:47:15 -08003397 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003398}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003399
Glenn Kasten000f0e32012-03-01 17:10:56 -08003400void AudioFlinger::DirectOutputThread::threadLoop_mix()
3401{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003402 AudioBufferProvider::Buffer buffer;
3403 size_t frameCount = mFrameCount;
3404 int8_t *curBuf = (int8_t *)mMixBuffer;
3405 // output audio to hardware
3406 while (frameCount) {
3407 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003408 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003409 if (CC_UNLIKELY(buffer.raw == NULL)) {
3410 memset(curBuf, 0, frameCount * mFrameSize);
3411 break;
3412 }
3413 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3414 frameCount -= buffer.frameCount;
3415 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003416 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003417 }
3418 sleepTime = 0;
3419 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003420 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003421
3422 // apply volume
3423
3424 // Do not apply volume on compressed audio
3425 if (!audio_is_linear_pcm(mFormat)) {
3426 return;
3427 }
3428
3429 // convert to signed 16 bit before volume calculation
3430 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3431 size_t count = mFrameCount * mChannelCount;
3432 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
3433 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003434 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003435 *dst-- = (int16_t)(*src--^0x80) << 8;
3436 }
3437 }
3438
3439 frameCount = mFrameCount;
3440 int16_t *out = mMixBuffer;
3441 if (rampVolume) {
3442 if (mChannelCount == 1) {
3443 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3444 int32_t vlInc = d / (int32_t)frameCount;
3445 int32_t vl = ((int32_t)mLeftVolShort << 16);
3446 do {
3447 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3448 out++;
3449 vl += vlInc;
3450 } while (--frameCount);
3451
3452 } else {
3453 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3454 int32_t vlInc = d / (int32_t)frameCount;
3455 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3456 int32_t vrInc = d / (int32_t)frameCount;
3457 int32_t vl = ((int32_t)mLeftVolShort << 16);
3458 int32_t vr = ((int32_t)mRightVolShort << 16);
3459 do {
3460 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3461 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3462 out += 2;
3463 vl += vlInc;
3464 vr += vrInc;
3465 } while (--frameCount);
3466 }
3467 } else {
3468 if (mChannelCount == 1) {
3469 do {
3470 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3471 out++;
3472 } while (--frameCount);
3473 } else {
3474 do {
3475 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3476 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3477 out += 2;
3478 } while (--frameCount);
3479 }
3480 }
3481
3482 // convert back to unsigned 8 bit after volume calculation
3483 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3484 size_t count = mFrameCount * mChannelCount;
3485 int16_t *src = mMixBuffer;
3486 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003487 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003488 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3489 }
3490 }
3491
3492 mLeftVolShort = leftVol;
3493 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003494}
3495
3496void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3497{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003498 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003499 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003500 sleepTime = activeSleepTime;
3501 } else {
3502 sleepTime = idleSleepTime;
3503 }
3504 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003505 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003506 sleepTime = 0;
3507 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003508}
3509
3510// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003511int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003512{
3513 return 0;
3514}
3515
3516// deleteTrackName_l() must be called with ThreadBase::mLock held
3517void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3518{
3519}
3520
3521// checkForNewParameters_l() must be called with ThreadBase::mLock held
3522bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3523{
3524 bool reconfig = false;
3525
3526 while (!mNewParameters.isEmpty()) {
3527 status_t status = NO_ERROR;
3528 String8 keyValuePair = mNewParameters[0];
3529 AudioParameter param = AudioParameter(keyValuePair);
3530 int value;
3531
3532 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3533 // do not accept frame count changes if tracks are open as the track buffer
3534 // size depends on frame count and correct behavior would not be garantied
3535 // if frame count is changed after track creation
3536 if (!mTracks.isEmpty()) {
3537 status = INVALID_OPERATION;
3538 } else {
3539 reconfig = true;
3540 }
3541 }
3542 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003543 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003544 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003545 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003546 mOutput->stream->common.standby(&mOutput->stream->common);
3547 mStandby = true;
3548 mBytesWritten = 0;
3549 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003550 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003551 }
3552 if (status == NO_ERROR && reconfig) {
3553 readOutputParameters();
3554 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3555 }
3556 }
3557
3558 mNewParameters.removeAt(0);
3559
3560 mParamStatus = status;
3561 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003562 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3563 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003564 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003565 }
3566 return reconfig;
3567}
3568
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003569uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003570{
3571 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003572 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003573 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003574 } else {
3575 time = 10000;
3576 }
3577 return time;
3578}
3579
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003580uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003581{
3582 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003583 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003584 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003585 } else {
3586 time = 10000;
3587 }
3588 return time;
3589}
3590
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003591uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003592{
3593 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003594 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003595 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3596 } else {
3597 time = 10000;
3598 }
3599 return time;
3600}
3601
Glenn Kasten66fcab92012-02-24 14:59:21 -08003602void AudioFlinger::DirectOutputThread::cacheParameters_l()
3603{
3604 PlaybackThread::cacheParameters_l();
3605
3606 // use shorter standby delay as on normal output to release
3607 // hardware resources as soon as possible
3608 standbyDelay = microseconds(activeSleepTime*2);
3609}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003610
Mathias Agopian65ab4712010-07-14 17:59:35 -07003611// ----------------------------------------------------------------------------
3612
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003613AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003614 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003615 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3616 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003617{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618 addOutputTrack(mainThread);
3619}
3620
3621AudioFlinger::DuplicatingThread::~DuplicatingThread()
3622{
3623 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3624 mOutputTracks[i]->destroy();
3625 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003626}
3627
Glenn Kasten000f0e32012-03-01 17:10:56 -08003628void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003629{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003630 // mix buffers...
3631 if (outputsReady(outputTracks)) {
3632 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3633 } else {
3634 memset(mMixBuffer, 0, mixBufferSize);
3635 }
3636 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003637 writeFrames = mNormalFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003638}
3639
3640void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3641{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003642 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003643 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003644 sleepTime = activeSleepTime;
3645 } else {
3646 sleepTime = idleSleepTime;
3647 }
3648 } else if (mBytesWritten != 0) {
3649 // flush remaining overflow buffers in output tracks
3650 for (size_t i = 0; i < outputTracks.size(); i++) {
3651 if (outputTracks[i]->isActive()) {
3652 sleepTime = 0;
3653 writeFrames = 0;
3654 memset(mMixBuffer, 0, mixBufferSize);
3655 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003656 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003657 }
3658 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003659}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003660
Glenn Kasten000f0e32012-03-01 17:10:56 -08003661void AudioFlinger::DuplicatingThread::threadLoop_write()
3662{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003663 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003664 for (size_t i = 0; i < outputTracks.size(); i++) {
3665 outputTracks[i]->write(mMixBuffer, writeFrames);
3666 }
3667 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003668}
Glenn Kasten688a6402012-02-29 07:57:06 -08003669
Glenn Kasten000f0e32012-03-01 17:10:56 -08003670void AudioFlinger::DuplicatingThread::threadLoop_standby()
3671{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003672 // DuplicatingThread implements standby by stopping all tracks
3673 for (size_t i = 0; i < outputTracks.size(); i++) {
3674 outputTracks[i]->stop();
3675 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003676}
3677
Glenn Kastenfa26a852012-03-06 11:28:04 -08003678void AudioFlinger::DuplicatingThread::saveOutputTracks()
3679{
3680 outputTracks = mOutputTracks;
3681}
3682
3683void AudioFlinger::DuplicatingThread::clearOutputTracks()
3684{
3685 outputTracks.clear();
3686}
3687
Mathias Agopian65ab4712010-07-14 17:59:35 -07003688void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3689{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003690 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003691 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003692 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003693 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003694 this,
3695 mSampleRate,
3696 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003697 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003698 frameCount);
3699 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003700 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003701 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003702 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003703 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003704 }
3705}
3706
3707void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3708{
3709 Mutex::Autolock _l(mLock);
3710 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003711 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003712 mOutputTracks[i]->destroy();
3713 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003714 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003715 return;
3716 }
3717 }
Steve Block3856b092011-10-20 11:56:00 +01003718 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003719}
3720
Glenn Kasten438b0362012-03-06 11:24:48 -08003721// caller must hold mLock
3722void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003723{
3724 mWaitTimeMs = UINT_MAX;
3725 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3726 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003727 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003728 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3729 if (waitTimeMs < mWaitTimeMs) {
3730 mWaitTimeMs = waitTimeMs;
3731 }
3732 }
3733 }
3734}
3735
3736
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003737bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003738{
3739 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003740 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003741 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003742 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003743 return false;
3744 }
3745 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3746 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003747 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003748 return false;
3749 }
3750 }
3751 return true;
3752}
3753
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003754uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003755{
3756 return (mWaitTimeMs * 1000) / 2;
3757}
3758
Glenn Kasten66fcab92012-02-24 14:59:21 -08003759void AudioFlinger::DuplicatingThread::cacheParameters_l()
3760{
3761 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3762 updateWaitTime_l();
3763
3764 MixerThread::cacheParameters_l();
3765}
3766
Mathias Agopian65ab4712010-07-14 17:59:35 -07003767// ----------------------------------------------------------------------------
3768
3769// TrackBase constructor must be called with AudioFlinger::mLock held
3770AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003771 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003772 const sp<Client>& client,
3773 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003774 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003775 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003776 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003777 const sp<IMemory>& sharedBuffer,
3778 int sessionId)
3779 : RefBase(),
3780 mThread(thread),
3781 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003782 mCblk(NULL),
3783 // mBuffer
3784 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003785 mFrameCount(0),
3786 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07003787 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003788 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003789 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003790 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003791 // mChannelCount
3792 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003793{
Steve Block3856b092011-10-20 11:56:00 +01003794 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003795
Steve Blockb8a80522011-12-20 16:23:08 +00003796 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003797 size_t size = sizeof(audio_track_cblk_t);
3798 uint8_t channelCount = popcount(channelMask);
3799 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3800 if (sharedBuffer == 0) {
3801 size += bufferSize;
3802 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003803
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003804 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003805 mCblkMemory = client->heap()->allocate(size);
3806 if (mCblkMemory != 0) {
3807 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003808 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003809 new(mCblk) audio_track_cblk_t();
3810 // clear all buffers
3811 mCblk->frameCount = frameCount;
3812 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003813// uncomment the following lines to quickly test 32-bit wraparound
3814// mCblk->user = 0xffff0000;
3815// mCblk->server = 0xffff0000;
3816// mCblk->userBase = 0xffff0000;
3817// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003818 mChannelCount = channelCount;
3819 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003820 if (sharedBuffer == 0) {
3821 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3822 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3823 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003824 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003825 mCblk->flags = CBLK_UNDERRUN_ON;
3826 } else {
3827 mBuffer = sharedBuffer->pointer();
3828 }
3829 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3830 }
3831 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003832 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003833 client->heap()->dump("AudioTrack");
3834 return;
3835 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003836 } else {
3837 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07003838 // construct the shared structure in-place.
3839 new(mCblk) audio_track_cblk_t();
3840 // clear all buffers
3841 mCblk->frameCount = frameCount;
3842 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003843// uncomment the following lines to quickly test 32-bit wraparound
3844// mCblk->user = 0xffff0000;
3845// mCblk->server = 0xffff0000;
3846// mCblk->userBase = 0xffff0000;
3847// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003848 mChannelCount = channelCount;
3849 mChannelMask = channelMask;
3850 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3851 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3852 // Force underrun condition to avoid false underrun callback until first data is
3853 // written to buffer (other flags are cleared)
3854 mCblk->flags = CBLK_UNDERRUN_ON;
3855 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003856 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003857}
3858
3859AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3860{
Glenn Kastena0d68332012-01-27 16:47:15 -08003861 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003862 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003863 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003864 } else {
3865 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003866 }
3867 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003868 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003869 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003870 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003871 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003872 // If the client's reference count drops to zero, the associated destructor
3873 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3874 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003875 mClient.clear();
3876 }
3877}
3878
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003879// AudioBufferProvider interface
3880// getNextBuffer() = 0;
3881// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003882void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3883{
Glenn Kastene0feee32011-12-13 11:53:26 -08003884 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003885 mFrameCount = buffer->frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003886 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003887 buffer->frameCount = 0;
3888}
3889
3890bool AudioFlinger::ThreadBase::TrackBase::step() {
3891 bool result;
3892 audio_track_cblk_t* cblk = this->cblk();
3893
3894 result = cblk->stepServer(mFrameCount);
3895 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003896 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003897 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003898 }
3899 return result;
3900}
3901
3902void AudioFlinger::ThreadBase::TrackBase::reset() {
3903 audio_track_cblk_t* cblk = this->cblk();
3904
3905 cblk->user = 0;
3906 cblk->server = 0;
3907 cblk->userBase = 0;
3908 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003909 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01003910 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003911}
3912
Mathias Agopian65ab4712010-07-14 17:59:35 -07003913int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3914 return (int)mCblk->sampleRate;
3915}
3916
Mathias Agopian65ab4712010-07-14 17:59:35 -07003917void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3918 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003919 size_t frameSize = cblk->frameSize;
3920 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3921 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003922
3923 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07003924 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
3925 "TrackBase::getBuffer buffer out of range:\n"
3926 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
3927 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003928 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07003929 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003930
3931 return bufferStart;
3932}
3933
Eric Laurenta011e352012-03-29 15:51:43 -07003934status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
3935{
3936 mSyncEvents.add(event);
3937 return NO_ERROR;
3938}
3939
Mathias Agopian65ab4712010-07-14 17:59:35 -07003940// ----------------------------------------------------------------------------
3941
3942// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3943AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003944 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003945 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003946 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003947 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003948 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003949 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003950 int frameCount,
3951 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07003952 int sessionId,
3953 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003954 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07003955 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07003956 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07003957 // mRetryCount initialized later when needed
3958 mSharedBuffer(sharedBuffer),
3959 mStreamType(streamType),
3960 mName(-1), // see note below
3961 mMainBuffer(thread->mixBuffer()),
3962 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07003963 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07003964 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07003965 mFlags(flags),
3966 mFastIndex(-1),
3967 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003968{
3969 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003970 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3971 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003972 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten58912562012-04-03 10:45:00 -07003973 if (flags & IAudioFlinger::TRACK_FAST) {
3974 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
3975 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
3976 int i = __builtin_ctz(thread->mFastTrackAvailMask);
3977 ALOG_ASSERT(0 < i && i < FastMixerState::kMaxFastTracks);
3978 mFastIndex = i;
3979 thread->mFastTrackAvailMask &= ~(1 << i);
3980 // Although we've allocated an index, we can't mutate or push a new fast track state
3981 // here, because that data structure can only be changed within the normal mixer
3982 // threadLoop(). So instead, make a note to mutate and push later.
3983 thread->mFastTrackNewArray[i] = this;
3984 thread->mFastTrackNewMask |= 1 << i;
3985 }
Glenn Kastenf9959012012-03-19 11:14:37 -07003986 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003987 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kastenf9959012012-03-19 11:14:37 -07003988 if (mName < 0) {
3989 ALOGE("no more track names available");
3990 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003991 }
Glenn Kastenf9959012012-03-19 11:14:37 -07003992 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003993}
3994
3995AudioFlinger::PlaybackThread::Track::~Track()
3996{
Steve Block3856b092011-10-20 11:56:00 +01003997 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003998 sp<ThreadBase> thread = mThread.promote();
3999 if (thread != 0) {
4000 Mutex::Autolock _l(thread->mLock);
4001 mState = TERMINATED;
4002 }
4003}
4004
4005void AudioFlinger::PlaybackThread::Track::destroy()
4006{
4007 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4008 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004009 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004010 // we must acquire a strong reference on this Track before locking mLock
4011 // here so that the destructor is called only when exiting this function.
4012 // On the other hand, as long as Track::destroy() is only called by
4013 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4014 // this Track with its member mTrack.
4015 sp<Track> keep(this);
4016 { // scope for mLock
4017 sp<ThreadBase> thread = mThread.promote();
4018 if (thread != 0) {
4019 if (!isOutputTrack()) {
4020 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004021 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004022
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004023#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004024 // to track the speaker usage
4025 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004026#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004027 }
4028 AudioSystem::releaseOutput(thread->id());
4029 }
4030 Mutex::Autolock _l(thread->mLock);
4031 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4032 playbackThread->destroyTrack_l(this);
4033 }
4034 }
4035}
4036
4037void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4038{
Glenn Kasten83d86532012-01-17 14:39:34 -08004039 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004040 if (isFastTrack()) {
4041 strcpy(buffer, " fast");
4042 } else {
4043 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4044 }
4045 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %1d %1d %1d %5u %5.2g %5.2g 0x%08x 0x%08x 0x%08x 0x%08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004046 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004047 mStreamType,
4048 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004049 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004050 mSessionId,
4051 mFrameCount,
4052 mState,
4053 mMute,
4054 mFillingUpStatus,
4055 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004056 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4057 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004058 mCblk->server,
4059 mCblk->user,
4060 (int)mMainBuffer,
4061 (int)mAuxBuffer);
4062}
4063
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004064// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004065status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004066 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004067{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004068 audio_track_cblk_t* cblk = this->cblk();
4069 uint32_t framesReady;
4070 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004071
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004072 // Check if last stepServer failed, try to step now
4073 if (mStepServerFailed) {
4074 if (!step()) goto getNextBuffer_exit;
4075 ALOGV("stepServer recovered");
4076 mStepServerFailed = false;
4077 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004078
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004079 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004080
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004081 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004082 uint32_t s = cblk->server;
4083 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4084
4085 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4086 if (framesReq > framesReady) {
4087 framesReq = framesReady;
4088 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004089 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004090 framesReq = bufferEnd - s;
4091 }
4092
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004093 buffer->raw = getBuffer(s, framesReq);
4094 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004095
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004096 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004097 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004098 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004099
4100getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004101 buffer->raw = NULL;
4102 buffer->frameCount = 0;
4103 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4104 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004105}
4106
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004107uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004108 return mCblk->framesReady();
4109}
4110
Mathias Agopian65ab4712010-07-14 17:59:35 -07004111bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004112 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004113
John Grossman4ff14ba2012-02-08 16:37:41 -08004114 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004115 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4116 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004117 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004118 return true;
4119 }
4120 return false;
4121}
4122
Glenn Kasten3acbd052012-02-28 10:39:56 -08004123status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004124 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004125{
4126 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004127 ALOGV("start(%d), calling pid %d session %d",
4128 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004129
Mathias Agopian65ab4712010-07-14 17:59:35 -07004130 sp<ThreadBase> thread = mThread.promote();
4131 if (thread != 0) {
4132 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004133 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004134 // here the track could be either new, or restarted
4135 // in both cases "unstop" the track
4136 if (mState == PAUSED) {
4137 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004138 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004139 } else {
4140 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004141 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004142 }
4143
4144 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4145 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004146 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004147 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004148
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004149#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004150 // to track the speaker usage
4151 if (status == NO_ERROR) {
4152 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4153 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004154#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004155 }
4156 if (status == NO_ERROR) {
4157 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4158 playbackThread->addTrack_l(this);
4159 } else {
4160 mState = state;
4161 }
4162 } else {
4163 status = BAD_VALUE;
4164 }
4165 return status;
4166}
4167
4168void AudioFlinger::PlaybackThread::Track::stop()
4169{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004170 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004171 sp<ThreadBase> thread = mThread.promote();
4172 if (thread != 0) {
4173 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004174 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004175 if (mState > STOPPED) {
4176 mState = STOPPED;
4177 // If the track is not active (PAUSED and buffers full), flush buffers
4178 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4179 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4180 reset();
4181 }
Steve Block3856b092011-10-20 11:56:00 +01004182 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004183 }
4184 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4185 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004186 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004187 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004188
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004189#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004190 // to track the speaker usage
4191 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004192#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004193 }
4194 }
4195}
4196
4197void AudioFlinger::PlaybackThread::Track::pause()
4198{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004199 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200 sp<ThreadBase> thread = mThread.promote();
4201 if (thread != 0) {
4202 Mutex::Autolock _l(thread->mLock);
4203 if (mState == ACTIVE || mState == RESUMING) {
4204 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004205 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004206 if (!isOutputTrack()) {
4207 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004208 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004209 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004210
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004211#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004212 // to track the speaker usage
4213 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004214#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004215 }
4216 }
4217 }
4218}
4219
4220void AudioFlinger::PlaybackThread::Track::flush()
4221{
Steve Block3856b092011-10-20 11:56:00 +01004222 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004223 sp<ThreadBase> thread = mThread.promote();
4224 if (thread != 0) {
4225 Mutex::Autolock _l(thread->mLock);
4226 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
4227 return;
4228 }
4229 // No point remaining in PAUSED state after a flush => go to
4230 // STOPPED state
4231 mState = STOPPED;
4232
Eric Laurent38ccae22011-03-28 18:37:07 -07004233 // do not reset the track if it is still in the process of being stopped or paused.
4234 // this will be done by prepareTracks_l() when the track is stopped.
4235 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4236 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4237 reset();
4238 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004239 }
4240}
4241
4242void AudioFlinger::PlaybackThread::Track::reset()
4243{
4244 // Do not reset twice to avoid discarding data written just after a flush and before
4245 // the audioflinger thread detects the track is stopped.
4246 if (!mResetDone) {
4247 TrackBase::reset();
4248 // Force underrun condition to avoid false underrun callback until first data is
4249 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004250 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4251 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004252 mFillingUpStatus = FS_FILLING;
4253 mResetDone = true;
Eric Laurenta011e352012-03-29 15:51:43 -07004254 mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004255 }
4256}
4257
4258void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4259{
4260 mMute = muted;
4261}
4262
Mathias Agopian65ab4712010-07-14 17:59:35 -07004263status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4264{
4265 status_t status = DEAD_OBJECT;
4266 sp<ThreadBase> thread = mThread.promote();
4267 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004268 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4269 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004270 }
4271 return status;
4272}
4273
4274void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4275{
4276 mAuxEffectId = EffectId;
4277 mAuxBuffer = buffer;
4278}
4279
Eric Laurenta011e352012-03-29 15:51:43 -07004280bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4281 size_t audioHalFrames)
4282{
4283 // a track is considered presented when the total number of frames written to audio HAL
4284 // corresponds to the number of frames written when presentationComplete() is called for the
4285 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4286 if (mPresentationCompleteFrames == 0) {
4287 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4288 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4289 mPresentationCompleteFrames, audioHalFrames);
4290 }
4291 if (framesWritten >= mPresentationCompleteFrames) {
4292 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4293 mSessionId, framesWritten);
4294 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
4295 mPresentationCompleteFrames = 0;
4296 return true;
4297 }
4298 return false;
4299}
4300
4301void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4302{
4303 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4304 if (mSyncEvents[i]->type() == type) {
4305 mSyncEvents[i]->trigger();
4306 mSyncEvents.removeAt(i);
4307 i--;
4308 }
4309 }
4310}
4311
Glenn Kasten58912562012-04-03 10:45:00 -07004312// implement VolumeBufferProvider interface
4313
4314uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4315{
4316 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4317 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4318 uint32_t vlr = mCblk->getVolumeLR();
4319 uint32_t vl = vlr & 0xFFFF;
4320 uint32_t vr = vlr >> 16;
4321 // track volumes come from shared memory, so can't be trusted and must be clamped
4322 if (vl > MAX_GAIN_INT) {
4323 vl = MAX_GAIN_INT;
4324 }
4325 if (vr > MAX_GAIN_INT) {
4326 vr = MAX_GAIN_INT;
4327 }
4328 // now apply the cached master volume and stream type volume;
4329 // this is trusted but lacks any synchronization or barrier so may be stale
4330 float v = mCachedVolume;
4331 vl *= v;
4332 vr *= v;
4333 // re-combine into U4.16
4334 vlr = (vr << 16) | (vl & 0xFFFF);
4335 // FIXME look at mute, pause, and stop flags
4336 return vlr;
4337}
Eric Laurenta011e352012-03-29 15:51:43 -07004338
John Grossman4ff14ba2012-02-08 16:37:41 -08004339// timed audio tracks
4340
4341sp<AudioFlinger::PlaybackThread::TimedTrack>
4342AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004343 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004344 const sp<Client>& client,
4345 audio_stream_type_t streamType,
4346 uint32_t sampleRate,
4347 audio_format_t format,
4348 uint32_t channelMask,
4349 int frameCount,
4350 const sp<IMemory>& sharedBuffer,
4351 int sessionId) {
4352 if (!client->reserveTimedTrack())
4353 return NULL;
4354
Glenn Kastena0356762012-03-19 10:38:51 -07004355 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004356 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4357 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004358}
4359
4360AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004361 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004362 const sp<Client>& client,
4363 audio_stream_type_t streamType,
4364 uint32_t sampleRate,
4365 audio_format_t format,
4366 uint32_t channelMask,
4367 int frameCount,
4368 const sp<IMemory>& sharedBuffer,
4369 int sessionId)
4370 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004371 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004372 mQueueHeadInFlight(false),
4373 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004374 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004375 mTimedSilenceBuffer(NULL),
4376 mTimedSilenceBufferSize(0),
4377 mTimedAudioOutputOnTime(false),
4378 mMediaTimeTransformValid(false)
4379{
4380 LocalClock lc;
4381 mLocalTimeFreq = lc.getLocalFreq();
4382
4383 mLocalTimeToSampleTransform.a_zero = 0;
4384 mLocalTimeToSampleTransform.b_zero = 0;
4385 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4386 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4387 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4388 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004389
4390 mMediaTimeToSampleTransform.a_zero = 0;
4391 mMediaTimeToSampleTransform.b_zero = 0;
4392 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4393 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4394 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4395 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004396}
4397
4398AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4399 mClient->releaseTimedTrack();
4400 delete [] mTimedSilenceBuffer;
4401}
4402
4403status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4404 size_t size, sp<IMemory>* buffer) {
4405
4406 Mutex::Autolock _l(mTimedBufferQueueLock);
4407
4408 trimTimedBufferQueue_l();
4409
4410 // lazily initialize the shared memory heap for timed buffers
4411 if (mTimedMemoryDealer == NULL) {
4412 const int kTimedBufferHeapSize = 512 << 10;
4413
4414 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4415 "AudioFlingerTimed");
4416 if (mTimedMemoryDealer == NULL)
4417 return NO_MEMORY;
4418 }
4419
4420 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4421 if (newBuffer == NULL) {
4422 newBuffer = mTimedMemoryDealer->allocate(size);
4423 if (newBuffer == NULL)
4424 return NO_MEMORY;
4425 }
4426
4427 *buffer = newBuffer;
4428 return NO_ERROR;
4429}
4430
4431// caller must hold mTimedBufferQueueLock
4432void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4433 int64_t mediaTimeNow;
4434 {
4435 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4436 if (!mMediaTimeTransformValid)
4437 return;
4438
4439 int64_t targetTimeNow;
4440 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4441 ? mCCHelper.getCommonTime(&targetTimeNow)
4442 : mCCHelper.getLocalTime(&targetTimeNow);
4443
4444 if (OK != res)
4445 return;
4446
4447 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4448 &mediaTimeNow)) {
4449 return;
4450 }
4451 }
4452
John Grossman1c345192012-03-27 14:00:17 -07004453 size_t trimEnd;
4454 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004455 int64_t bufEnd;
4456
John Grossmanc95cfbb2012-04-12 11:53:11 -07004457 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4458 // We have a next buffer. Just use its PTS as the PTS of the frame
4459 // following the last frame in this buffer. If the stream is sparse
4460 // (ie, there are deliberate gaps left in the stream which should be
4461 // filled with silence by the TimedAudioTrack), then this can result
4462 // in one extra buffer being left un-trimmed when it could have
4463 // been. In general, this is not typical, and we would rather
4464 // optimized away the TS calculation below for the more common case
4465 // where PTSes are contiguous.
4466 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4467 } else {
4468 // We have no next buffer. Compute the PTS of the frame following
4469 // the last frame in this buffer by computing the duration of of
4470 // this frame in media time units and adding it to the PTS of the
4471 // buffer.
4472 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4473 / mCblk->frameSize;
4474
4475 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4476 &bufEnd)) {
4477 ALOGE("Failed to convert frame count of %lld to media time"
4478 " duration" " (scale factor %d/%u) in %s",
4479 frameCount,
4480 mMediaTimeToSampleTransform.a_to_b_numer,
4481 mMediaTimeToSampleTransform.a_to_b_denom,
4482 __PRETTY_FUNCTION__);
4483 break;
4484 }
4485 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004486 }
John Grossman9fbdee12012-03-26 17:51:46 -07004487
4488 if (bufEnd > mediaTimeNow)
4489 break;
4490
4491 // Is the buffer we want to use in the middle of a mix operation right
4492 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4493 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004494 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004495 mTrimQueueHeadOnRelease = true;
4496 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004497 }
4498
John Grossman9fbdee12012-03-26 17:51:46 -07004499 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004500 if (trimStart < trimEnd) {
4501 // Update the bookkeeping for framesReady()
4502 for (size_t i = trimStart; i < trimEnd; ++i) {
4503 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4504 }
4505
4506 // Now actually remove the buffers from the queue.
4507 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004508 }
4509}
4510
John Grossman1c345192012-03-27 14:00:17 -07004511void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4512 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004513 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4514 "%s called (reason \"%s\"), but timed buffer queue has no"
4515 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004516
4517 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4518 mTimedBufferQueue.removeAt(0);
4519}
4520
4521void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4522 const TimedBuffer& buf,
4523 const char* logTag) {
4524 uint32_t bufBytes = buf.buffer()->size();
4525 uint32_t consumedAlready = buf.position();
4526
Eric Laurentb388e532012-04-14 13:32:48 -07004527 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004528 "Bad bookkeeping while updating frames pending. Timed buffer is"
4529 " only %u bytes long, but claims to have consumed %u"
4530 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004531 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004532
4533 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004534 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4535 "Bad bookkeeping while updating frames pending. Should have at"
4536 " least %u queued frames, but we think we have only %u. (update"
4537 " reason: \"%s\")",
4538 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004539
4540 mFramesPendingInQueue -= bufFrames;
4541}
4542
John Grossman4ff14ba2012-02-08 16:37:41 -08004543status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4544 const sp<IMemory>& buffer, int64_t pts) {
4545
4546 {
4547 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4548 if (!mMediaTimeTransformValid)
4549 return INVALID_OPERATION;
4550 }
4551
4552 Mutex::Autolock _l(mTimedBufferQueueLock);
4553
John Grossman1c345192012-03-27 14:00:17 -07004554 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4555 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004556 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4557
4558 return NO_ERROR;
4559}
4560
4561status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4562 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4563
John Grossman1c345192012-03-27 14:00:17 -07004564 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4565 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4566 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004567
4568 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4569 target == TimedAudioTrack::COMMON_TIME)) {
4570 return BAD_VALUE;
4571 }
4572
4573 Mutex::Autolock lock(mMediaTimeTransformLock);
4574 mMediaTimeTransform = xform;
4575 mMediaTimeTransformTarget = target;
4576 mMediaTimeTransformValid = true;
4577
4578 return NO_ERROR;
4579}
4580
4581#define min(a, b) ((a) < (b) ? (a) : (b))
4582
4583// implementation of getNextBuffer for tracks whose buffers have timestamps
4584status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4585 AudioBufferProvider::Buffer* buffer, int64_t pts)
4586{
4587 if (pts == AudioBufferProvider::kInvalidPTS) {
4588 buffer->raw = 0;
4589 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07004590 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004591 return INVALID_OPERATION;
4592 }
4593
John Grossman4ff14ba2012-02-08 16:37:41 -08004594 Mutex::Autolock _l(mTimedBufferQueueLock);
4595
John Grossman9fbdee12012-03-26 17:51:46 -07004596 ALOG_ASSERT(!mQueueHeadInFlight,
4597 "getNextBuffer called without releaseBuffer!");
4598
John Grossman4ff14ba2012-02-08 16:37:41 -08004599 while (true) {
4600
4601 // if we have no timed buffers, then fail
4602 if (mTimedBufferQueue.isEmpty()) {
4603 buffer->raw = 0;
4604 buffer->frameCount = 0;
4605 return NOT_ENOUGH_DATA;
4606 }
4607
4608 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4609
4610 // calculate the PTS of the head of the timed buffer queue expressed in
4611 // local time
4612 int64_t headLocalPTS;
4613 {
4614 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4615
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004616 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004617
4618 if (mMediaTimeTransform.a_to_b_denom == 0) {
4619 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07004620 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004621 return NO_ERROR;
4622 }
4623
4624 int64_t transformedPTS;
4625 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4626 &transformedPTS)) {
4627 // the transform failed. this shouldn't happen, but if it does
4628 // then just drop this buffer
4629 ALOGW("timedGetNextBuffer transform failed");
4630 buffer->raw = 0;
4631 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07004632 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08004633 return NO_ERROR;
4634 }
4635
4636 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4637 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4638 &headLocalPTS)) {
4639 buffer->raw = 0;
4640 buffer->frameCount = 0;
4641 return INVALID_OPERATION;
4642 }
4643 } else {
4644 headLocalPTS = transformedPTS;
4645 }
4646 }
4647
4648 // adjust the head buffer's PTS to reflect the portion of the head buffer
4649 // that has already been consumed
4650 int64_t effectivePTS = headLocalPTS +
4651 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4652
4653 // Calculate the delta in samples between the head of the input buffer
4654 // queue and the start of the next output buffer that will be written.
4655 // If the transformation fails because of over or underflow, it means
4656 // that the sample's position in the output stream is so far out of
4657 // whack that it should just be dropped.
4658 int64_t sampleDelta;
4659 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4660 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004661 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
4662 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08004663 continue;
4664 }
4665 if (!mLocalTimeToSampleTransform.doForwardTransform(
4666 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07004667 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004668 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08004669 continue;
4670 }
4671
John Grossman1c345192012-03-27 14:00:17 -07004672 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
4673 " sampleDelta=[%d.%08x]",
4674 head.pts(), head.position(), pts,
4675 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
4676 + (sampleDelta >> 32)),
4677 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08004678
4679 // if the delta between the ideal placement for the next input sample and
4680 // the current output position is within this threshold, then we will
4681 // concatenate the next input samples to the previous output
4682 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07004683 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08004684
4685 // if this is the first buffer of audio that we're emitting from this track
4686 // then it should be almost exactly on time.
4687 const int64_t kSampleStartupThreshold = 1LL << 32;
4688
4689 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07004690 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004691 // the next input is close enough to being on time, so concatenate it
4692 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07004693 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004694
John Grossman1c345192012-03-27 14:00:17 -07004695 ALOGVV("*** on time: head.pos=%d frameCount=%u",
4696 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08004697 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07004698 }
4699
4700 // Looks like our output is not on time. Reset our on timed status.
4701 // Next time we mix samples from our input queue, then should be within
4702 // the StartupThreshold.
4703 mTimedAudioOutputOnTime = false;
4704 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004705 // the gap between the current output position and the proper start of
4706 // the next input sample is too big, so fill it with silence
4707 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4708
John Grossman9fbdee12012-03-26 17:51:46 -07004709 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004710 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4711 return NO_ERROR;
4712 } else {
4713 // the next input sample is late
4714 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4715 size_t onTimeSamplePosition =
4716 head.position() + lateFrames * mCblk->frameSize;
4717
4718 if (onTimeSamplePosition > head.buffer()->size()) {
4719 // all the remaining samples in the head are too late, so
4720 // drop it and move on
4721 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004722 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08004723 continue;
4724 } else {
4725 // skip over the late samples
4726 head.setPosition(onTimeSamplePosition);
4727
4728 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07004729 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004730
4731 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4732 return NO_ERROR;
4733 }
4734 }
4735 }
4736}
4737
4738// Yield samples from the timed buffer queue head up to the given output
4739// buffer's capacity.
4740//
4741// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004742void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004743 AudioBufferProvider::Buffer* buffer) {
4744
4745 const TimedBuffer& head = mTimedBufferQueue[0];
4746
4747 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4748 head.position());
4749
4750 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4751 mCblk->frameSize);
4752 size_t framesRequested = buffer->frameCount;
4753 buffer->frameCount = min(framesLeftInHead, framesRequested);
4754
John Grossman9fbdee12012-03-26 17:51:46 -07004755 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08004756 mTimedAudioOutputOnTime = true;
4757}
4758
4759// Yield samples of silence up to the given output buffer's capacity
4760//
4761// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004762void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004763 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4764
4765 // lazily allocate a buffer filled with silence
4766 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4767 delete [] mTimedSilenceBuffer;
4768 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4769 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4770 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4771 }
4772
4773 buffer->raw = mTimedSilenceBuffer;
4774 size_t framesRequested = buffer->frameCount;
4775 buffer->frameCount = min(numFrames, framesRequested);
4776
4777 mTimedAudioOutputOnTime = false;
4778}
4779
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004780// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004781void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4782 AudioBufferProvider::Buffer* buffer) {
4783
4784 Mutex::Autolock _l(mTimedBufferQueueLock);
4785
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004786 // If the buffer which was just released is part of the buffer at the head
4787 // of the queue, be sure to update the amt of the buffer which has been
4788 // consumed. If the buffer being returned is not part of the head of the
4789 // queue, its either because the buffer is part of the silence buffer, or
4790 // because the head of the timed queue was trimmed after the mixer called
4791 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07004792 if (buffer->raw == mTimedSilenceBuffer) {
4793 ALOG_ASSERT(!mQueueHeadInFlight,
4794 "Queue head in flight during release of silence buffer!");
4795 goto done;
4796 }
4797
4798 ALOG_ASSERT(mQueueHeadInFlight,
4799 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
4800 " head in flight.");
4801
4802 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004803 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004804
4805 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07004806 void* end = reinterpret_cast<void*>(
4807 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
4808 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004809
John Grossman9fbdee12012-03-26 17:51:46 -07004810 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
4811 "released buffer not within the head of the timed buffer"
4812 " queue; qHead = [%p, %p], released buffer = %p",
4813 start, end, buffer->raw);
4814
4815 head.setPosition(head.position() +
4816 (buffer->frameCount * mCblk->frameSize));
4817 mQueueHeadInFlight = false;
4818
John Grossman1c345192012-03-27 14:00:17 -07004819 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
4820 "Bad bookkeeping during releaseBuffer! Should have at"
4821 " least %u queued frames, but we think we have only %u",
4822 buffer->frameCount, mFramesPendingInQueue);
4823
4824 mFramesPendingInQueue -= buffer->frameCount;
4825
John Grossman9fbdee12012-03-26 17:51:46 -07004826 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
4827 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07004828 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07004829 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004830 }
John Grossman9fbdee12012-03-26 17:51:46 -07004831 } else {
4832 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
4833 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08004834 }
4835
John Grossman9fbdee12012-03-26 17:51:46 -07004836done:
John Grossman4ff14ba2012-02-08 16:37:41 -08004837 buffer->raw = 0;
4838 buffer->frameCount = 0;
4839}
4840
4841uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4842 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07004843 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08004844}
4845
4846AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4847 : mPTS(0), mPosition(0) {}
4848
4849AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4850 const sp<IMemory>& buffer, int64_t pts)
4851 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4852
Mathias Agopian65ab4712010-07-14 17:59:35 -07004853// ----------------------------------------------------------------------------
4854
4855// RecordTrack constructor must be called with AudioFlinger::mLock held
4856AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004857 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004858 const sp<Client>& client,
4859 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004860 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004861 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004862 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004863 int sessionId)
4864 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004865 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004866 mOverflow(false)
4867{
4868 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004869 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
4870 if (format == AUDIO_FORMAT_PCM_16_BIT) {
4871 mCblk->frameSize = mChannelCount * sizeof(int16_t);
4872 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
4873 mCblk->frameSize = mChannelCount * sizeof(int8_t);
4874 } else {
4875 mCblk->frameSize = sizeof(int8_t);
4876 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004877 }
4878}
4879
4880AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4881{
4882 sp<ThreadBase> thread = mThread.promote();
4883 if (thread != 0) {
4884 AudioSystem::releaseInput(thread->id());
4885 }
4886}
4887
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004888// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004889status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004890{
4891 audio_track_cblk_t* cblk = this->cblk();
4892 uint32_t framesAvail;
4893 uint32_t framesReq = buffer->frameCount;
4894
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004895 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004896 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004897 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004898 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004899 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004900 }
4901
4902 framesAvail = cblk->framesAvailable_l();
4903
Glenn Kastenf6b16782011-12-15 09:51:17 -08004904 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004905 uint32_t s = cblk->server;
4906 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4907
4908 if (framesReq > framesAvail) {
4909 framesReq = framesAvail;
4910 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004911 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004912 framesReq = bufferEnd - s;
4913 }
4914
4915 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004916 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004917
4918 buffer->frameCount = framesReq;
4919 return NO_ERROR;
4920 }
4921
4922getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004923 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004924 buffer->frameCount = 0;
4925 return NOT_ENOUGH_DATA;
4926}
4927
Glenn Kasten3acbd052012-02-28 10:39:56 -08004928status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004929 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004930{
4931 sp<ThreadBase> thread = mThread.promote();
4932 if (thread != 0) {
4933 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08004934 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004935 } else {
4936 return BAD_VALUE;
4937 }
4938}
4939
4940void AudioFlinger::RecordThread::RecordTrack::stop()
4941{
4942 sp<ThreadBase> thread = mThread.promote();
4943 if (thread != 0) {
4944 RecordThread *recordThread = (RecordThread *)thread.get();
4945 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004946 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08004947 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07004948 // read from buffer
4949 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004950 }
4951}
4952
4953void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4954{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004955 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004956 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004957 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004958 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004959 mSessionId,
4960 mFrameCount,
4961 mState,
4962 mCblk->sampleRate,
4963 mCblk->server,
4964 mCblk->user);
4965}
4966
4967
4968// ----------------------------------------------------------------------------
4969
4970AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004971 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004972 DuplicatingThread *sourceThread,
4973 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004974 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004975 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004976 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07004977 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
4978 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004979 mActive(false), mSourceThread(sourceThread)
4980{
4981
Mathias Agopian65ab4712010-07-14 17:59:35 -07004982 if (mCblk != NULL) {
4983 mCblk->flags |= CBLK_DIRECTION_OUT;
4984 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004985 mOutBuffer.frameCount = 0;
4986 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004987 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004988 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4989 mCblk, mBuffer, mCblk->buffers,
4990 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004991 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004992 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004993 }
4994}
4995
4996AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4997{
4998 clearBufferQueue();
4999}
5000
Glenn Kasten3acbd052012-02-28 10:39:56 -08005001status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005002 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005003{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005004 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005005 if (status != NO_ERROR) {
5006 return status;
5007 }
5008
5009 mActive = true;
5010 mRetryCount = 127;
5011 return status;
5012}
5013
5014void AudioFlinger::PlaybackThread::OutputTrack::stop()
5015{
5016 Track::stop();
5017 clearBufferQueue();
5018 mOutBuffer.frameCount = 0;
5019 mActive = false;
5020}
5021
5022bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5023{
5024 Buffer *pInBuffer;
5025 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005026 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005027 bool outputBufferFull = false;
5028 inBuffer.frameCount = frames;
5029 inBuffer.i16 = data;
5030
5031 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5032
5033 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005034 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005035 sp<ThreadBase> thread = mThread.promote();
5036 if (thread != 0) {
5037 MixerThread *mixerThread = (MixerThread *)thread.get();
5038 if (mCblk->frameCount > frames){
5039 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5040 uint32_t startFrames = (mCblk->frameCount - frames);
5041 pInBuffer = new Buffer;
5042 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5043 pInBuffer->frameCount = startFrames;
5044 pInBuffer->i16 = pInBuffer->mBuffer;
5045 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5046 mBufferQueue.add(pInBuffer);
5047 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005048 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005049 }
5050 }
5051 }
5052 }
5053
5054 while (waitTimeLeftMs) {
5055 // First write pending buffers, then new data
5056 if (mBufferQueue.size()) {
5057 pInBuffer = mBufferQueue.itemAt(0);
5058 } else {
5059 pInBuffer = &inBuffer;
5060 }
5061
5062 if (pInBuffer->frameCount == 0) {
5063 break;
5064 }
5065
5066 if (mOutBuffer.frameCount == 0) {
5067 mOutBuffer.frameCount = pInBuffer->frameCount;
5068 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005069 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005070 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005071 outputBufferFull = true;
5072 break;
5073 }
5074 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5075 if (waitTimeLeftMs >= waitTimeMs) {
5076 waitTimeLeftMs -= waitTimeMs;
5077 } else {
5078 waitTimeLeftMs = 0;
5079 }
5080 }
5081
5082 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5083 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5084 mCblk->stepUser(outFrames);
5085 pInBuffer->frameCount -= outFrames;
5086 pInBuffer->i16 += outFrames * channelCount;
5087 mOutBuffer.frameCount -= outFrames;
5088 mOutBuffer.i16 += outFrames * channelCount;
5089
5090 if (pInBuffer->frameCount == 0) {
5091 if (mBufferQueue.size()) {
5092 mBufferQueue.removeAt(0);
5093 delete [] pInBuffer->mBuffer;
5094 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005095 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005096 } else {
5097 break;
5098 }
5099 }
5100 }
5101
5102 // If we could not write all frames, allocate a buffer and queue it for next time.
5103 if (inBuffer.frameCount) {
5104 sp<ThreadBase> thread = mThread.promote();
5105 if (thread != 0 && !thread->standby()) {
5106 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5107 pInBuffer = new Buffer;
5108 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5109 pInBuffer->frameCount = inBuffer.frameCount;
5110 pInBuffer->i16 = pInBuffer->mBuffer;
5111 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5112 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005113 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005114 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005115 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005116 }
5117 }
5118 }
5119
5120 // Calling write() with a 0 length buffer, means that no more data will be written:
5121 // If no more buffers are pending, fill output track buffer to make sure it is started
5122 // by output mixer.
5123 if (frames == 0 && mBufferQueue.size() == 0) {
5124 if (mCblk->user < mCblk->frameCount) {
5125 frames = mCblk->frameCount - mCblk->user;
5126 pInBuffer = new Buffer;
5127 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5128 pInBuffer->frameCount = frames;
5129 pInBuffer->i16 = pInBuffer->mBuffer;
5130 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5131 mBufferQueue.add(pInBuffer);
5132 } else if (mActive) {
5133 stop();
5134 }
5135 }
5136
5137 return outputBufferFull;
5138}
5139
5140status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5141{
5142 int active;
5143 status_t result;
5144 audio_track_cblk_t* cblk = mCblk;
5145 uint32_t framesReq = buffer->frameCount;
5146
Steve Block3856b092011-10-20 11:56:00 +01005147// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005148 buffer->frameCount = 0;
5149
5150 uint32_t framesAvail = cblk->framesAvailable();
5151
5152
5153 if (framesAvail == 0) {
5154 Mutex::Autolock _l(cblk->lock);
5155 goto start_loop_here;
5156 while (framesAvail == 0) {
5157 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005158 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005159 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005160 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005161 }
5162 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5163 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005164 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005165 }
5166 // read the server count again
5167 start_loop_here:
5168 framesAvail = cblk->framesAvailable_l();
5169 }
5170 }
5171
5172// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005173// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005174// }
5175
5176 if (framesReq > framesAvail) {
5177 framesReq = framesAvail;
5178 }
5179
5180 uint32_t u = cblk->user;
5181 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5182
Marco Nelissena1472d92012-03-30 14:36:54 -07005183 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005184 framesReq = bufferEnd - u;
5185 }
5186
5187 buffer->frameCount = framesReq;
5188 buffer->raw = (void *)cblk->buffer(u);
5189 return NO_ERROR;
5190}
5191
5192
5193void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5194{
5195 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005196
5197 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005198 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005199 delete [] pBuffer->mBuffer;
5200 delete pBuffer;
5201 }
5202 mBufferQueue.clear();
5203}
5204
5205// ----------------------------------------------------------------------------
5206
5207AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5208 : RefBase(),
5209 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005210 // 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 -07005211 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005212 mPid(pid),
5213 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005214{
5215 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5216}
5217
5218// Client destructor must be called with AudioFlinger::mLock held
5219AudioFlinger::Client::~Client()
5220{
5221 mAudioFlinger->removeClient_l(mPid);
5222}
5223
Glenn Kasten435dbe62012-01-30 10:15:48 -08005224sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005225{
5226 return mMemoryDealer;
5227}
5228
John Grossman4ff14ba2012-02-08 16:37:41 -08005229// Reserve one of the limited slots for a timed audio track associated
5230// with this client
5231bool AudioFlinger::Client::reserveTimedTrack()
5232{
5233 const int kMaxTimedTracksPerClient = 4;
5234
5235 Mutex::Autolock _l(mTimedTrackLock);
5236
5237 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5238 ALOGW("can not create timed track - pid %d has exceeded the limit",
5239 mPid);
5240 return false;
5241 }
5242
5243 mTimedTrackCount++;
5244 return true;
5245}
5246
5247// Release a slot for a timed audio track
5248void AudioFlinger::Client::releaseTimedTrack()
5249{
5250 Mutex::Autolock _l(mTimedTrackLock);
5251 mTimedTrackCount--;
5252}
5253
Mathias Agopian65ab4712010-07-14 17:59:35 -07005254// ----------------------------------------------------------------------------
5255
5256AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5257 const sp<IAudioFlingerClient>& client,
5258 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005259 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005260{
5261}
5262
5263AudioFlinger::NotificationClient::~NotificationClient()
5264{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005265}
5266
5267void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5268{
5269 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005270 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005271}
5272
5273// ----------------------------------------------------------------------------
5274
5275AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5276 : BnAudioTrack(),
5277 mTrack(track)
5278{
5279}
5280
5281AudioFlinger::TrackHandle::~TrackHandle() {
5282 // just stop the track on deletion, associated resources
5283 // will be freed from the main thread once all pending buffers have
5284 // been played. Unless it's not in the active track list, in which
5285 // case we free everything now...
5286 mTrack->destroy();
5287}
5288
Glenn Kasten90716c52012-01-26 13:40:12 -08005289sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5290 return mTrack->getCblk();
5291}
5292
Glenn Kasten3acbd052012-02-28 10:39:56 -08005293status_t AudioFlinger::TrackHandle::start() {
5294 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005295}
5296
5297void AudioFlinger::TrackHandle::stop() {
5298 mTrack->stop();
5299}
5300
5301void AudioFlinger::TrackHandle::flush() {
5302 mTrack->flush();
5303}
5304
5305void AudioFlinger::TrackHandle::mute(bool e) {
5306 mTrack->mute(e);
5307}
5308
5309void AudioFlinger::TrackHandle::pause() {
5310 mTrack->pause();
5311}
5312
Mathias Agopian65ab4712010-07-14 17:59:35 -07005313status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5314{
5315 return mTrack->attachAuxEffect(EffectId);
5316}
5317
John Grossman4ff14ba2012-02-08 16:37:41 -08005318status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5319 sp<IMemory>* buffer) {
5320 if (!mTrack->isTimedTrack())
5321 return INVALID_OPERATION;
5322
5323 PlaybackThread::TimedTrack* tt =
5324 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5325 return tt->allocateTimedBuffer(size, buffer);
5326}
5327
5328status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5329 int64_t pts) {
5330 if (!mTrack->isTimedTrack())
5331 return INVALID_OPERATION;
5332
5333 PlaybackThread::TimedTrack* tt =
5334 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5335 return tt->queueTimedBuffer(buffer, pts);
5336}
5337
5338status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5339 const LinearTransform& xform, int target) {
5340
5341 if (!mTrack->isTimedTrack())
5342 return INVALID_OPERATION;
5343
5344 PlaybackThread::TimedTrack* tt =
5345 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5346 return tt->setMediaTimeTransform(
5347 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5348}
5349
Mathias Agopian65ab4712010-07-14 17:59:35 -07005350status_t AudioFlinger::TrackHandle::onTransact(
5351 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5352{
5353 return BnAudioTrack::onTransact(code, data, reply, flags);
5354}
5355
5356// ----------------------------------------------------------------------------
5357
5358sp<IAudioRecord> AudioFlinger::openRecord(
5359 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005360 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005361 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005362 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005363 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005364 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005365 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005366 int *sessionId,
5367 status_t *status)
5368{
5369 sp<RecordThread::RecordTrack> recordTrack;
5370 sp<RecordHandle> recordHandle;
5371 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372 status_t lStatus;
5373 RecordThread *thread;
5374 size_t inFrameCount;
5375 int lSessionId;
5376
5377 // check calling permissions
5378 if (!recordingAllowed()) {
5379 lStatus = PERMISSION_DENIED;
5380 goto Exit;
5381 }
5382
5383 // add client to list
5384 { // scope for mLock
5385 Mutex::Autolock _l(mLock);
5386 thread = checkRecordThread_l(input);
5387 if (thread == NULL) {
5388 lStatus = BAD_VALUE;
5389 goto Exit;
5390 }
5391
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005392 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005393
5394 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005395 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005396 lSessionId = *sessionId;
5397 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005398 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005399 if (sessionId != NULL) {
5400 *sessionId = lSessionId;
5401 }
5402 }
5403 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005404 recordTrack = thread->createRecordTrack_l(client,
5405 sampleRate,
5406 format,
5407 channelMask,
5408 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005409 lSessionId,
5410 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005411 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005412 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005413 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5414 // destructor is called by the TrackBase destructor with mLock held
5415 client.clear();
5416 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005417 goto Exit;
5418 }
5419
5420 // return to handle to client
5421 recordHandle = new RecordHandle(recordTrack);
5422 lStatus = NO_ERROR;
5423
5424Exit:
5425 if (status) {
5426 *status = lStatus;
5427 }
5428 return recordHandle;
5429}
5430
5431// ----------------------------------------------------------------------------
5432
5433AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5434 : BnAudioRecord(),
5435 mRecordTrack(recordTrack)
5436{
5437}
5438
5439AudioFlinger::RecordHandle::~RecordHandle() {
5440 stop();
5441}
5442
Glenn Kasten90716c52012-01-26 13:40:12 -08005443sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5444 return mRecordTrack->getCblk();
5445}
5446
Glenn Kasten3acbd052012-02-28 10:39:56 -08005447status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005448 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005449 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005450}
5451
5452void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005453 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005454 mRecordTrack->stop();
5455}
5456
Mathias Agopian65ab4712010-07-14 17:59:35 -07005457status_t AudioFlinger::RecordHandle::onTransact(
5458 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5459{
5460 return BnAudioRecord::onTransact(code, data, reply, flags);
5461}
5462
5463// ----------------------------------------------------------------------------
5464
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005465AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5466 AudioStreamIn *input,
5467 uint32_t sampleRate,
5468 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005469 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005470 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005471 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005472 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5473 // mRsmpInIndex and mInputBytes set by readInputParameters()
5474 mReqChannelCount(popcount(channels)),
5475 mReqSampleRate(sampleRate)
5476 // mBytesRead is only meaningful while active, and so is cleared in start()
5477 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005478{
Glenn Kasten480b4682012-02-28 12:30:08 -08005479 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005480
Mathias Agopian65ab4712010-07-14 17:59:35 -07005481 readInputParameters();
5482}
5483
5484
5485AudioFlinger::RecordThread::~RecordThread()
5486{
5487 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005488 delete mResampler;
5489 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005490}
5491
5492void AudioFlinger::RecordThread::onFirstRef()
5493{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005494 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005495}
5496
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005497status_t AudioFlinger::RecordThread::readyToRun()
5498{
5499 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005500 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005501 return status;
5502}
5503
Mathias Agopian65ab4712010-07-14 17:59:35 -07005504bool AudioFlinger::RecordThread::threadLoop()
5505{
5506 AudioBufferProvider::Buffer buffer;
5507 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005508 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005509
Eric Laurent44d98482010-09-30 16:12:31 -07005510 nsecs_t lastWarning = 0;
5511
Eric Laurentfeb0db62011-07-22 09:04:31 -07005512 acquireWakeLock();
5513
Mathias Agopian65ab4712010-07-14 17:59:35 -07005514 // start recording
5515 while (!exitPending()) {
5516
5517 processConfigEvents();
5518
5519 { // scope for mLock
5520 Mutex::Autolock _l(mLock);
5521 checkForNewParameters_l();
5522 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5523 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005524 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005525 mStandby = true;
5526 }
5527
5528 if (exitPending()) break;
5529
Eric Laurentfeb0db62011-07-22 09:04:31 -07005530 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005531 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005532 // go to sleep
5533 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005534 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005535 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005536 continue;
5537 }
5538 if (mActiveTrack != 0) {
5539 if (mActiveTrack->mState == TrackBase::PAUSING) {
5540 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005541 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005542 mStandby = true;
5543 }
5544 mActiveTrack.clear();
5545 mStartStopCond.broadcast();
5546 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5547 if (mReqChannelCount != mActiveTrack->channelCount()) {
5548 mActiveTrack.clear();
5549 mStartStopCond.broadcast();
5550 } else if (mBytesRead != 0) {
5551 // record start succeeds only if first read from audio input
5552 // succeeds
5553 if (mBytesRead > 0) {
5554 mActiveTrack->mState = TrackBase::ACTIVE;
5555 } else {
5556 mActiveTrack.clear();
5557 }
5558 mStartStopCond.broadcast();
5559 }
5560 mStandby = false;
5561 }
5562 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005563 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005564 }
5565
5566 if (mActiveTrack != 0) {
5567 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5568 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005569 unlockEffectChains(effectChains);
5570 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005571 continue;
5572 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005573 for (size_t i = 0; i < effectChains.size(); i ++) {
5574 effectChains[i]->process_l();
5575 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005576
Mathias Agopian65ab4712010-07-14 17:59:35 -07005577 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005578 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005579 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08005580 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005581 // no resampling
5582 while (framesOut) {
5583 size_t framesIn = mFrameCount - mRsmpInIndex;
5584 if (framesIn) {
5585 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5586 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5587 if (framesIn > framesOut)
5588 framesIn = framesOut;
5589 mRsmpInIndex += framesIn;
5590 framesOut -= framesIn;
5591 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07005592 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005593 memcpy(dst, src, framesIn * mFrameSize);
5594 } else {
5595 int16_t *src16 = (int16_t *)src;
5596 int16_t *dst16 = (int16_t *)dst;
5597 if (mChannelCount == 1) {
5598 while (framesIn--) {
5599 *dst16++ = *src16;
5600 *dst16++ = *src16++;
5601 }
5602 } else {
5603 while (framesIn--) {
5604 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5605 src16 += 2;
5606 }
5607 }
5608 }
5609 }
5610 if (framesOut && mFrameCount == mRsmpInIndex) {
5611 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005612 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005613 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005614 framesOut = 0;
5615 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005616 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005617 mRsmpInIndex = 0;
5618 }
5619 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005620 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005621 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5622 // Force input into standby so that it tries to
5623 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005624 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005625 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005626 }
5627 mRsmpInIndex = mFrameCount;
5628 framesOut = 0;
5629 buffer.frameCount = 0;
5630 }
5631 }
5632 }
5633 } else {
5634 // resampling
5635
5636 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5637 // alter output frame count as if we were expecting stereo samples
5638 if (mChannelCount == 1 && mReqChannelCount == 1) {
5639 framesOut >>= 1;
5640 }
5641 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5642 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5643 // are 32 bit aligned which should be always true.
5644 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005645 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005646 // the resampler always outputs stereo samples: do post stereo to mono conversion
5647 int16_t *src = (int16_t *)mRsmpOutBuffer;
5648 int16_t *dst = buffer.i16;
5649 while (framesOut--) {
5650 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5651 src += 2;
5652 }
5653 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005654 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005655 }
5656
5657 }
Eric Laurenta011e352012-03-29 15:51:43 -07005658 if (mFramestoDrop == 0) {
5659 mActiveTrack->releaseBuffer(&buffer);
5660 } else {
5661 if (mFramestoDrop > 0) {
5662 mFramestoDrop -= buffer.frameCount;
5663 if (mFramestoDrop < 0) {
5664 mFramestoDrop = 0;
5665 }
5666 }
5667 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005668 mActiveTrack->overflow();
5669 }
5670 // client isn't retrieving buffers fast enough
5671 else {
Eric Laurent44d98482010-09-30 16:12:31 -07005672 if (!mActiveTrack->setOverflow()) {
5673 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08005674 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005675 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07005676 lastWarning = now;
5677 }
5678 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005679 // Release the processor for a while before asking for a new buffer.
5680 // This will give the application more chance to read from the buffer and
5681 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005682 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005683 }
5684 }
Eric Laurentec437d82011-07-26 20:54:46 -07005685 // enable changes in effect chain
5686 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005687 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005688 }
5689
5690 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005691 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005692 }
5693 mActiveTrack.clear();
5694
5695 mStartStopCond.broadcast();
5696
Eric Laurentfeb0db62011-07-22 09:04:31 -07005697 releaseWakeLock();
5698
Steve Block3856b092011-10-20 11:56:00 +01005699 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005700 return false;
5701}
5702
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005703
5704sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5705 const sp<AudioFlinger::Client>& client,
5706 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005707 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005708 int channelMask,
5709 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005710 int sessionId,
5711 status_t *status)
5712{
5713 sp<RecordTrack> track;
5714 status_t lStatus;
5715
5716 lStatus = initCheck();
5717 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005718 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005719 goto Exit;
5720 }
5721
5722 { // scope for mLock
5723 Mutex::Autolock _l(mLock);
5724
5725 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005726 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005727
Glenn Kasten7378ca52012-01-20 13:44:40 -08005728 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005729 lStatus = NO_MEMORY;
5730 goto Exit;
5731 }
5732
5733 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005734 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5735 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005736 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005737 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5738 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005739 }
5740 lStatus = NO_ERROR;
5741
5742Exit:
5743 if (status) {
5744 *status = lStatus;
5745 }
5746 return track;
5747}
5748
Eric Laurenta011e352012-03-29 15:51:43 -07005749status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08005750 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005751 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005752{
Glenn Kasten58912562012-04-03 10:45:00 -07005753 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005754 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005755 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07005756
5757 if (event == AudioSystem::SYNC_EVENT_NONE) {
5758 mSyncStartEvent.clear();
5759 mFramestoDrop = 0;
5760 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
5761 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
5762 triggerSession,
5763 recordTrack->sessionId(),
5764 syncStartEventCallback,
5765 this);
5766 mFramestoDrop = -1;
5767 }
5768
Mathias Agopian65ab4712010-07-14 17:59:35 -07005769 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005770 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005771 if (mActiveTrack != 0) {
5772 if (recordTrack != mActiveTrack.get()) {
5773 status = -EBUSY;
5774 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5775 mActiveTrack->mState = TrackBase::ACTIVE;
5776 }
5777 return status;
5778 }
5779
5780 recordTrack->mState = TrackBase::IDLE;
5781 mActiveTrack = recordTrack;
5782 mLock.unlock();
5783 status_t status = AudioSystem::startInput(mId);
5784 mLock.lock();
5785 if (status != NO_ERROR) {
5786 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07005787 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005788 return status;
5789 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005790 mRsmpInIndex = mFrameCount;
5791 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005792 if (mResampler != NULL) {
5793 mResampler->reset();
5794 }
5795 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005796 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005797 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005798 mWaitWorkCV.signal();
5799 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005800 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005801 mActiveTrack.clear();
5802 status = INVALID_OPERATION;
5803 goto startError;
5804 }
5805 mStartStopCond.wait(mLock);
5806 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005807 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005808 status = BAD_VALUE;
5809 goto startError;
5810 }
Steve Block3856b092011-10-20 11:56:00 +01005811 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005812 return status;
5813 }
5814startError:
5815 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07005816 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005817 return status;
5818}
5819
Eric Laurenta011e352012-03-29 15:51:43 -07005820void AudioFlinger::RecordThread::clearSyncStartEvent()
5821{
5822 if (mSyncStartEvent != 0) {
5823 mSyncStartEvent->cancel();
5824 }
5825 mSyncStartEvent.clear();
5826}
5827
5828void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5829{
5830 sp<SyncEvent> strongEvent = event.promote();
5831
5832 if (strongEvent != 0) {
5833 RecordThread *me = (RecordThread *)strongEvent->cookie();
5834 me->handleSyncStartEvent(strongEvent);
5835 }
5836}
5837
5838void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
5839{
5840 ALOGV("handleSyncStartEvent() mActiveTrack %p session %d event->listenerSession() %d",
5841 mActiveTrack.get(),
5842 mActiveTrack.get() ? mActiveTrack->sessionId() : 0,
5843 event->listenerSession());
5844
5845 if (mActiveTrack != 0 &&
5846 event == mSyncStartEvent) {
5847 // TODO: use actual buffer filling status instead of 2 buffers when info is available
5848 // from audio HAL
5849 mFramestoDrop = mFrameCount * 2;
5850 mSyncStartEvent.clear();
5851 }
5852}
5853
Mathias Agopian65ab4712010-07-14 17:59:35 -07005854void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005855 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005856 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005857 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005858 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005859 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5860 mActiveTrack->mState = TrackBase::PAUSING;
5861 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005862 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005863 return;
5864 }
5865 mStartStopCond.wait(mLock);
5866 // if we have been restarted, recordTrack == mActiveTrack.get() here
5867 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5868 mLock.unlock();
5869 AudioSystem::stopInput(mId);
5870 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005871 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005872 }
5873 }
5874 }
5875}
5876
Eric Laurenta011e352012-03-29 15:51:43 -07005877bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
5878{
5879 return false;
5880}
5881
5882status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
5883{
5884 if (!isValidSyncEvent(event)) {
5885 return BAD_VALUE;
5886 }
5887
5888 Mutex::Autolock _l(mLock);
5889
5890 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
5891 mTrack->setSyncEvent(event);
5892 return NO_ERROR;
5893 }
5894 return NAME_NOT_FOUND;
5895}
5896
Mathias Agopian65ab4712010-07-14 17:59:35 -07005897status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5898{
5899 const size_t SIZE = 256;
5900 char buffer[SIZE];
5901 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005902
5903 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5904 result.append(buffer);
5905
5906 if (mActiveTrack != 0) {
5907 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005908 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005909 mActiveTrack->dump(buffer, SIZE);
5910 result.append(buffer);
5911
5912 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5913 result.append(buffer);
5914 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5915 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005916 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005917 result.append(buffer);
5918 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5919 result.append(buffer);
5920 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5921 result.append(buffer);
5922
5923
5924 } else {
5925 result.append("No record client\n");
5926 }
5927 write(fd, result.string(), result.size());
5928
5929 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005930 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005931
5932 return NO_ERROR;
5933}
5934
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005935// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005936status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005937{
5938 size_t framesReq = buffer->frameCount;
5939 size_t framesReady = mFrameCount - mRsmpInIndex;
5940 int channelCount;
5941
5942 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005943 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005944 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005945 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005946 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5947 // Force input into standby so that it tries to
5948 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005949 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005950 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005951 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005952 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005953 buffer->frameCount = 0;
5954 return NOT_ENOUGH_DATA;
5955 }
5956 mRsmpInIndex = 0;
5957 framesReady = mFrameCount;
5958 }
5959
5960 if (framesReq > framesReady) {
5961 framesReq = framesReady;
5962 }
5963
5964 if (mChannelCount == 1 && mReqChannelCount == 2) {
5965 channelCount = 1;
5966 } else {
5967 channelCount = 2;
5968 }
5969 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5970 buffer->frameCount = framesReq;
5971 return NO_ERROR;
5972}
5973
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005974// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07005975void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5976{
5977 mRsmpInIndex += buffer->frameCount;
5978 buffer->frameCount = 0;
5979}
5980
5981bool AudioFlinger::RecordThread::checkForNewParameters_l()
5982{
5983 bool reconfig = false;
5984
5985 while (!mNewParameters.isEmpty()) {
5986 status_t status = NO_ERROR;
5987 String8 keyValuePair = mNewParameters[0];
5988 AudioParameter param = AudioParameter(keyValuePair);
5989 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005990 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005991 int reqSamplingRate = mReqSampleRate;
5992 int reqChannelCount = mReqChannelCount;
5993
5994 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5995 reqSamplingRate = value;
5996 reconfig = true;
5997 }
5998 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08005999 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006000 reconfig = true;
6001 }
6002 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006003 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006004 reconfig = true;
6005 }
6006 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6007 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006008 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006009 // if frame count is changed after track creation
6010 if (mActiveTrack != 0) {
6011 status = INVALID_OPERATION;
6012 } else {
6013 reconfig = true;
6014 }
6015 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006016 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6017 // forward device change to effects that have requested to be
6018 // aware of attached audio device.
6019 for (size_t i = 0; i < mEffectChains.size(); i++) {
6020 mEffectChains[i]->setDevice_l(value);
6021 }
6022 // store input device and output device but do not forward output device to audio HAL.
6023 // Note that status is ignored by the caller for output device
6024 // (see AudioFlinger::setParameters()
6025 if (value & AUDIO_DEVICE_OUT_ALL) {
6026 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6027 status = BAD_VALUE;
6028 } else {
6029 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006030 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6031 if (mTrack != NULL) {
6032 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006033 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006034 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6035 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6036 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006037 }
6038 mDevice |= (uint32_t)value;
6039 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006040 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006041 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006042 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006043 mInput->stream->common.standby(&mInput->stream->common);
6044 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6045 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006046 }
6047 if (reconfig) {
6048 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006049 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006050 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006051 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006052 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6053 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006054 status = NO_ERROR;
6055 }
6056 if (status == NO_ERROR) {
6057 readInputParameters();
6058 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6059 }
6060 }
6061 }
6062
6063 mNewParameters.removeAt(0);
6064
6065 mParamStatus = status;
6066 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006067 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6068 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006069 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006070 }
6071 return reconfig;
6072}
6073
6074String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6075{
Dima Zavinfce7a472011-04-19 22:30:36 -07006076 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006077 String8 out_s8 = String8();
6078
6079 Mutex::Autolock _l(mLock);
6080 if (initCheck() != NO_ERROR) {
6081 return out_s8;
6082 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006083
Dima Zavin799a70e2011-04-18 16:57:27 -07006084 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006085 out_s8 = String8(s);
6086 free(s);
6087 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006088}
6089
6090void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6091 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006092 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006093
6094 switch (event) {
6095 case AudioSystem::INPUT_OPENED:
6096 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006097 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006098 desc.samplingRate = mSampleRate;
6099 desc.format = mFormat;
6100 desc.frameCount = mFrameCount;
6101 desc.latency = 0;
6102 param2 = &desc;
6103 break;
6104
6105 case AudioSystem::INPUT_CLOSED:
6106 default:
6107 break;
6108 }
6109 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6110}
6111
6112void AudioFlinger::RecordThread::readInputParameters()
6113{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006114 delete mRsmpInBuffer;
6115 // mRsmpInBuffer is always assigned a new[] below
6116 delete mRsmpOutBuffer;
6117 mRsmpOutBuffer = NULL;
6118 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006119 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120
Dima Zavin799a70e2011-04-18 16:57:27 -07006121 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006122 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6123 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006124 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006125 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006126 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006127 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006128 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006129 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6130
Glenn Kasten53d76db2012-03-08 12:32:47 -08006131 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006132 {
6133 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006134 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6135 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006136 if (mChannelCount == 1 && mReqChannelCount == 2) {
6137 channelCount = 1;
6138 } else {
6139 channelCount = 2;
6140 }
6141 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6142 mResampler->setSampleRate(mSampleRate);
6143 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6144 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6145
6146 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6147 if (mChannelCount == 1 && mReqChannelCount == 1) {
6148 mFrameCount >>= 1;
6149 }
6150
6151 }
6152 mRsmpInIndex = mFrameCount;
6153}
6154
6155unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6156{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006157 Mutex::Autolock _l(mLock);
6158 if (initCheck() != NO_ERROR) {
6159 return 0;
6160 }
6161
Dima Zavin799a70e2011-04-18 16:57:27 -07006162 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006163}
6164
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006165uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6166{
6167 Mutex::Autolock _l(mLock);
6168 uint32_t result = 0;
6169 if (getEffectChain_l(sessionId) != 0) {
6170 result = EFFECT_SESSION;
6171 }
6172
6173 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6174 result |= TRACK_SESSION;
6175 }
6176
6177 return result;
6178}
6179
Eric Laurent59bd0da2011-08-01 09:52:20 -07006180AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6181{
6182 Mutex::Autolock _l(mLock);
6183 return mTrack;
6184}
6185
Glenn Kastenaed850d2012-01-26 09:46:34 -08006186AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006187{
6188 Mutex::Autolock _l(mLock);
6189 return mInput;
6190}
6191
6192AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6193{
6194 Mutex::Autolock _l(mLock);
6195 AudioStreamIn *input = mInput;
6196 mInput = NULL;
6197 return input;
6198}
6199
6200// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006201audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006202{
6203 if (mInput == NULL) {
6204 return NULL;
6205 }
6206 return &mInput->stream->common;
6207}
6208
6209
Mathias Agopian65ab4712010-07-14 17:59:35 -07006210// ----------------------------------------------------------------------------
6211
Eric Laurenta4c5a552012-03-29 10:12:40 -07006212audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6213{
6214 if (!settingsAllowed()) {
6215 return 0;
6216 }
6217 Mutex::Autolock _l(mLock);
6218 return loadHwModule_l(name);
6219}
6220
6221// loadHwModule_l() must be called with AudioFlinger::mLock held
6222audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6223{
6224 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6225 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6226 ALOGW("loadHwModule() module %s already loaded", name);
6227 return mAudioHwDevs.keyAt(i);
6228 }
6229 }
6230
Eric Laurenta4c5a552012-03-29 10:12:40 -07006231 audio_hw_device_t *dev;
6232
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006233 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006234 if (rc) {
6235 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6236 return 0;
6237 }
6238
6239 mHardwareStatus = AUDIO_HW_INIT;
6240 rc = dev->init_check(dev);
6241 mHardwareStatus = AUDIO_HW_IDLE;
6242 if (rc) {
6243 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6244 return 0;
6245 }
6246
6247 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6248 (NULL != dev->set_master_volume)) {
6249 AutoMutex lock(mHardwareLock);
6250 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6251 dev->set_master_volume(dev, mMasterVolume);
6252 mHardwareStatus = AUDIO_HW_IDLE;
6253 }
6254
6255 audio_module_handle_t handle = nextUniqueId();
6256 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6257
6258 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006259 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006260
6261 return handle;
6262
6263}
6264
6265audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6266 audio_devices_t *pDevices,
6267 uint32_t *pSamplingRate,
6268 audio_format_t *pFormat,
6269 audio_channel_mask_t *pChannelMask,
6270 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006271 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006272{
6273 status_t status;
6274 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006275 struct audio_config config = {
6276 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6277 channel_mask: pChannelMask ? *pChannelMask : 0,
6278 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6279 };
6280 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006281 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006282
Eric Laurenta4c5a552012-03-29 10:12:40 -07006283 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6284 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006285 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006286 config.sample_rate,
6287 config.format,
6288 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006289 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006290
6291 if (pDevices == NULL || *pDevices == 0) {
6292 return 0;
6293 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006294
Mathias Agopian65ab4712010-07-14 17:59:35 -07006295 Mutex::Autolock _l(mLock);
6296
Eric Laurenta4c5a552012-03-29 10:12:40 -07006297 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006298 if (outHwDev == NULL)
6299 return 0;
6300
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006301 audio_io_handle_t id = nextUniqueId();
6302
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006303 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006304
6305 status = outHwDev->open_output_stream(outHwDev,
6306 id,
6307 *pDevices,
6308 (audio_output_flags_t)flags,
6309 &config,
6310 &outStream);
6311
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006312 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006313 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006314 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006315 config.sample_rate,
6316 config.format,
6317 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006318 status);
6319
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006320 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006321 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006322
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006323 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006324 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6325 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006326 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006327 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006328 } else {
6329 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006330 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006331 }
6332 mPlaybackThreads.add(id, thread);
6333
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006334 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6335 if (pFormat != NULL) *pFormat = config.format;
6336 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006337 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006338
6339 // notify client processes of the new output creation
6340 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006341
6342 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006343 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006344 ALOGI("Using module %d has the primary audio interface", module);
6345 mPrimaryHardwareDev = outHwDev;
6346
6347 AutoMutex lock(mHardwareLock);
6348 mHardwareStatus = AUDIO_HW_SET_MODE;
6349 outHwDev->set_mode(outHwDev, mMode);
6350
6351 // Determine the level of master volume support the primary audio HAL has,
6352 // and set the initial master volume at the same time.
6353 float initialVolume = 1.0;
6354 mMasterVolumeSupportLvl = MVS_NONE;
6355
6356 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6357 if ((NULL != outHwDev->get_master_volume) &&
6358 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6359 mMasterVolumeSupportLvl = MVS_FULL;
6360 } else {
6361 mMasterVolumeSupportLvl = MVS_SETONLY;
6362 initialVolume = 1.0;
6363 }
6364
6365 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6366 if ((NULL == outHwDev->set_master_volume) ||
6367 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6368 mMasterVolumeSupportLvl = MVS_NONE;
6369 }
6370 // now that we have a primary device, initialize master volume on other devices
6371 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6372 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6373
6374 if ((dev != mPrimaryHardwareDev) &&
6375 (NULL != dev->set_master_volume)) {
6376 dev->set_master_volume(dev, initialVolume);
6377 }
6378 }
6379 mHardwareStatus = AUDIO_HW_IDLE;
6380 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6381 ? initialVolume
6382 : 1.0;
6383 mMasterVolume = initialVolume;
6384 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006385 return id;
6386 }
6387
6388 return 0;
6389}
6390
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006391audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6392 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006393{
6394 Mutex::Autolock _l(mLock);
6395 MixerThread *thread1 = checkMixerThread_l(output1);
6396 MixerThread *thread2 = checkMixerThread_l(output2);
6397
6398 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006399 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006400 return 0;
6401 }
6402
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006403 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006404 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6405 thread->addOutputTrack(thread2);
6406 mPlaybackThreads.add(id, thread);
6407 // notify client processes of the new output creation
6408 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6409 return id;
6410}
6411
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006412status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006413{
6414 // keep strong reference on the playback thread so that
6415 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006416 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006417 {
6418 Mutex::Autolock _l(mLock);
6419 thread = checkPlaybackThread_l(output);
6420 if (thread == NULL) {
6421 return BAD_VALUE;
6422 }
6423
Steve Block3856b092011-10-20 11:56:00 +01006424 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006425
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006426 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006427 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006428 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006429 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6430 dupThread->removeOutputTrack((MixerThread *)thread.get());
6431 }
6432 }
6433 }
Glenn Kastena1117922012-01-26 10:53:32 -08006434 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006435 mPlaybackThreads.removeItem(output);
6436 }
6437 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006438 // The thread entity (active unit of execution) is no longer running here,
6439 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006440
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006441 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006442 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006443 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006444 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006445 out->hwDev->close_output_stream(out->hwDev, out->stream);
6446 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006447 }
6448 return NO_ERROR;
6449}
6450
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006451status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006452{
6453 Mutex::Autolock _l(mLock);
6454 PlaybackThread *thread = checkPlaybackThread_l(output);
6455
6456 if (thread == NULL) {
6457 return BAD_VALUE;
6458 }
6459
Steve Block3856b092011-10-20 11:56:00 +01006460 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006461 thread->suspend();
6462
6463 return NO_ERROR;
6464}
6465
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006466status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006467{
6468 Mutex::Autolock _l(mLock);
6469 PlaybackThread *thread = checkPlaybackThread_l(output);
6470
6471 if (thread == NULL) {
6472 return BAD_VALUE;
6473 }
6474
Steve Block3856b092011-10-20 11:56:00 +01006475 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006476
6477 thread->restore();
6478
6479 return NO_ERROR;
6480}
6481
Eric Laurenta4c5a552012-03-29 10:12:40 -07006482audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6483 audio_devices_t *pDevices,
6484 uint32_t *pSamplingRate,
6485 audio_format_t *pFormat,
6486 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006487{
6488 status_t status;
6489 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006490 struct audio_config config = {
6491 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6492 channel_mask: pChannelMask ? *pChannelMask : 0,
6493 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6494 };
6495 uint32_t reqSamplingRate = config.sample_rate;
6496 audio_format_t reqFormat = config.format;
6497 audio_channel_mask_t reqChannels = config.channel_mask;
6498 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006499 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006500
6501 if (pDevices == NULL || *pDevices == 0) {
6502 return 0;
6503 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006504
Mathias Agopian65ab4712010-07-14 17:59:35 -07006505 Mutex::Autolock _l(mLock);
6506
Eric Laurenta4c5a552012-03-29 10:12:40 -07006507 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006508 if (inHwDev == NULL)
6509 return 0;
6510
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006511 audio_io_handle_t id = nextUniqueId();
6512
6513 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006514 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006515 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006516 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006517 config.sample_rate,
6518 config.format,
6519 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006520 status);
6521
6522 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6523 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6524 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006525 if (status == BAD_VALUE &&
6526 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6527 (config.sample_rate <= 2 * reqSamplingRate) &&
6528 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006529 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006530 inStream = NULL;
6531 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006532 }
6533
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006534 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006535 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6536
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006537 // Start record thread
6538 // RecorThread require both input and output device indication to forward to audio
6539 // pre processing modules
6540 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6541 thread = new RecordThread(this,
6542 input,
6543 reqSamplingRate,
6544 reqChannels,
6545 id,
6546 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006547 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006548 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006549 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006550 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006551 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006552
Dima Zavin799a70e2011-04-18 16:57:27 -07006553 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006554
6555 // notify client processes of the new input creation
6556 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6557 return id;
6558 }
6559
6560 return 0;
6561}
6562
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006563status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006564{
6565 // keep strong reference on the record thread so that
6566 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006567 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006568 {
6569 Mutex::Autolock _l(mLock);
6570 thread = checkRecordThread_l(input);
6571 if (thread == NULL) {
6572 return BAD_VALUE;
6573 }
6574
Steve Block3856b092011-10-20 11:56:00 +01006575 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08006576 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006577 mRecordThreads.removeItem(input);
6578 }
6579 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006580 // The thread entity (active unit of execution) is no longer running here,
6581 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006582
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006583 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006584 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006585 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006586 in->hwDev->close_input_stream(in->hwDev, in->stream);
6587 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006588
6589 return NO_ERROR;
6590}
6591
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006592status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006593{
6594 Mutex::Autolock _l(mLock);
6595 MixerThread *dstThread = checkMixerThread_l(output);
6596 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006597 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006598 return BAD_VALUE;
6599 }
6600
Steve Block3856b092011-10-20 11:56:00 +01006601 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006602 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
6603
6604 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6605 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08006606 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006607 MixerThread *srcThread = (MixerThread *)thread;
6608 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006609 }
Eric Laurentde070132010-07-13 04:45:46 -07006610 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006611
6612 return NO_ERROR;
6613}
6614
6615
6616int AudioFlinger::newAudioSessionId()
6617{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006618 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006619}
6620
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006621void AudioFlinger::acquireAudioSessionId(int audioSession)
6622{
6623 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006624 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006625 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006626 size_t num = mAudioSessionRefs.size();
6627 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006628 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006629 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6630 ref->mCnt++;
6631 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006632 return;
6633 }
6634 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006635 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6636 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006637}
6638
6639void AudioFlinger::releaseAudioSessionId(int audioSession)
6640{
6641 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006642 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006643 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006644 size_t num = mAudioSessionRefs.size();
6645 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006646 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006647 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6648 ref->mCnt--;
6649 ALOGV(" decremented refcount to %d", ref->mCnt);
6650 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006651 mAudioSessionRefs.removeAt(i);
6652 delete ref;
6653 purgeStaleEffects_l();
6654 }
6655 return;
6656 }
6657 }
Steve Block5ff1dd52012-01-05 23:22:43 +00006658 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006659}
6660
6661void AudioFlinger::purgeStaleEffects_l() {
6662
Steve Block3856b092011-10-20 11:56:00 +01006663 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006664
6665 Vector< sp<EffectChain> > chains;
6666
6667 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6668 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6669 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6670 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07006671 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6672 chains.push(ec);
6673 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006674 }
6675 }
6676 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6677 sp<RecordThread> t = mRecordThreads.valueAt(i);
6678 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6679 sp<EffectChain> ec = t->mEffectChains[j];
6680 chains.push(ec);
6681 }
6682 }
6683
6684 for (size_t i = 0; i < chains.size(); i++) {
6685 sp<EffectChain> ec = chains[i];
6686 int sessionid = ec->sessionId();
6687 sp<ThreadBase> t = ec->mThread.promote();
6688 if (t == 0) {
6689 continue;
6690 }
6691 size_t numsessionrefs = mAudioSessionRefs.size();
6692 bool found = false;
6693 for (size_t k = 0; k < numsessionrefs; k++) {
6694 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006695 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01006696 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006697 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006698 found = true;
6699 break;
6700 }
6701 }
6702 if (!found) {
6703 // remove all effects from the chain
6704 while (ec->mEffects.size()) {
6705 sp<EffectModule> effect = ec->mEffects[0];
6706 effect->unPin();
6707 Mutex::Autolock _l (t->mLock);
6708 t->removeEffect_l(effect);
6709 for (size_t j = 0; j < effect->mHandles.size(); j++) {
6710 sp<EffectHandle> handle = effect->mHandles[j].promote();
6711 if (handle != 0) {
6712 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07006713 if (handle->mHasControl && handle->mEnabled) {
6714 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
6715 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006716 }
6717 }
6718 AudioSystem::unregisterEffect(effect->id());
6719 }
6720 }
6721 }
6722 return;
6723}
6724
Mathias Agopian65ab4712010-07-14 17:59:35 -07006725// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006726AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006727{
Glenn Kastena1117922012-01-26 10:53:32 -08006728 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006729}
6730
6731// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006732AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006733{
6734 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08006735 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006736}
6737
6738// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006739AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006740{
Glenn Kastena1117922012-01-26 10:53:32 -08006741 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006742}
6743
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006744uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07006745{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006746 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006747}
6748
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006749AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006750{
6751 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6752 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006753 AudioStreamOut *output = thread->getOutput();
6754 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006755 return thread;
6756 }
6757 }
6758 return NULL;
6759}
6760
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006761uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006762{
6763 PlaybackThread *thread = primaryPlaybackThread_l();
6764
6765 if (thread == NULL) {
6766 return 0;
6767 }
6768
6769 return thread->device();
6770}
6771
Eric Laurenta011e352012-03-29 15:51:43 -07006772sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
6773 int triggerSession,
6774 int listenerSession,
6775 sync_event_callback_t callBack,
6776 void *cookie)
6777{
6778 Mutex::Autolock _l(mLock);
6779
6780 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
6781 status_t playStatus = NAME_NOT_FOUND;
6782 status_t recStatus = NAME_NOT_FOUND;
6783 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6784 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
6785 if (playStatus == NO_ERROR) {
6786 return event;
6787 }
6788 }
6789 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6790 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
6791 if (recStatus == NO_ERROR) {
6792 return event;
6793 }
6794 }
6795 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
6796 mPendingSyncEvents.add(event);
6797 } else {
6798 ALOGV("createSyncEvent() invalid event %d", event->type());
6799 event.clear();
6800 }
6801 return event;
6802}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006803
Mathias Agopian65ab4712010-07-14 17:59:35 -07006804// ----------------------------------------------------------------------------
6805// Effect management
6806// ----------------------------------------------------------------------------
6807
6808
Glenn Kastenf587ba52012-01-26 16:25:10 -08006809status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006810{
6811 Mutex::Autolock _l(mLock);
6812 return EffectQueryNumberEffects(numEffects);
6813}
6814
Glenn Kastenf587ba52012-01-26 16:25:10 -08006815status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006816{
6817 Mutex::Autolock _l(mLock);
6818 return EffectQueryEffect(index, descriptor);
6819}
6820
Glenn Kasten5e92a782012-01-30 07:40:52 -08006821status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08006822 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006823{
6824 Mutex::Autolock _l(mLock);
6825 return EffectGetDescriptor(pUuid, descriptor);
6826}
6827
6828
Mathias Agopian65ab4712010-07-14 17:59:35 -07006829sp<IEffect> AudioFlinger::createEffect(pid_t pid,
6830 effect_descriptor_t *pDesc,
6831 const sp<IEffectClient>& effectClient,
6832 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006833 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006834 int sessionId,
6835 status_t *status,
6836 int *id,
6837 int *enabled)
6838{
6839 status_t lStatus = NO_ERROR;
6840 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006841 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006842
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006843 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006844 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006845
6846 if (pDesc == NULL) {
6847 lStatus = BAD_VALUE;
6848 goto Exit;
6849 }
6850
Eric Laurent84e9a102010-09-23 16:10:16 -07006851 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006852 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006853 lStatus = PERMISSION_DENIED;
6854 goto Exit;
6855 }
6856
Dima Zavinfce7a472011-04-19 22:30:36 -07006857 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07006858 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08006859 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006860 lStatus = PERMISSION_DENIED;
6861 goto Exit;
6862 }
6863
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006864 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006865 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006866 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07006867 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07006868 lStatus = BAD_VALUE;
6869 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07006870 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006871 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006872 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07006873 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006874 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07006875 }
6876 }
6877
Mathias Agopian65ab4712010-07-14 17:59:35 -07006878 {
6879 Mutex::Autolock _l(mLock);
6880
Mathias Agopian65ab4712010-07-14 17:59:35 -07006881
6882 if (!EffectIsNullUuid(&pDesc->uuid)) {
6883 // if uuid is specified, request effect descriptor
6884 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
6885 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006886 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006887 goto Exit;
6888 }
6889 } else {
6890 // if uuid is not specified, look for an available implementation
6891 // of the required type in effect factory
6892 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006893 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006894 lStatus = BAD_VALUE;
6895 goto Exit;
6896 }
6897 uint32_t numEffects = 0;
6898 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006899 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07006900 bool found = false;
6901
6902 lStatus = EffectQueryNumberEffects(&numEffects);
6903 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006904 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006905 goto Exit;
6906 }
6907 for (uint32_t i = 0; i < numEffects; i++) {
6908 lStatus = EffectQueryEffect(i, &desc);
6909 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006910 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006911 continue;
6912 }
6913 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
6914 // If matching type found save effect descriptor. If the session is
6915 // 0 and the effect is not auxiliary, continue enumeration in case
6916 // an auxiliary version of this effect type is available
6917 found = true;
6918 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07006919 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006920 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6921 break;
6922 }
6923 }
6924 }
6925 if (!found) {
6926 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00006927 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006928 goto Exit;
6929 }
6930 // For same effect type, chose auxiliary version over insert version if
6931 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07006932 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006933 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6934 memcpy(&desc, &d, sizeof(effect_descriptor_t));
6935 }
6936 }
6937
6938 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07006939 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006940 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6941 lStatus = INVALID_OPERATION;
6942 goto Exit;
6943 }
6944
Eric Laurent59255e42011-07-27 19:49:51 -07006945 // check recording permission for visualizer
6946 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
6947 !recordingAllowed()) {
6948 lStatus = PERMISSION_DENIED;
6949 goto Exit;
6950 }
6951
Mathias Agopian65ab4712010-07-14 17:59:35 -07006952 // return effect descriptor
6953 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6954
6955 // If output is not specified try to find a matching audio session ID in one of the
6956 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07006957 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6958 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006959 // Note: io is never 0 when creating an effect on an input
6960 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006961 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07006962 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6963 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006964 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006965 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006966 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006967 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006968 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006969 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6970 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6971 io = mRecordThreads.keyAt(i);
6972 break;
6973 }
6974 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006975 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006976 // If no output thread contains the requested session ID, default to
6977 // first output. The effect chain will be moved to the correct output
6978 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006979 if (io == 0 && mPlaybackThreads.size()) {
6980 io = mPlaybackThreads.keyAt(0);
6981 }
Steve Block3856b092011-10-20 11:56:00 +01006982 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006983 }
6984 ThreadBase *thread = checkRecordThread_l(io);
6985 if (thread == NULL) {
6986 thread = checkPlaybackThread_l(io);
6987 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006988 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006989 lStatus = BAD_VALUE;
6990 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006991 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006992 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006993
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006994 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006995
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006996 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006997 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6998 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006999 if (handle != 0 && id != NULL) {
7000 *id = handle->id();
7001 }
7002 }
7003
7004Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007005 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007006 *status = lStatus;
7007 }
7008 return handle;
7009}
7010
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007011status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7012 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007013{
Steve Block3856b092011-10-20 11:56:00 +01007014 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007015 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007016 Mutex::Autolock _l(mLock);
7017 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007018 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007019 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007020 }
Eric Laurentde070132010-07-13 04:45:46 -07007021 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7022 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007023 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007024 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007025 }
Eric Laurentde070132010-07-13 04:45:46 -07007026 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7027 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007028 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007029 return BAD_VALUE;
7030 }
7031
7032 Mutex::Autolock _dl(dstThread->mLock);
7033 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007034 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007035
Mathias Agopian65ab4712010-07-14 17:59:35 -07007036 return NO_ERROR;
7037}
7038
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007039// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007040status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007041 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007042 AudioFlinger::PlaybackThread *dstThread,
7043 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007044{
Steve Block3856b092011-10-20 11:56:00 +01007045 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007046 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007047
Eric Laurent59255e42011-07-27 19:49:51 -07007048 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007049 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007050 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007051 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007052 return INVALID_OPERATION;
7053 }
7054
Eric Laurent39e94f82010-07-28 01:32:47 -07007055 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007056 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007057 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007058 // removed.
7059 srcThread->removeEffectChain_l(chain);
7060
7061 // transfer all effects one by one so that new effect chain is created on new thread with
7062 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007063 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007064 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007065 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007066 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7067 while (effect != 0) {
7068 srcThread->removeEffect_l(effect);
7069 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007070 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7071 if (effect->state() == EffectModule::ACTIVE ||
7072 effect->state() == EffectModule::STOPPING) {
7073 effect->start();
7074 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007075 // if the move request is not received from audio policy manager, the effect must be
7076 // re-registered with the new strategy and output
7077 if (dstChain == 0) {
7078 dstChain = effect->chain().promote();
7079 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007080 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007081 srcThread->addEffect_l(effect);
7082 return NO_INIT;
7083 }
7084 strategy = dstChain->strategy();
7085 }
7086 if (reRegister) {
7087 AudioSystem::unregisterEffect(effect->id());
7088 AudioSystem::registerEffect(&effect->desc(),
7089 dstOutput,
7090 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007091 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007092 effect->id());
7093 }
Eric Laurentde070132010-07-13 04:45:46 -07007094 effect = chain->getEffectFromId_l(0);
7095 }
7096
7097 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007098}
7099
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007100
Mathias Agopian65ab4712010-07-14 17:59:35 -07007101// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007102sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007103 const sp<AudioFlinger::Client>& client,
7104 const sp<IEffectClient>& effectClient,
7105 int32_t priority,
7106 int sessionId,
7107 effect_descriptor_t *desc,
7108 int *enabled,
7109 status_t *status
7110 )
7111{
7112 sp<EffectModule> effect;
7113 sp<EffectHandle> handle;
7114 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007115 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007116 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007117 bool effectCreated = false;
7118 bool effectRegistered = false;
7119
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007120 lStatus = initCheck();
7121 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007122 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007123 goto Exit;
7124 }
7125
7126 // Do not allow effects with session ID 0 on direct output or duplicating threads
7127 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007128 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007129 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007130 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007131 lStatus = BAD_VALUE;
7132 goto Exit;
7133 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007134 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007135 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007136 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007137 desc->name, desc->flags, mType);
7138 lStatus = BAD_VALUE;
7139 goto Exit;
7140 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007141
Steve Block3856b092011-10-20 11:56:00 +01007142 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007143
7144 { // scope for mLock
7145 Mutex::Autolock _l(mLock);
7146
7147 // check for existing effect chain with the requested audio session
7148 chain = getEffectChain_l(sessionId);
7149 if (chain == 0) {
7150 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007151 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007152 chain = new EffectChain(this, sessionId);
7153 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007154 chain->setStrategy(getStrategyForSession_l(sessionId));
7155 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007156 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007157 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007158 }
7159
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007160 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007161
7162 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007163 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007164 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007165 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007166 if (lStatus != NO_ERROR) {
7167 goto Exit;
7168 }
7169 effectRegistered = true;
7170 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007171 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007172 lStatus = effect->status();
7173 if (lStatus != NO_ERROR) {
7174 goto Exit;
7175 }
Eric Laurentcab11242010-07-15 12:50:15 -07007176 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007177 if (lStatus != NO_ERROR) {
7178 goto Exit;
7179 }
7180 effectCreated = true;
7181
7182 effect->setDevice(mDevice);
7183 effect->setMode(mAudioFlinger->getMode());
7184 }
7185 // create effect handle and connect it to effect module
7186 handle = new EffectHandle(effect, client, effectClient, priority);
7187 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08007188 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007189 *enabled = (int)effect->isEnabled();
7190 }
7191 }
7192
7193Exit:
7194 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007195 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007196 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007197 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007198 }
7199 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007200 AudioSystem::unregisterEffect(effect->id());
7201 }
7202 if (chainCreated) {
7203 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007204 }
7205 handle.clear();
7206 }
7207
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007208 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007209 *status = lStatus;
7210 }
7211 return handle;
7212}
7213
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007214sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7215{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007216 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007217 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007218}
7219
Eric Laurentde070132010-07-13 04:45:46 -07007220// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7221// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007222status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007223{
7224 // check for existing effect chain with the requested audio session
7225 int sessionId = effect->sessionId();
7226 sp<EffectChain> chain = getEffectChain_l(sessionId);
7227 bool chainCreated = false;
7228
7229 if (chain == 0) {
7230 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007231 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007232 chain = new EffectChain(this, sessionId);
7233 addEffectChain_l(chain);
7234 chain->setStrategy(getStrategyForSession_l(sessionId));
7235 chainCreated = true;
7236 }
Steve Block3856b092011-10-20 11:56:00 +01007237 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007238
7239 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007240 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007241 this, effect->desc().name, chain.get());
7242 return BAD_VALUE;
7243 }
7244
7245 status_t status = chain->addEffect_l(effect);
7246 if (status != NO_ERROR) {
7247 if (chainCreated) {
7248 removeEffectChain_l(chain);
7249 }
7250 return status;
7251 }
7252
7253 effect->setDevice(mDevice);
7254 effect->setMode(mAudioFlinger->getMode());
7255 return NO_ERROR;
7256}
7257
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007258void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007259
Steve Block3856b092011-10-20 11:56:00 +01007260 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007261 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007262 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7263 detachAuxEffect_l(effect->id());
7264 }
7265
7266 sp<EffectChain> chain = effect->chain().promote();
7267 if (chain != 0) {
7268 // remove effect chain if removing last effect
7269 if (chain->removeEffect_l(effect) == 0) {
7270 removeEffectChain_l(chain);
7271 }
7272 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007273 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007274 }
7275}
7276
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007277void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007278 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007279{
7280 effectChains = mEffectChains;
7281 for (size_t i = 0; i < mEffectChains.size(); i++) {
7282 mEffectChains[i]->lock();
7283 }
7284}
7285
7286void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007287 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007288{
7289 for (size_t i = 0; i < effectChains.size(); i++) {
7290 effectChains[i]->unlock();
7291 }
7292}
7293
7294sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7295{
7296 Mutex::Autolock _l(mLock);
7297 return getEffectChain_l(sessionId);
7298}
7299
7300sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7301{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007302 size_t size = mEffectChains.size();
7303 for (size_t i = 0; i < size; i++) {
7304 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007305 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007306 }
7307 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007308 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007309}
7310
Glenn Kastenf78aee72012-01-04 11:00:47 -08007311void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007312{
7313 Mutex::Autolock _l(mLock);
7314 size_t size = mEffectChains.size();
7315 for (size_t i = 0; i < size; i++) {
7316 mEffectChains[i]->setMode_l(mode);
7317 }
7318}
7319
7320void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007321 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007322 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007323
Mathias Agopian65ab4712010-07-14 17:59:35 -07007324 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007325 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007326 // delete the effect module if removing last handle on it
7327 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007328 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007329 removeEffect_l(effect);
7330 AudioSystem::unregisterEffect(effect->id());
7331 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007332 }
7333}
7334
7335status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7336{
7337 int session = chain->sessionId();
7338 int16_t *buffer = mMixBuffer;
7339 bool ownsBuffer = false;
7340
Steve Block3856b092011-10-20 11:56:00 +01007341 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007342 if (session > 0) {
7343 // Only one effect chain can be present in direct output thread and it uses
7344 // the mix buffer as input
7345 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007346 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007347 buffer = new int16_t[numSamples];
7348 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007349 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007350 ownsBuffer = true;
7351 }
7352
7353 // Attach all tracks with same session ID to this chain.
7354 for (size_t i = 0; i < mTracks.size(); ++i) {
7355 sp<Track> track = mTracks[i];
7356 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007357 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007358 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007359 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007360 }
7361 }
7362
7363 // indicate all active tracks in the chain
7364 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7365 sp<Track> track = mActiveTracks[i].promote();
7366 if (track == 0) continue;
7367 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007368 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007369 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007370 }
7371 }
7372 }
7373
7374 chain->setInBuffer(buffer, ownsBuffer);
7375 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007376 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007377 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007378 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7379 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007380 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007381 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7382 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007383 // Effect chain for other sessions are inserted at beginning of effect
7384 // chains list to be processed before output mix effects. Relative order between other
7385 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007386 size_t size = mEffectChains.size();
7387 size_t i = 0;
7388 for (i = 0; i < size; i++) {
7389 if (mEffectChains[i]->sessionId() < session) break;
7390 }
7391 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007392 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007393
7394 return NO_ERROR;
7395}
7396
7397size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7398{
7399 int session = chain->sessionId();
7400
Steve Block3856b092011-10-20 11:56:00 +01007401 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007402
7403 for (size_t i = 0; i < mEffectChains.size(); i++) {
7404 if (chain == mEffectChains[i]) {
7405 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007406 // detach all active tracks from the chain
7407 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7408 sp<Track> track = mActiveTracks[i].promote();
7409 if (track == 0) continue;
7410 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007411 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007412 chain.get(), session);
7413 chain->decActiveTrackCnt();
7414 }
7415 }
7416
Mathias Agopian65ab4712010-07-14 17:59:35 -07007417 // detach all tracks with same session ID from this chain
7418 for (size_t i = 0; i < mTracks.size(); ++i) {
7419 sp<Track> track = mTracks[i];
7420 if (session == track->sessionId()) {
7421 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007422 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007423 }
7424 }
Eric Laurentde070132010-07-13 04:45:46 -07007425 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007426 }
7427 }
7428 return mEffectChains.size();
7429}
7430
Eric Laurentde070132010-07-13 04:45:46 -07007431status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7432 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007433{
7434 Mutex::Autolock _l(mLock);
7435 return attachAuxEffect_l(track, EffectId);
7436}
7437
Eric Laurentde070132010-07-13 04:45:46 -07007438status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7439 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007440{
7441 status_t status = NO_ERROR;
7442
7443 if (EffectId == 0) {
7444 track->setAuxBuffer(0, NULL);
7445 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007446 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7447 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007448 if (effect != 0) {
7449 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7450 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7451 } else {
7452 status = INVALID_OPERATION;
7453 }
7454 } else {
7455 status = BAD_VALUE;
7456 }
7457 }
7458 return status;
7459}
7460
7461void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7462{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007463 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007464 sp<Track> track = mTracks[i];
7465 if (track->auxEffectId() == effectId) {
7466 attachAuxEffect_l(track, 0);
7467 }
7468 }
7469}
7470
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007471status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7472{
7473 // only one chain per input thread
7474 if (mEffectChains.size() != 0) {
7475 return INVALID_OPERATION;
7476 }
Steve Block3856b092011-10-20 11:56:00 +01007477 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007478
7479 chain->setInBuffer(NULL);
7480 chain->setOutBuffer(NULL);
7481
Eric Laurent59255e42011-07-27 19:49:51 -07007482 checkSuspendOnAddEffectChain_l(chain);
7483
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007484 mEffectChains.add(chain);
7485
7486 return NO_ERROR;
7487}
7488
7489size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7490{
Steve Block3856b092011-10-20 11:56:00 +01007491 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007492 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007493 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7494 chain.get(), mEffectChains.size(), this);
7495 if (mEffectChains.size() == 1) {
7496 mEffectChains.removeAt(0);
7497 }
7498 return 0;
7499}
7500
Mathias Agopian65ab4712010-07-14 17:59:35 -07007501// ----------------------------------------------------------------------------
7502// EffectModule implementation
7503// ----------------------------------------------------------------------------
7504
7505#undef LOG_TAG
7506#define LOG_TAG "AudioFlinger::EffectModule"
7507
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007508AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007509 const wp<AudioFlinger::EffectChain>& chain,
7510 effect_descriptor_t *desc,
7511 int id,
7512 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007513 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007514 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007515{
Steve Block3856b092011-10-20 11:56:00 +01007516 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007517 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007518 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007519 return;
7520 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007521
7522 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7523
7524 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007525 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007526
7527 if (mStatus != NO_ERROR) {
7528 return;
7529 }
7530 lStatus = init();
7531 if (lStatus < 0) {
7532 mStatus = lStatus;
7533 goto Error;
7534 }
7535
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007536 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
7537 mPinned = true;
7538 }
Steve Block3856b092011-10-20 11:56:00 +01007539 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007540 return;
7541Error:
7542 EffectRelease(mEffectInterface);
7543 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007544 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007545}
7546
7547AudioFlinger::EffectModule::~EffectModule()
7548{
Steve Block3856b092011-10-20 11:56:00 +01007549 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007550 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007551 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7552 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7553 sp<ThreadBase> thread = mThread.promote();
7554 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007555 audio_stream_t *stream = thread->stream();
7556 if (stream != NULL) {
7557 stream->remove_audio_effect(stream, mEffectInterface);
7558 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007559 }
7560 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007561 // release effect engine
7562 EffectRelease(mEffectInterface);
7563 }
7564}
7565
Glenn Kasten435dbe62012-01-30 10:15:48 -08007566status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007567{
7568 status_t status;
7569
7570 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007571 int priority = handle->priority();
7572 size_t size = mHandles.size();
7573 sp<EffectHandle> h;
7574 size_t i;
7575 for (i = 0; i < size; i++) {
7576 h = mHandles[i].promote();
7577 if (h == 0) continue;
7578 if (h->priority() <= priority) break;
7579 }
7580 // if inserted in first place, move effect control from previous owner to this handle
7581 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007582 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007583 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007584 enabled = h->enabled();
7585 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007586 }
Eric Laurent59255e42011-07-27 19:49:51 -07007587 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007588 status = NO_ERROR;
7589 } else {
7590 status = ALREADY_EXISTS;
7591 }
Steve Block3856b092011-10-20 11:56:00 +01007592 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007593 mHandles.insertAt(handle, i);
7594 return status;
7595}
7596
7597size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
7598{
7599 Mutex::Autolock _l(mLock);
7600 size_t size = mHandles.size();
7601 size_t i;
7602 for (i = 0; i < size; i++) {
7603 if (mHandles[i] == handle) break;
7604 }
7605 if (i == size) {
7606 return size;
7607 }
Steve Block3856b092011-10-20 11:56:00 +01007608 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07007609
7610 bool enabled = false;
7611 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08007612 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01007613 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07007614 enabled = hdl->enabled();
7615 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007616 mHandles.removeAt(i);
7617 size = mHandles.size();
7618 // if removed from first place, move effect control from this handle to next in line
7619 if (i == 0 && size != 0) {
7620 sp<EffectHandle> h = mHandles[0].promote();
7621 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007622 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007623 }
7624 }
7625
Eric Laurentec437d82011-07-26 20:54:46 -07007626 // Prevent calls to process() and other functions on effect interface from now on.
7627 // The effect engine will be released by the destructor when the last strong reference on
7628 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007629 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07007630 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07007631 }
7632
Mathias Agopian65ab4712010-07-14 17:59:35 -07007633 return size;
7634}
7635
Eric Laurent59255e42011-07-27 19:49:51 -07007636sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7637{
7638 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08007639 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007640}
7641
Glenn Kasten58123c32012-02-03 10:32:24 -08007642void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007643{
Glenn Kasten90bebef2012-01-27 15:24:38 -08007644 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007645 // keep a strong reference on this EffectModule to avoid calling the
7646 // destructor before we exit
7647 sp<EffectModule> keep(this);
7648 {
7649 sp<ThreadBase> thread = mThread.promote();
7650 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007651 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007652 }
7653 }
7654}
7655
7656void AudioFlinger::EffectModule::updateState() {
7657 Mutex::Autolock _l(mLock);
7658
7659 switch (mState) {
7660 case RESTART:
7661 reset_l();
7662 // FALL THROUGH
7663
7664 case STARTING:
7665 // clear auxiliary effect input buffer for next accumulation
7666 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7667 memset(mConfig.inputCfg.buffer.raw,
7668 0,
7669 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7670 }
7671 start_l();
7672 mState = ACTIVE;
7673 break;
7674 case STOPPING:
7675 stop_l();
7676 mDisableWaitCnt = mMaxDisableWaitCnt;
7677 mState = STOPPED;
7678 break;
7679 case STOPPED:
7680 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
7681 // turn off sequence.
7682 if (--mDisableWaitCnt == 0) {
7683 reset_l();
7684 mState = IDLE;
7685 }
7686 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007687 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07007688 break;
7689 }
7690}
7691
7692void AudioFlinger::EffectModule::process()
7693{
7694 Mutex::Autolock _l(mLock);
7695
Eric Laurentec437d82011-07-26 20:54:46 -07007696 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007697 mConfig.inputCfg.buffer.raw == NULL ||
7698 mConfig.outputCfg.buffer.raw == NULL) {
7699 return;
7700 }
7701
Eric Laurent8f45bd72010-08-31 13:50:07 -07007702 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007703 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
7704 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08007705 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007706 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07007707 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007708 }
7709
7710 // do the actual processing in the effect engine
7711 int ret = (*mEffectInterface)->process(mEffectInterface,
7712 &mConfig.inputCfg.buffer,
7713 &mConfig.outputCfg.buffer);
7714
7715 // force transition to IDLE state when engine is ready
7716 if (mState == STOPPED && ret == -ENODATA) {
7717 mDisableWaitCnt = 1;
7718 }
7719
7720 // clear auxiliary effect input buffer for next accumulation
7721 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08007722 memset(mConfig.inputCfg.buffer.raw, 0,
7723 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007724 }
7725 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08007726 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7727 // If an insert effect is idle and input buffer is different from output buffer,
7728 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07007729 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07007730 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08007731 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
7732 int16_t *in = mConfig.inputCfg.buffer.s16;
7733 int16_t *out = mConfig.outputCfg.buffer.s16;
7734 for (size_t i = 0; i < frameCnt; i++) {
7735 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007736 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007737 }
7738 }
7739}
7740
7741void AudioFlinger::EffectModule::reset_l()
7742{
7743 if (mEffectInterface == NULL) {
7744 return;
7745 }
7746 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
7747}
7748
7749status_t AudioFlinger::EffectModule::configure()
7750{
7751 uint32_t channels;
7752 if (mEffectInterface == NULL) {
7753 return NO_INIT;
7754 }
7755
7756 sp<ThreadBase> thread = mThread.promote();
7757 if (thread == 0) {
7758 return DEAD_OBJECT;
7759 }
7760
7761 // TODO: handle configuration of effects replacing track process
7762 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007763 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007764 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07007765 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007766 }
7767
7768 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007769 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007770 } else {
7771 mConfig.inputCfg.channels = channels;
7772 }
7773 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07007774 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
7775 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007776 mConfig.inputCfg.samplingRate = thread->sampleRate();
7777 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
7778 mConfig.inputCfg.bufferProvider.cookie = NULL;
7779 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
7780 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
7781 mConfig.outputCfg.bufferProvider.cookie = NULL;
7782 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
7783 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
7784 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
7785 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07007786 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07007787 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07007788 // - in other sessions:
7789 // last effect in the chain accumulates in output buffer: input buffer != output buffer
7790 // other effect: overwrites output buffer: input buffer == output buffer
7791 // Auxiliary effect:
7792 // accumulates in output buffer: input buffer != output buffer
7793 // Therefore: accumulate <=> input buffer != output buffer
7794 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7795 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
7796 } else {
7797 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
7798 }
7799 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
7800 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
7801 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
7802 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
7803
Steve Block3856b092011-10-20 11:56:00 +01007804 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07007805 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
7806
Mathias Agopian65ab4712010-07-14 17:59:35 -07007807 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007808 uint32_t size = sizeof(int);
7809 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08007810 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07007811 sizeof(effect_config_t),
7812 &mConfig,
7813 &size,
7814 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007815 if (status == 0) {
7816 status = cmdStatus;
7817 }
7818
7819 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
7820 (1000 * mConfig.outputCfg.buffer.frameCount);
7821
7822 return status;
7823}
7824
7825status_t AudioFlinger::EffectModule::init()
7826{
7827 Mutex::Autolock _l(mLock);
7828 if (mEffectInterface == NULL) {
7829 return NO_INIT;
7830 }
7831 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007832 uint32_t size = sizeof(status_t);
7833 status_t status = (*mEffectInterface)->command(mEffectInterface,
7834 EFFECT_CMD_INIT,
7835 0,
7836 NULL,
7837 &size,
7838 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007839 if (status == 0) {
7840 status = cmdStatus;
7841 }
7842 return status;
7843}
7844
Eric Laurentec35a142011-10-05 17:42:25 -07007845status_t AudioFlinger::EffectModule::start()
7846{
7847 Mutex::Autolock _l(mLock);
7848 return start_l();
7849}
7850
Mathias Agopian65ab4712010-07-14 17:59:35 -07007851status_t AudioFlinger::EffectModule::start_l()
7852{
7853 if (mEffectInterface == NULL) {
7854 return NO_INIT;
7855 }
7856 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007857 uint32_t size = sizeof(status_t);
7858 status_t status = (*mEffectInterface)->command(mEffectInterface,
7859 EFFECT_CMD_ENABLE,
7860 0,
7861 NULL,
7862 &size,
7863 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007864 if (status == 0) {
7865 status = cmdStatus;
7866 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007867 if (status == 0 &&
7868 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7869 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7870 sp<ThreadBase> thread = mThread.promote();
7871 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007872 audio_stream_t *stream = thread->stream();
7873 if (stream != NULL) {
7874 stream->add_audio_effect(stream, mEffectInterface);
7875 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007876 }
7877 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007878 return status;
7879}
7880
Eric Laurentec437d82011-07-26 20:54:46 -07007881status_t AudioFlinger::EffectModule::stop()
7882{
7883 Mutex::Autolock _l(mLock);
7884 return stop_l();
7885}
7886
Mathias Agopian65ab4712010-07-14 17:59:35 -07007887status_t AudioFlinger::EffectModule::stop_l()
7888{
7889 if (mEffectInterface == NULL) {
7890 return NO_INIT;
7891 }
7892 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007893 uint32_t size = sizeof(status_t);
7894 status_t status = (*mEffectInterface)->command(mEffectInterface,
7895 EFFECT_CMD_DISABLE,
7896 0,
7897 NULL,
7898 &size,
7899 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007900 if (status == 0) {
7901 status = cmdStatus;
7902 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007903 if (status == 0 &&
7904 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7905 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7906 sp<ThreadBase> thread = mThread.promote();
7907 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007908 audio_stream_t *stream = thread->stream();
7909 if (stream != NULL) {
7910 stream->remove_audio_effect(stream, mEffectInterface);
7911 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007912 }
7913 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007914 return status;
7915}
7916
Eric Laurent25f43952010-07-28 05:40:18 -07007917status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
7918 uint32_t cmdSize,
7919 void *pCmdData,
7920 uint32_t *replySize,
7921 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007922{
7923 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007924// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007925
Eric Laurentec437d82011-07-26 20:54:46 -07007926 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007927 return NO_INIT;
7928 }
Eric Laurent25f43952010-07-28 05:40:18 -07007929 status_t status = (*mEffectInterface)->command(mEffectInterface,
7930 cmdCode,
7931 cmdSize,
7932 pCmdData,
7933 replySize,
7934 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007935 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007936 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007937 for (size_t i = 1; i < mHandles.size(); i++) {
7938 sp<EffectHandle> h = mHandles[i].promote();
7939 if (h != 0) {
7940 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7941 }
7942 }
7943 }
7944 return status;
7945}
7946
7947status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7948{
Eric Laurentdb7c0792011-08-10 10:37:50 -07007949
Mathias Agopian65ab4712010-07-14 17:59:35 -07007950 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007951 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007952
7953 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007954 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7955 if (enabled && status != NO_ERROR) {
7956 return status;
7957 }
7958
Mathias Agopian65ab4712010-07-14 17:59:35 -07007959 switch (mState) {
7960 // going from disabled to enabled
7961 case IDLE:
7962 mState = STARTING;
7963 break;
7964 case STOPPED:
7965 mState = RESTART;
7966 break;
7967 case STOPPING:
7968 mState = ACTIVE;
7969 break;
7970
7971 // going from enabled to disabled
7972 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007973 mState = STOPPED;
7974 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007975 case STARTING:
7976 mState = IDLE;
7977 break;
7978 case ACTIVE:
7979 mState = STOPPING;
7980 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007981 case DESTROYED:
7982 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007983 }
7984 for (size_t i = 1; i < mHandles.size(); i++) {
7985 sp<EffectHandle> h = mHandles[i].promote();
7986 if (h != 0) {
7987 h->setEnabled(enabled);
7988 }
7989 }
7990 }
7991 return NO_ERROR;
7992}
7993
Glenn Kastenc59c0042012-02-02 14:06:11 -08007994bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007995{
7996 switch (mState) {
7997 case RESTART:
7998 case STARTING:
7999 case ACTIVE:
8000 return true;
8001 case IDLE:
8002 case STOPPING:
8003 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008004 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008005 default:
8006 return false;
8007 }
8008}
8009
Glenn Kastenc59c0042012-02-02 14:06:11 -08008010bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008011{
8012 switch (mState) {
8013 case RESTART:
8014 case ACTIVE:
8015 case STOPPING:
8016 case STOPPED:
8017 return true;
8018 case IDLE:
8019 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008020 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008021 default:
8022 return false;
8023 }
8024}
8025
Mathias Agopian65ab4712010-07-14 17:59:35 -07008026status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8027{
8028 Mutex::Autolock _l(mLock);
8029 status_t status = NO_ERROR;
8030
8031 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8032 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008033 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008034 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8035 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008036 status_t cmdStatus;
8037 uint32_t volume[2];
8038 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008039 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008040 volume[0] = *left;
8041 volume[1] = *right;
8042 if (controller) {
8043 pVolume = volume;
8044 }
Eric Laurent25f43952010-07-28 05:40:18 -07008045 status = (*mEffectInterface)->command(mEffectInterface,
8046 EFFECT_CMD_SET_VOLUME,
8047 size,
8048 volume,
8049 &size,
8050 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008051 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8052 *left = volume[0];
8053 *right = volume[1];
8054 }
8055 }
8056 return status;
8057}
8058
8059status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8060{
8061 Mutex::Autolock _l(mLock);
8062 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008063 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8064 // audio pre processing modules on RecordThread can receive both output and
8065 // input device indication in the same call
8066 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8067 if (dev) {
8068 status_t cmdStatus;
8069 uint32_t size = sizeof(status_t);
8070
8071 status = (*mEffectInterface)->command(mEffectInterface,
8072 EFFECT_CMD_SET_DEVICE,
8073 sizeof(uint32_t),
8074 &dev,
8075 &size,
8076 &cmdStatus);
8077 if (status == NO_ERROR) {
8078 status = cmdStatus;
8079 }
8080 }
8081 dev = device & AUDIO_DEVICE_IN_ALL;
8082 if (dev) {
8083 status_t cmdStatus;
8084 uint32_t size = sizeof(status_t);
8085
8086 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8087 EFFECT_CMD_SET_INPUT_DEVICE,
8088 sizeof(uint32_t),
8089 &dev,
8090 &size,
8091 &cmdStatus);
8092 if (status2 == NO_ERROR) {
8093 status2 = cmdStatus;
8094 }
8095 if (status == NO_ERROR) {
8096 status = status2;
8097 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008098 }
8099 }
8100 return status;
8101}
8102
Glenn Kastenf78aee72012-01-04 11:00:47 -08008103status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008104{
8105 Mutex::Autolock _l(mLock);
8106 status_t status = NO_ERROR;
8107 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008108 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008109 uint32_t size = sizeof(status_t);
8110 status = (*mEffectInterface)->command(mEffectInterface,
8111 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008112 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008113 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008114 &size,
8115 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008116 if (status == NO_ERROR) {
8117 status = cmdStatus;
8118 }
8119 }
8120 return status;
8121}
8122
Eric Laurent59255e42011-07-27 19:49:51 -07008123void AudioFlinger::EffectModule::setSuspended(bool suspended)
8124{
8125 Mutex::Autolock _l(mLock);
8126 mSuspended = suspended;
8127}
Glenn Kastena3a85482012-01-04 11:01:11 -08008128
8129bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008130{
8131 Mutex::Autolock _l(mLock);
8132 return mSuspended;
8133}
8134
Mathias Agopian65ab4712010-07-14 17:59:35 -07008135status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8136{
8137 const size_t SIZE = 256;
8138 char buffer[SIZE];
8139 String8 result;
8140
8141 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8142 result.append(buffer);
8143
8144 bool locked = tryLock(mLock);
8145 // failed to lock - AudioFlinger is probably deadlocked
8146 if (!locked) {
8147 result.append("\t\tCould not lock Fx mutex:\n");
8148 }
8149
8150 result.append("\t\tSession Status State Engine:\n");
8151 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8152 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8153 result.append(buffer);
8154
8155 result.append("\t\tDescriptor:\n");
8156 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8157 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8158 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8159 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8160 result.append(buffer);
8161 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8162 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8163 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8164 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8165 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008166 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008167 mDescriptor.apiVersion,
8168 mDescriptor.flags);
8169 result.append(buffer);
8170 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8171 mDescriptor.name);
8172 result.append(buffer);
8173 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8174 mDescriptor.implementor);
8175 result.append(buffer);
8176
8177 result.append("\t\t- Input configuration:\n");
8178 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8179 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8180 (uint32_t)mConfig.inputCfg.buffer.raw,
8181 mConfig.inputCfg.buffer.frameCount,
8182 mConfig.inputCfg.samplingRate,
8183 mConfig.inputCfg.channels,
8184 mConfig.inputCfg.format);
8185 result.append(buffer);
8186
8187 result.append("\t\t- Output configuration:\n");
8188 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8189 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8190 (uint32_t)mConfig.outputCfg.buffer.raw,
8191 mConfig.outputCfg.buffer.frameCount,
8192 mConfig.outputCfg.samplingRate,
8193 mConfig.outputCfg.channels,
8194 mConfig.outputCfg.format);
8195 result.append(buffer);
8196
8197 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8198 result.append(buffer);
8199 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8200 for (size_t i = 0; i < mHandles.size(); ++i) {
8201 sp<EffectHandle> handle = mHandles[i].promote();
8202 if (handle != 0) {
8203 handle->dump(buffer, SIZE);
8204 result.append(buffer);
8205 }
8206 }
8207
8208 result.append("\n");
8209
8210 write(fd, result.string(), result.length());
8211
8212 if (locked) {
8213 mLock.unlock();
8214 }
8215
8216 return NO_ERROR;
8217}
8218
8219// ----------------------------------------------------------------------------
8220// EffectHandle implementation
8221// ----------------------------------------------------------------------------
8222
8223#undef LOG_TAG
8224#define LOG_TAG "AudioFlinger::EffectHandle"
8225
8226AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8227 const sp<AudioFlinger::Client>& client,
8228 const sp<IEffectClient>& effectClient,
8229 int32_t priority)
8230 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008231 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008232 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008233{
Steve Block3856b092011-10-20 11:56:00 +01008234 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008235
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008236 if (client == 0) {
8237 return;
8238 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008239 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8240 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8241 if (mCblkMemory != 0) {
8242 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8243
Glenn Kastena0d68332012-01-27 16:47:15 -08008244 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008245 new(mCblk) effect_param_cblk_t();
8246 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008247 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008248 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008249 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008250 return;
8251 }
8252}
8253
8254AudioFlinger::EffectHandle::~EffectHandle()
8255{
Steve Block3856b092011-10-20 11:56:00 +01008256 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008257 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01008258 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008259}
8260
8261status_t AudioFlinger::EffectHandle::enable()
8262{
Steve Block3856b092011-10-20 11:56:00 +01008263 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008264 if (!mHasControl) return INVALID_OPERATION;
8265 if (mEffect == 0) return DEAD_OBJECT;
8266
Eric Laurentdb7c0792011-08-10 10:37:50 -07008267 if (mEnabled) {
8268 return NO_ERROR;
8269 }
8270
Eric Laurent59255e42011-07-27 19:49:51 -07008271 mEnabled = true;
8272
8273 sp<ThreadBase> thread = mEffect->thread().promote();
8274 if (thread != 0) {
8275 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8276 }
8277
8278 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8279 if (mEffect->suspended()) {
8280 return NO_ERROR;
8281 }
8282
Eric Laurentdb7c0792011-08-10 10:37:50 -07008283 status_t status = mEffect->setEnabled(true);
8284 if (status != NO_ERROR) {
8285 if (thread != 0) {
8286 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8287 }
8288 mEnabled = false;
8289 }
8290 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008291}
8292
8293status_t AudioFlinger::EffectHandle::disable()
8294{
Steve Block3856b092011-10-20 11:56:00 +01008295 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008296 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008297 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008298
Eric Laurentdb7c0792011-08-10 10:37:50 -07008299 if (!mEnabled) {
8300 return NO_ERROR;
8301 }
Eric Laurent59255e42011-07-27 19:49:51 -07008302 mEnabled = false;
8303
8304 if (mEffect->suspended()) {
8305 return NO_ERROR;
8306 }
8307
8308 status_t status = mEffect->setEnabled(false);
8309
8310 sp<ThreadBase> thread = mEffect->thread().promote();
8311 if (thread != 0) {
8312 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8313 }
8314
8315 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008316}
8317
8318void AudioFlinger::EffectHandle::disconnect()
8319{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008320 disconnect(true);
8321}
8322
Glenn Kasten58123c32012-02-03 10:32:24 -08008323void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008324{
Glenn Kasten58123c32012-02-03 10:32:24 -08008325 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008326 if (mEffect == 0) {
8327 return;
8328 }
Glenn Kasten58123c32012-02-03 10:32:24 -08008329 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07008330
Eric Laurenta85a74a2011-10-19 11:44:54 -07008331 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008332 sp<ThreadBase> thread = mEffect->thread().promote();
8333 if (thread != 0) {
8334 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8335 }
Eric Laurent59255e42011-07-27 19:49:51 -07008336 }
8337
Mathias Agopian65ab4712010-07-14 17:59:35 -07008338 // release sp on module => module destructor can be called now
8339 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008340 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008341 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008342 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008343 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8344 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008345 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008346 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008347 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8348 mClient.clear();
8349 }
8350}
8351
Eric Laurent25f43952010-07-28 05:40:18 -07008352status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8353 uint32_t cmdSize,
8354 void *pCmdData,
8355 uint32_t *replySize,
8356 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008357{
Steve Block3856b092011-10-20 11:56:00 +01008358// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008359// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008360
8361 // only get parameter command is permitted for applications not controlling the effect
8362 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8363 return INVALID_OPERATION;
8364 }
8365 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008366 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008367
8368 // handle commands that are not forwarded transparently to effect engine
8369 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8370 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8371 // no risk to block the whole media server process or mixer threads is we are stuck here
8372 Mutex::Autolock _l(mCblk->lock);
8373 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8374 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8375 mCblk->serverIndex = 0;
8376 mCblk->clientIndex = 0;
8377 return BAD_VALUE;
8378 }
8379 status_t status = NO_ERROR;
8380 while (mCblk->serverIndex < mCblk->clientIndex) {
8381 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008382 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008383 int *p = (int *)(mBuffer + mCblk->serverIndex);
8384 int size = *p++;
8385 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008386 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008387 break;
8388 }
8389 effect_param_t *param = (effect_param_t *)p;
8390 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008391 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008392 mCblk->serverIndex += size;
8393 continue;
8394 }
Eric Laurent25f43952010-07-28 05:40:18 -07008395 uint32_t psize = sizeof(effect_param_t) +
8396 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8397 param->vsize;
8398 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8399 psize,
8400 p,
8401 &rsize,
8402 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008403 // stop at first error encountered
8404 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008405 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008406 *(int *)pReplyData = reply;
8407 break;
8408 } else if (reply != NO_ERROR) {
8409 *(int *)pReplyData = reply;
8410 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008411 }
8412 mCblk->serverIndex += size;
8413 }
8414 mCblk->serverIndex = 0;
8415 mCblk->clientIndex = 0;
8416 return status;
8417 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008418 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008419 return enable();
8420 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008421 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008422 return disable();
8423 }
8424
8425 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8426}
8427
Eric Laurent59255e42011-07-27 19:49:51 -07008428void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008429{
Steve Block3856b092011-10-20 11:56:00 +01008430 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008431
8432 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008433 mEnabled = enabled;
8434
Mathias Agopian65ab4712010-07-14 17:59:35 -07008435 if (signal && mEffectClient != 0) {
8436 mEffectClient->controlStatusChanged(hasControl);
8437 }
8438}
8439
Eric Laurent25f43952010-07-28 05:40:18 -07008440void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8441 uint32_t cmdSize,
8442 void *pCmdData,
8443 uint32_t replySize,
8444 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008445{
8446 if (mEffectClient != 0) {
8447 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8448 }
8449}
8450
8451
8452
8453void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8454{
8455 if (mEffectClient != 0) {
8456 mEffectClient->enableStatusChanged(enabled);
8457 }
8458}
8459
8460status_t AudioFlinger::EffectHandle::onTransact(
8461 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8462{
8463 return BnEffect::onTransact(code, data, reply, flags);
8464}
8465
8466
8467void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8468{
Glenn Kastena0d68332012-01-27 16:47:15 -08008469 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008470
8471 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008472 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008473 mPriority,
8474 mHasControl,
8475 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008476 mCblk ? mCblk->clientIndex : 0,
8477 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008478 );
8479
8480 if (locked) {
8481 mCblk->lock.unlock();
8482 }
8483}
8484
8485#undef LOG_TAG
8486#define LOG_TAG "AudioFlinger::EffectChain"
8487
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008488AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008489 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008490 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008491 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8492 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008493{
Dima Zavinfce7a472011-04-19 22:30:36 -07008494 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008495 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008496 return;
8497 }
8498 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8499 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008500}
8501
8502AudioFlinger::EffectChain::~EffectChain()
8503{
8504 if (mOwnInBuffer) {
8505 delete mInBuffer;
8506 }
8507
8508}
8509
Eric Laurent59255e42011-07-27 19:49:51 -07008510// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008511sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008512{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008513 size_t size = mEffects.size();
8514
8515 for (size_t i = 0; i < size; i++) {
8516 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008517 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008518 }
8519 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008520 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008521}
8522
Eric Laurent59255e42011-07-27 19:49:51 -07008523// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008524sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008525{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008526 size_t size = mEffects.size();
8527
8528 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07008529 // by convention, return first effect if id provided is 0 (0 is never a valid id)
8530 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008531 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008532 }
8533 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008534 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008535}
8536
Eric Laurent59255e42011-07-27 19:49:51 -07008537// getEffectFromType_l() must be called with ThreadBase::mLock held
8538sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
8539 const effect_uuid_t *type)
8540{
Eric Laurent59255e42011-07-27 19:49:51 -07008541 size_t size = mEffects.size();
8542
8543 for (size_t i = 0; i < size; i++) {
8544 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008545 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07008546 }
8547 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008548 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008549}
8550
Mathias Agopian65ab4712010-07-14 17:59:35 -07008551// Must be called with EffectChain::mLock locked
8552void AudioFlinger::EffectChain::process_l()
8553{
Eric Laurentdac69112010-09-28 14:09:57 -07008554 sp<ThreadBase> thread = mThread.promote();
8555 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008556 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07008557 return;
8558 }
Dima Zavinfce7a472011-04-19 22:30:36 -07008559 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
8560 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08008561 // always process effects unless no more tracks are on the session and the effect tail
8562 // has been rendered
8563 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07008564 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008565 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07008566
Eric Laurent544fe9b2011-11-11 15:42:52 -08008567 if (!tracksOnSession && mTailBufferCount == 0) {
8568 doProcess = false;
8569 }
8570
8571 if (activeTrackCnt() == 0) {
8572 // if no track is active and the effect tail has not been rendered,
8573 // the input buffer must be cleared here as the mixer process will not do it
8574 if (tracksOnSession || mTailBufferCount > 0) {
8575 size_t numSamples = thread->frameCount() * thread->channelCount();
8576 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
8577 if (mTailBufferCount > 0) {
8578 mTailBufferCount--;
8579 }
8580 }
8581 }
Eric Laurentdac69112010-09-28 14:09:57 -07008582 }
8583
Mathias Agopian65ab4712010-07-14 17:59:35 -07008584 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08008585 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07008586 for (size_t i = 0; i < size; i++) {
8587 mEffects[i]->process();
8588 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008589 }
8590 for (size_t i = 0; i < size; i++) {
8591 mEffects[i]->updateState();
8592 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008593}
8594
Eric Laurentcab11242010-07-15 12:50:15 -07008595// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07008596status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008597{
8598 effect_descriptor_t desc = effect->desc();
8599 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
8600
8601 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07008602 effect->setChain(this);
8603 sp<ThreadBase> thread = mThread.promote();
8604 if (thread == 0) {
8605 return NO_INIT;
8606 }
8607 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008608
8609 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8610 // Auxiliary effects are inserted at the beginning of mEffects vector as
8611 // they are processed first and accumulated in chain input buffer
8612 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07008613
Mathias Agopian65ab4712010-07-14 17:59:35 -07008614 // the input buffer for auxiliary effect contains mono samples in
8615 // 32 bit format. This is to avoid saturation in AudoMixer
8616 // accumulation stage. Saturation is done in EffectModule::process() before
8617 // calling the process in effect engine
8618 size_t numSamples = thread->frameCount();
8619 int32_t *buffer = new int32_t[numSamples];
8620 memset(buffer, 0, numSamples * sizeof(int32_t));
8621 effect->setInBuffer((int16_t *)buffer);
8622 // auxiliary effects output samples to chain input buffer for further processing
8623 // by insert effects
8624 effect->setOutBuffer(mInBuffer);
8625 } else {
8626 // Insert effects are inserted at the end of mEffects vector as they are processed
8627 // after track and auxiliary effects.
8628 // Insert effect order as a function of indicated preference:
8629 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8630 // another effect is present
8631 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8632 // last effect claiming first position
8633 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8634 // first effect claiming last position
8635 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8636 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8637 // already present
8638
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008639 size_t size = mEffects.size();
8640 size_t idx_insert = size;
8641 ssize_t idx_insert_first = -1;
8642 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008643
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008644 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008645 effect_descriptor_t d = mEffects[i]->desc();
8646 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8647 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8648 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8649 // check invalid effect chaining combinations
8650 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8651 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008652 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008653 return INVALID_OPERATION;
8654 }
8655 // remember position of first insert effect and by default
8656 // select this as insert position for new effect
8657 if (idx_insert == size) {
8658 idx_insert = i;
8659 }
8660 // remember position of last insert effect claiming
8661 // first position
8662 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8663 idx_insert_first = i;
8664 }
8665 // remember position of first insert effect claiming
8666 // last position
8667 if (iPref == EFFECT_FLAG_INSERT_LAST &&
8668 idx_insert_last == -1) {
8669 idx_insert_last = i;
8670 }
8671 }
8672 }
8673
8674 // modify idx_insert from first position if needed
8675 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8676 if (idx_insert_last != -1) {
8677 idx_insert = idx_insert_last;
8678 } else {
8679 idx_insert = size;
8680 }
8681 } else {
8682 if (idx_insert_first != -1) {
8683 idx_insert = idx_insert_first + 1;
8684 }
8685 }
8686
8687 // always read samples from chain input buffer
8688 effect->setInBuffer(mInBuffer);
8689
8690 // if last effect in the chain, output samples to chain
8691 // output buffer, otherwise to chain input buffer
8692 if (idx_insert == size) {
8693 if (idx_insert != 0) {
8694 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
8695 mEffects[idx_insert-1]->configure();
8696 }
8697 effect->setOutBuffer(mOutBuffer);
8698 } else {
8699 effect->setOutBuffer(mInBuffer);
8700 }
8701 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008702
Steve Block3856b092011-10-20 11:56:00 +01008703 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008704 }
8705 effect->configure();
8706 return NO_ERROR;
8707}
8708
Eric Laurentcab11242010-07-15 12:50:15 -07008709// removeEffect_l() must be called with PlaybackThread::mLock held
8710size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008711{
8712 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008713 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008714 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
8715
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008716 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008717 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07008718 // calling stop here will remove pre-processing effect from the audio HAL.
8719 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
8720 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07008721 if (mEffects[i]->state() == EffectModule::ACTIVE ||
8722 mEffects[i]->state() == EffectModule::STOPPING) {
8723 mEffects[i]->stop();
8724 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008725 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
8726 delete[] effect->inBuffer();
8727 } else {
8728 if (i == size - 1 && i != 0) {
8729 mEffects[i - 1]->setOutBuffer(mOutBuffer);
8730 mEffects[i - 1]->configure();
8731 }
8732 }
8733 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01008734 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008735 break;
8736 }
8737 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008738
8739 return mEffects.size();
8740}
8741
Eric Laurentcab11242010-07-15 12:50:15 -07008742// setDevice_l() must be called with PlaybackThread::mLock held
8743void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008744{
8745 size_t size = mEffects.size();
8746 for (size_t i = 0; i < size; i++) {
8747 mEffects[i]->setDevice(device);
8748 }
8749}
8750
Eric Laurentcab11242010-07-15 12:50:15 -07008751// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08008752void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008753{
8754 size_t size = mEffects.size();
8755 for (size_t i = 0; i < size; i++) {
8756 mEffects[i]->setMode(mode);
8757 }
8758}
8759
Eric Laurentcab11242010-07-15 12:50:15 -07008760// setVolume_l() must be called with PlaybackThread::mLock held
8761bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008762{
8763 uint32_t newLeft = *left;
8764 uint32_t newRight = *right;
8765 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07008766 int ctrlIdx = -1;
8767 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008768
Eric Laurentcab11242010-07-15 12:50:15 -07008769 // first update volume controller
8770 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07008771 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07008772 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
8773 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07008774 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07008775 break;
8776 }
8777 }
8778
8779 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07008780 if (hasControl) {
8781 *left = mNewLeftVolume;
8782 *right = mNewRightVolume;
8783 }
8784 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07008785 }
8786
8787 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07008788 mLeftVolume = newLeft;
8789 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008790
8791 // second get volume update from volume controller
8792 if (ctrlIdx >= 0) {
8793 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07008794 mNewLeftVolume = newLeft;
8795 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008796 }
8797 // then indicate volume to all other effects in chain.
8798 // Pass altered volume to effects before volume controller
8799 // and requested volume to effects after controller
8800 uint32_t lVol = newLeft;
8801 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008802
Mathias Agopian65ab4712010-07-14 17:59:35 -07008803 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07008804 if ((int)i == ctrlIdx) continue;
8805 // this also works for ctrlIdx == -1 when there is no volume controller
8806 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008807 lVol = *left;
8808 rVol = *right;
8809 }
8810 mEffects[i]->setVolume(&lVol, &rVol, false);
8811 }
8812 *left = newLeft;
8813 *right = newRight;
8814
8815 return hasControl;
8816}
8817
Mathias Agopian65ab4712010-07-14 17:59:35 -07008818status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
8819{
8820 const size_t SIZE = 256;
8821 char buffer[SIZE];
8822 String8 result;
8823
8824 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
8825 result.append(buffer);
8826
8827 bool locked = tryLock(mLock);
8828 // failed to lock - AudioFlinger is probably deadlocked
8829 if (!locked) {
8830 result.append("\tCould not lock mutex:\n");
8831 }
8832
Eric Laurentcab11242010-07-15 12:50:15 -07008833 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
8834 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008835 mEffects.size(),
8836 (uint32_t)mInBuffer,
8837 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008838 mActiveTrackCnt);
8839 result.append(buffer);
8840 write(fd, result.string(), result.size());
8841
8842 for (size_t i = 0; i < mEffects.size(); ++i) {
8843 sp<EffectModule> effect = mEffects[i];
8844 if (effect != 0) {
8845 effect->dump(fd, args);
8846 }
8847 }
8848
8849 if (locked) {
8850 mLock.unlock();
8851 }
8852
8853 return NO_ERROR;
8854}
8855
Eric Laurent59255e42011-07-27 19:49:51 -07008856// must be called with ThreadBase::mLock held
8857void AudioFlinger::EffectChain::setEffectSuspended_l(
8858 const effect_uuid_t *type, bool suspend)
8859{
8860 sp<SuspendedEffectDesc> desc;
8861 // use effect type UUID timelow as key as there is no real risk of identical
8862 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008863 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008864 if (suspend) {
8865 if (index >= 0) {
8866 desc = mSuspendedEffects.valueAt(index);
8867 } else {
8868 desc = new SuspendedEffectDesc();
8869 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
8870 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01008871 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008872 }
8873 if (desc->mRefCount++ == 0) {
8874 sp<EffectModule> effect = getEffectIfEnabled(type);
8875 if (effect != 0) {
8876 desc->mEffect = effect;
8877 effect->setSuspended(true);
8878 effect->setEnabled(false);
8879 }
8880 }
8881 } else {
8882 if (index < 0) {
8883 return;
8884 }
8885 desc = mSuspendedEffects.valueAt(index);
8886 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008887 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008888 desc->mRefCount = 1;
8889 }
8890 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01008891 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008892 if (desc->mEffect != 0) {
8893 sp<EffectModule> effect = desc->mEffect.promote();
8894 if (effect != 0) {
8895 effect->setSuspended(false);
8896 sp<EffectHandle> handle = effect->controlHandle();
8897 if (handle != 0) {
8898 effect->setEnabled(handle->enabled());
8899 }
8900 }
8901 desc->mEffect.clear();
8902 }
8903 mSuspendedEffects.removeItemsAt(index);
8904 }
8905 }
8906}
8907
8908// must be called with ThreadBase::mLock held
8909void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
8910{
8911 sp<SuspendedEffectDesc> desc;
8912
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008913 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07008914 if (suspend) {
8915 if (index >= 0) {
8916 desc = mSuspendedEffects.valueAt(index);
8917 } else {
8918 desc = new SuspendedEffectDesc();
8919 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01008920 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07008921 }
8922 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08008923 Vector< sp<EffectModule> > effects;
8924 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07008925 for (size_t i = 0; i < effects.size(); i++) {
8926 setEffectSuspended_l(&effects[i]->desc().type, true);
8927 }
8928 }
8929 } else {
8930 if (index < 0) {
8931 return;
8932 }
8933 desc = mSuspendedEffects.valueAt(index);
8934 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008935 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008936 desc->mRefCount = 1;
8937 }
8938 if (--desc->mRefCount == 0) {
8939 Vector<const effect_uuid_t *> types;
8940 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8941 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8942 continue;
8943 }
8944 types.add(&mSuspendedEffects.valueAt(i)->mType);
8945 }
8946 for (size_t i = 0; i < types.size(); i++) {
8947 setEffectSuspended_l(types[i], false);
8948 }
Steve Block3856b092011-10-20 11:56:00 +01008949 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008950 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8951 }
8952 }
8953}
8954
Eric Laurent6bffdb82011-09-23 08:40:41 -07008955
8956// The volume effect is used for automated tests only
8957#ifndef OPENSL_ES_H_
8958static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8959 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8960const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8961#endif //OPENSL_ES_H_
8962
Eric Laurentdb7c0792011-08-10 10:37:50 -07008963bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8964{
8965 // auxiliary effects and visualizer are never suspended on output mix
8966 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8967 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008968 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8969 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008970 return false;
8971 }
8972 return true;
8973}
8974
Glenn Kastend0539712012-01-30 12:56:03 -08008975void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008976{
Glenn Kastend0539712012-01-30 12:56:03 -08008977 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008978 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008979 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8980 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008981 }
Eric Laurent59255e42011-07-27 19:49:51 -07008982 }
Eric Laurent59255e42011-07-27 19:49:51 -07008983}
8984
8985sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8986 const effect_uuid_t *type)
8987{
Glenn Kasten090f0192012-01-30 13:00:02 -08008988 sp<EffectModule> effect = getEffectFromType_l(type);
8989 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008990}
8991
8992void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8993 bool enabled)
8994{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008995 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008996 if (enabled) {
8997 if (index < 0) {
8998 // if the effect is not suspend check if all effects are suspended
8999 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9000 if (index < 0) {
9001 return;
9002 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009003 if (!isEffectEligibleForSuspend(effect->desc())) {
9004 return;
9005 }
Eric Laurent59255e42011-07-27 19:49:51 -07009006 setEffectSuspended_l(&effect->desc().type, enabled);
9007 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009008 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009009 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009010 return;
9011 }
Eric Laurent59255e42011-07-27 19:49:51 -07009012 }
Steve Block3856b092011-10-20 11:56:00 +01009013 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009014 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009015 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9016 // if effect is requested to suspended but was not yet enabled, supend it now.
9017 if (desc->mEffect == 0) {
9018 desc->mEffect = effect;
9019 effect->setEnabled(false);
9020 effect->setSuspended(true);
9021 }
9022 } else {
9023 if (index < 0) {
9024 return;
9025 }
Steve Block3856b092011-10-20 11:56:00 +01009026 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009027 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009028 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9029 desc->mEffect.clear();
9030 effect->setSuspended(false);
9031 }
9032}
9033
Mathias Agopian65ab4712010-07-14 17:59:35 -07009034#undef LOG_TAG
9035#define LOG_TAG "AudioFlinger"
9036
9037// ----------------------------------------------------------------------------
9038
9039status_t AudioFlinger::onTransact(
9040 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9041{
9042 return BnAudioFlinger::onTransact(code, data, reply, flags);
9043}
9044
Mathias Agopian65ab4712010-07-14 17:59:35 -07009045}; // namespace android