blob: 6eeda9ab6defdf91880329e27fb88500306f085c [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080038#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039
Glenn Kastend3cee2f2012-03-13 17:55:35 -070040#undef ADD_BATTERY_DATA
41
42#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080043#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080044#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070045#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070046
47#include <private/media/AudioTrackShared.h>
48#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070049
Dima Zavin64760242011-05-11 14:15:23 -070050#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070051#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
53#include "AudioMixer.h"
54#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080055#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Mathias Agopian65ab4712010-07-14 17:59:35 -070057#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070058#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070059#include <audio_effects/effect_ns.h>
60#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061
Glenn Kasten3b21c502011-12-15 09:52:39 -080062#include <audio_utils/primitives.h>
63
Eric Laurentfeb0db62011-07-22 09:04:31 -070064#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080065
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070066// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080067#ifdef DEBUG_CPU_USAGE
68#include <cpustats/CentralTendencyStatistics.h>
69#include <cpustats/ThreadCpuUsage.h>
70#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070071
John Grossman4ff14ba2012-02-08 16:37:41 -080072#include <common_time/cc_helper.h>
73#include <common_time/local_clock.h>
74
Glenn Kasten58912562012-04-03 10:45:00 -070075#include "FastMixer.h"
76
77// NBAIO implementations
78#include "AudioStreamOutSink.h"
79#include "MonoPipe.h"
80#include "MonoPipeReader.h"
81#include "SourceAudioBufferProvider.h"
82
Glenn Kasten1dc28b72012-04-24 10:01:03 -070083#ifdef HAVE_REQUEST_PRIORITY
84#include "SchedulingPolicyService.h"
85#endif
86
Glenn Kasten58912562012-04-03 10:45:00 -070087#ifdef SOAKER
88#include "Soaker.h"
89#endif
90
Mathias Agopian65ab4712010-07-14 17:59:35 -070091// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070092
John Grossman1c345192012-03-27 14:00:17 -070093// Note: the following macro is used for extremely verbose logging message. In
94// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
95// 0; but one side effect of this is to turn all LOGV's as well. Some messages
96// are so verbose that we want to suppress them even when we have ALOG_ASSERT
97// turned on. Do not uncomment the #def below unless you really know what you
98// are doing and want to see all of the extremely verbose messages.
99//#define VERY_VERY_VERBOSE_LOGGING
100#ifdef VERY_VERY_VERBOSE_LOGGING
101#define ALOGVV ALOGV
102#else
103#define ALOGVV(a...) do { } while(0)
104#endif
Eric Laurentde070132010-07-13 04:45:46 -0700105
Mathias Agopian65ab4712010-07-14 17:59:35 -0700106namespace android {
107
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800108static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
109static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110
Mathias Agopian65ab4712010-07-14 17:59:35 -0700111static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800112static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700113
114// retry counts for buffer fill timeout
115// 50 * ~20msecs = 1 second
116static const int8_t kMaxTrackRetries = 50;
117static const int8_t kMaxTrackStartupRetries = 50;
118// allow less retry attempts on direct output thread.
119// direct outputs can be a scarce resource in audio hardware and should
120// be released as quickly as possible.
121static const int8_t kMaxTrackRetriesDirect = 2;
122
123static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800124static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700125
Glenn Kasten7dede872011-12-13 11:04:14 -0800126// don't warn about blocked writes or record buffer overflows more often than this
127static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700129// RecordThread loop sleep time upon application overrun or audio HAL read error
130static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700131
Glenn Kasten7dede872011-12-13 11:04:14 -0800132// maximum time to wait for setParameters to complete
133static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700134
Eric Laurent7cafbb32011-11-22 18:50:29 -0800135// minimum sleep time for the mixer thread loop when tracks are active but in underrun
136static const uint32_t kMinThreadSleepTimeUs = 5000;
137// maximum divider applied to the active sleep time in the mixer thread loop
138static const uint32_t kMaxThreadSleepTimeShift = 2;
139
Glenn Kasten58912562012-04-03 10:45:00 -0700140// minimum normal mix buffer size, expressed in milliseconds rather than frames
141static const uint32_t kMinNormalMixBufferSizeMs = 20;
142
John Grossman4ff14ba2012-02-08 16:37:41 -0800143nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800144
Mathias Agopian65ab4712010-07-14 17:59:35 -0700145// ----------------------------------------------------------------------------
146
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700147#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800148// To collect the amplifier usage
149static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800150 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
151 if (service == NULL) {
152 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800153 return;
154 }
155
156 service->addBatteryData(params);
157}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700158#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800159
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700160static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700161{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700162 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700163 int rc;
164
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700165 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
166 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
167 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
168 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700169 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700170 }
171 rc = audio_hw_device_open(mod, dev);
172 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
173 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
174 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700175 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700176 }
177 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
178 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
179 rc = BAD_VALUE;
180 goto out;
181 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700182 return 0;
183
184out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700185 *dev = NULL;
186 return rc;
187}
188
Mathias Agopian65ab4712010-07-14 17:59:35 -0700189// ----------------------------------------------------------------------------
190
191AudioFlinger::AudioFlinger()
192 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800193 mPrimaryHardwareDev(NULL),
194 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
195 mMasterVolume(1.0f),
196 mMasterVolumeSupportLvl(MVS_NONE),
197 mMasterMute(false),
198 mNextUniqueId(1),
199 mMode(AUDIO_MODE_INVALID),
200 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700201{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700202}
203
204void AudioFlinger::onFirstRef()
205{
Dima Zavin799a70e2011-04-18 16:57:27 -0700206 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700207
Eric Laurent93575202011-01-18 18:39:02 -0800208 Mutex::Autolock _l(mLock);
209
Dima Zavin799a70e2011-04-18 16:57:27 -0700210 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800211 char val_str[PROPERTY_VALUE_MAX] = { 0 };
212 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
213 uint32_t int_val;
214 if (1 == sscanf(val_str, "%u", &int_val)) {
215 mStandbyTimeInNsecs = milliseconds(int_val);
216 ALOGI("Using %u mSec as standby time.", int_val);
217 } else {
218 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
219 ALOGI("Using default %u mSec as standby time.",
220 (uint32_t)(mStandbyTimeInNsecs / 1000000));
221 }
222 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700223
Eric Laurenta4c5a552012-03-29 10:12:40 -0700224 mMode = AUDIO_MODE_NORMAL;
225 mMasterVolumeSW = 1.0;
226 mMasterVolume = 1.0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800227 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700228}
229
230AudioFlinger::~AudioFlinger()
231{
Dima Zavin799a70e2011-04-18 16:57:27 -0700232
Mathias Agopian65ab4712010-07-14 17:59:35 -0700233 while (!mRecordThreads.isEmpty()) {
234 // closeInput() will remove first entry from mRecordThreads
235 closeInput(mRecordThreads.keyAt(0));
236 }
237 while (!mPlaybackThreads.isEmpty()) {
238 // closeOutput() will remove first entry from mPlaybackThreads
239 closeOutput(mPlaybackThreads.keyAt(0));
240 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700241
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800242 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
243 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700244 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
245 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700246 }
247}
248
Eric Laurenta4c5a552012-03-29 10:12:40 -0700249static const char * const audio_interfaces[] = {
250 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
251 AUDIO_HARDWARE_MODULE_ID_A2DP,
252 AUDIO_HARDWARE_MODULE_ID_USB,
253};
254#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
255
256audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, uint32_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700257{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700258 // if module is 0, the request comes from an old policy manager and we should load
259 // well known modules
260 if (module == 0) {
261 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
262 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
263 loadHwModule_l(audio_interfaces[i]);
264 }
265 } else {
266 // check a match for the requested module handle
267 AudioHwDevice *audioHwdevice = mAudioHwDevs.valueFor(module);
268 if (audioHwdevice != NULL) {
269 return audioHwdevice->hwDevice();
270 }
271 }
272 // then try to find a module supporting the requested device.
Dima Zavin799a70e2011-04-18 16:57:27 -0700273 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700274 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700275 if ((dev->get_supported_devices(dev) & devices) == devices)
276 return dev;
277 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700278
Dima Zavin799a70e2011-04-18 16:57:27 -0700279 return NULL;
280}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700281
282status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
283{
284 const size_t SIZE = 256;
285 char buffer[SIZE];
286 String8 result;
287
288 result.append("Clients:\n");
289 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800290 sp<Client> client = mClients.valueAt(i).promote();
291 if (client != 0) {
292 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
293 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700294 }
295 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700296
297 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800298 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700299 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
300 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800301 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700302 result.append(buffer);
303 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700304 write(fd, result.string(), result.size());
305 return NO_ERROR;
306}
307
308
309status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
310{
311 const size_t SIZE = 256;
312 char buffer[SIZE];
313 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800314 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700315
John Grossman4ff14ba2012-02-08 16:37:41 -0800316 snprintf(buffer, SIZE, "Hardware status: %d\n"
317 "Standby Time mSec: %u\n",
318 hardwareStatus,
319 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700320 result.append(buffer);
321 write(fd, result.string(), result.size());
322 return NO_ERROR;
323}
324
325status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
326{
327 const size_t SIZE = 256;
328 char buffer[SIZE];
329 String8 result;
330 snprintf(buffer, SIZE, "Permission Denial: "
331 "can't dump AudioFlinger from pid=%d, uid=%d\n",
332 IPCThreadState::self()->getCallingPid(),
333 IPCThreadState::self()->getCallingUid());
334 result.append(buffer);
335 write(fd, result.string(), result.size());
336 return NO_ERROR;
337}
338
339static bool tryLock(Mutex& mutex)
340{
341 bool locked = false;
342 for (int i = 0; i < kDumpLockRetries; ++i) {
343 if (mutex.tryLock() == NO_ERROR) {
344 locked = true;
345 break;
346 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800347 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700348 }
349 return locked;
350}
351
352status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
353{
Glenn Kasten44deb052012-02-05 18:09:08 -0800354 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700355 dumpPermissionDenial(fd, args);
356 } else {
357 // get state of hardware lock
358 bool hardwareLocked = tryLock(mHardwareLock);
359 if (!hardwareLocked) {
360 String8 result(kHardwareLockedString);
361 write(fd, result.string(), result.size());
362 } else {
363 mHardwareLock.unlock();
364 }
365
366 bool locked = tryLock(mLock);
367
368 // failed to lock - AudioFlinger is probably deadlocked
369 if (!locked) {
370 String8 result(kDeadlockedString);
371 write(fd, result.string(), result.size());
372 }
373
374 dumpClients(fd, args);
375 dumpInternals(fd, args);
376
377 // dump playback threads
378 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
379 mPlaybackThreads.valueAt(i)->dump(fd, args);
380 }
381
382 // dump record threads
383 for (size_t i = 0; i < mRecordThreads.size(); i++) {
384 mRecordThreads.valueAt(i)->dump(fd, args);
385 }
386
Dima Zavin799a70e2011-04-18 16:57:27 -0700387 // dump all hardware devs
388 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700389 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700390 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700391 }
392 if (locked) mLock.unlock();
393 }
394 return NO_ERROR;
395}
396
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800397sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
398{
399 // If pid is already in the mClients wp<> map, then use that entry
400 // (for which promote() is always != 0), otherwise create a new entry and Client.
401 sp<Client> client = mClients.valueFor(pid).promote();
402 if (client == 0) {
403 client = new Client(this, pid);
404 mClients.add(pid, client);
405 }
406
407 return client;
408}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700409
410// IAudioFlinger interface
411
412
413sp<IAudioTrack> AudioFlinger::createTrack(
414 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800415 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700416 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800417 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700418 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700419 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800420 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700421 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800422 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800423 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700424 int *sessionId,
425 status_t *status)
426{
427 sp<PlaybackThread::Track> track;
428 sp<TrackHandle> trackHandle;
429 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700430 status_t lStatus;
431 int lSessionId;
432
Glenn Kasten263709e2012-01-06 08:40:01 -0800433 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
434 // but if someone uses binder directly they could bypass that and cause us to crash
435 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000436 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437 lStatus = BAD_VALUE;
438 goto Exit;
439 }
440
441 {
442 Mutex::Autolock _l(mLock);
443 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700444 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700445 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000446 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700447 lStatus = BAD_VALUE;
448 goto Exit;
449 }
450
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800451 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452
Steve Block3856b092011-10-20 11:56:00 +0100453 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700454 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700455 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700456 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
457 if (mPlaybackThreads.keyAt(i) != output) {
458 // prevent same audio session on different output threads
459 uint32_t sessions = t->hasAudioSession(*sessionId);
460 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000461 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700462 lStatus = BAD_VALUE;
463 goto Exit;
464 }
465 // check if an effect with same session ID is waiting for a track to be created
466 if (sessions & PlaybackThread::EFFECT_SESSION) {
467 effectThread = t.get();
468 }
Eric Laurentde070132010-07-13 04:45:46 -0700469 }
470 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700471 lSessionId = *sessionId;
472 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700473 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700474 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700475 if (sessionId != NULL) {
476 *sessionId = lSessionId;
477 }
478 }
Steve Block3856b092011-10-20 11:56:00 +0100479 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700480
481 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800482 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700483
484 // move effect chain to this output thread if an effect on same session was waiting
485 // for a track to be created
486 if (lStatus == NO_ERROR && effectThread != NULL) {
487 Mutex::Autolock _dl(thread->mLock);
488 Mutex::Autolock _sl(effectThread->mLock);
489 moveEffectChain_l(lSessionId, effectThread, thread, true);
490 }
Eric Laurenta011e352012-03-29 15:51:43 -0700491
492 // Look for sync events awaiting for a session to be used.
493 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
494 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
495 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
496 track->setSyncEvent(mPendingSyncEvents[i]);
497 mPendingSyncEvents.removeAt(i);
498 i--;
499 }
500 }
501 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700502 }
503 if (lStatus == NO_ERROR) {
504 trackHandle = new TrackHandle(track);
505 } else {
506 // remove local strong reference to Client before deleting the Track so that the Client
507 // destructor is called by the TrackBase destructor with mLock held
508 client.clear();
509 track.clear();
510 }
511
512Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700513 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700514 *status = lStatus;
515 }
516 return trackHandle;
517}
518
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800519uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700520{
521 Mutex::Autolock _l(mLock);
522 PlaybackThread *thread = checkPlaybackThread_l(output);
523 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000524 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700525 return 0;
526 }
527 return thread->sampleRate();
528}
529
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800530int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700531{
532 Mutex::Autolock _l(mLock);
533 PlaybackThread *thread = checkPlaybackThread_l(output);
534 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000535 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700536 return 0;
537 }
538 return thread->channelCount();
539}
540
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800541audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700542{
543 Mutex::Autolock _l(mLock);
544 PlaybackThread *thread = checkPlaybackThread_l(output);
545 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000546 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800547 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700548 }
549 return thread->format();
550}
551
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800552size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553{
554 Mutex::Autolock _l(mLock);
555 PlaybackThread *thread = checkPlaybackThread_l(output);
556 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000557 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558 return 0;
559 }
Glenn Kasten58912562012-04-03 10:45:00 -0700560 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
561 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700562 return thread->frameCount();
563}
564
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800565uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700566{
567 Mutex::Autolock _l(mLock);
568 PlaybackThread *thread = checkPlaybackThread_l(output);
569 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000570 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700571 return 0;
572 }
573 return thread->latency();
574}
575
576status_t AudioFlinger::setMasterVolume(float value)
577{
Eric Laurenta1884f92011-08-23 08:25:03 -0700578 status_t ret = initCheck();
579 if (ret != NO_ERROR) {
580 return ret;
581 }
582
Mathias Agopian65ab4712010-07-14 17:59:35 -0700583 // check calling permissions
584 if (!settingsAllowed()) {
585 return PERMISSION_DENIED;
586 }
587
John Grossman4ff14ba2012-02-08 16:37:41 -0800588 float swmv = value;
589
Eric Laurenta4c5a552012-03-29 10:12:40 -0700590 Mutex::Autolock _l(mLock);
591
Mathias Agopian65ab4712010-07-14 17:59:35 -0700592 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800593 if (MVS_NONE != mMasterVolumeSupportLvl) {
594 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
595 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700596 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
John Grossman4ff14ba2012-02-08 16:37:41 -0800597
598 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
599 if (NULL != dev->set_master_volume) {
600 dev->set_master_volume(dev, value);
601 }
602 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800603 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800604
605 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700606 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700607
John Grossman4ff14ba2012-02-08 16:37:41 -0800608 mMasterVolume = value;
609 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800610 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700611 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700612
613 return NO_ERROR;
614}
615
Glenn Kastenf78aee72012-01-04 11:00:47 -0800616status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700617{
Eric Laurenta1884f92011-08-23 08:25:03 -0700618 status_t ret = initCheck();
619 if (ret != NO_ERROR) {
620 return ret;
621 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700622
623 // check calling permissions
624 if (!settingsAllowed()) {
625 return PERMISSION_DENIED;
626 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800627 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000628 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700629 return BAD_VALUE;
630 }
631
632 { // scope for the lock
633 AutoMutex lock(mHardwareLock);
634 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700635 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700636 mHardwareStatus = AUDIO_HW_IDLE;
637 }
638
639 if (NO_ERROR == ret) {
640 Mutex::Autolock _l(mLock);
641 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800642 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700643 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700644 }
645
646 return ret;
647}
648
649status_t AudioFlinger::setMicMute(bool state)
650{
Eric Laurenta1884f92011-08-23 08:25:03 -0700651 status_t ret = initCheck();
652 if (ret != NO_ERROR) {
653 return ret;
654 }
655
Mathias Agopian65ab4712010-07-14 17:59:35 -0700656 // check calling permissions
657 if (!settingsAllowed()) {
658 return PERMISSION_DENIED;
659 }
660
661 AutoMutex lock(mHardwareLock);
662 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700663 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700664 mHardwareStatus = AUDIO_HW_IDLE;
665 return ret;
666}
667
668bool AudioFlinger::getMicMute() const
669{
Eric Laurenta1884f92011-08-23 08:25:03 -0700670 status_t ret = initCheck();
671 if (ret != NO_ERROR) {
672 return false;
673 }
674
Dima Zavinfce7a472011-04-19 22:30:36 -0700675 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800676 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700677 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700678 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700679 mHardwareStatus = AUDIO_HW_IDLE;
680 return state;
681}
682
683status_t AudioFlinger::setMasterMute(bool muted)
684{
685 // check calling permissions
686 if (!settingsAllowed()) {
687 return PERMISSION_DENIED;
688 }
689
Eric Laurent93575202011-01-18 18:39:02 -0800690 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800691 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700692 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800693 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700694 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700695
696 return NO_ERROR;
697}
698
699float AudioFlinger::masterVolume() const
700{
Glenn Kasten98067102011-12-13 11:47:54 -0800701 Mutex::Autolock _l(mLock);
702 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700703}
704
John Grossman4ff14ba2012-02-08 16:37:41 -0800705float AudioFlinger::masterVolumeSW() const
706{
707 Mutex::Autolock _l(mLock);
708 return masterVolumeSW_l();
709}
710
Mathias Agopian65ab4712010-07-14 17:59:35 -0700711bool AudioFlinger::masterMute() const
712{
Glenn Kasten98067102011-12-13 11:47:54 -0800713 Mutex::Autolock _l(mLock);
714 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700715}
716
John Grossman4ff14ba2012-02-08 16:37:41 -0800717float AudioFlinger::masterVolume_l() const
718{
719 if (MVS_FULL == mMasterVolumeSupportLvl) {
720 float ret_val;
721 AutoMutex lock(mHardwareLock);
722
723 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800724 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
725 (NULL != mPrimaryHardwareDev->get_master_volume),
726 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800727
728 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
729 mHardwareStatus = AUDIO_HW_IDLE;
730 return ret_val;
731 }
732
733 return mMasterVolume;
734}
735
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800736status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
737 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700738{
739 // check calling permissions
740 if (!settingsAllowed()) {
741 return PERMISSION_DENIED;
742 }
743
Glenn Kasten263709e2012-01-06 08:40:01 -0800744 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000745 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700746 return BAD_VALUE;
747 }
748
749 AutoMutex lock(mLock);
750 PlaybackThread *thread = NULL;
751 if (output) {
752 thread = checkPlaybackThread_l(output);
753 if (thread == NULL) {
754 return BAD_VALUE;
755 }
756 }
757
758 mStreamTypes[stream].volume = value;
759
760 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800761 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700762 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700763 }
764 } else {
765 thread->setStreamVolume(stream, value);
766 }
767
768 return NO_ERROR;
769}
770
Glenn Kastenfff6d712012-01-12 16:38:12 -0800771status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700772{
773 // check calling permissions
774 if (!settingsAllowed()) {
775 return PERMISSION_DENIED;
776 }
777
Glenn Kasten263709e2012-01-06 08:40:01 -0800778 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700779 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000780 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700781 return BAD_VALUE;
782 }
783
Eric Laurent93575202011-01-18 18:39:02 -0800784 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700785 mStreamTypes[stream].mute = muted;
786 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700787 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700788
789 return NO_ERROR;
790}
791
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800792float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700793{
Glenn Kasten263709e2012-01-06 08:40:01 -0800794 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700795 return 0.0f;
796 }
797
798 AutoMutex lock(mLock);
799 float volume;
800 if (output) {
801 PlaybackThread *thread = checkPlaybackThread_l(output);
802 if (thread == NULL) {
803 return 0.0f;
804 }
805 volume = thread->streamVolume(stream);
806 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800807 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700808 }
809
810 return volume;
811}
812
Glenn Kastenfff6d712012-01-12 16:38:12 -0800813bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814{
Glenn Kasten263709e2012-01-06 08:40:01 -0800815 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700816 return true;
817 }
818
Glenn Kasten6637baa2012-01-09 09:40:36 -0800819 AutoMutex lock(mLock);
820 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821}
822
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800823status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700824{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800825 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700826 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
827 // check calling permissions
828 if (!settingsAllowed()) {
829 return PERMISSION_DENIED;
830 }
831
Mathias Agopian65ab4712010-07-14 17:59:35 -0700832 // ioHandle == 0 means the parameters are global to the audio hardware interface
833 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700834 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700835 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800836 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700837 AutoMutex lock(mHardwareLock);
838 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
839 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
840 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
841 status_t result = dev->set_parameters(dev, keyValuePairs.string());
842 final_result = result ?: final_result;
843 }
844 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800845 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700846 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
847 AudioParameter param = AudioParameter(keyValuePairs);
848 String8 value;
849 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700850 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
851 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700852 for (size_t i = 0; i < mRecordThreads.size(); i++) {
853 sp<RecordThread> thread = mRecordThreads.valueAt(i);
854 RecordThread::RecordTrack *track = thread->track();
855 if (track != NULL) {
856 audio_devices_t device = (audio_devices_t)(
857 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700858 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700859 thread->setEffectSuspended(FX_IID_AEC,
860 suspend,
861 track->sessionId());
862 thread->setEffectSuspended(FX_IID_NS,
863 suspend,
864 track->sessionId());
865 }
866 }
Eric Laurentbee53372011-08-29 12:42:48 -0700867 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700868 }
869 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700870 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700871 }
872
873 // hold a strong ref on thread in case closeOutput() or closeInput() is called
874 // and the thread is exited once the lock is released
875 sp<ThreadBase> thread;
876 {
877 Mutex::Autolock _l(mLock);
878 thread = checkPlaybackThread_l(ioHandle);
879 if (thread == NULL) {
880 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800881 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700882 // indicate output device change to all input threads for pre processing
883 AudioParameter param = AudioParameter(keyValuePairs);
884 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700885 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
886 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700887 for (size_t i = 0; i < mRecordThreads.size(); i++) {
888 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
889 }
890 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700891 }
892 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800893 if (thread != 0) {
894 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700895 }
896 return BAD_VALUE;
897}
898
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800899String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700900{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800901// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700902// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
903
Eric Laurenta4c5a552012-03-29 10:12:40 -0700904 Mutex::Autolock _l(mLock);
905
Mathias Agopian65ab4712010-07-14 17:59:35 -0700906 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700907 String8 out_s8;
908
Dima Zavin799a70e2011-04-18 16:57:27 -0700909 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800910 char *s;
911 {
912 AutoMutex lock(mHardwareLock);
913 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700914 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800915 s = dev->get_parameters(dev, keys.string());
916 mHardwareStatus = AUDIO_HW_IDLE;
917 }
John Grossmanef7740b2012-02-09 11:28:36 -0800918 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700919 free(s);
920 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700921 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922 }
923
Mathias Agopian65ab4712010-07-14 17:59:35 -0700924 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
925 if (playbackThread != NULL) {
926 return playbackThread->getParameters(keys);
927 }
928 RecordThread *recordThread = checkRecordThread_l(ioHandle);
929 if (recordThread != NULL) {
930 return recordThread->getParameters(keys);
931 }
932 return String8("");
933}
934
Glenn Kastenf587ba52012-01-26 16:25:10 -0800935size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700936{
Eric Laurenta1884f92011-08-23 08:25:03 -0700937 status_t ret = initCheck();
938 if (ret != NO_ERROR) {
939 return 0;
940 }
941
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800942 AutoMutex lock(mHardwareLock);
943 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700944 struct audio_config config = {
945 sample_rate: sampleRate,
946 channel_mask: audio_channel_in_mask_from_count(channelCount),
947 format: format,
948 };
949 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800950 mHardwareStatus = AUDIO_HW_IDLE;
951 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700952}
953
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800954unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700955{
956 if (ioHandle == 0) {
957 return 0;
958 }
959
960 Mutex::Autolock _l(mLock);
961
962 RecordThread *recordThread = checkRecordThread_l(ioHandle);
963 if (recordThread != NULL) {
964 return recordThread->getInputFramesLost();
965 }
966 return 0;
967}
968
969status_t AudioFlinger::setVoiceVolume(float value)
970{
Eric Laurenta1884f92011-08-23 08:25:03 -0700971 status_t ret = initCheck();
972 if (ret != NO_ERROR) {
973 return ret;
974 }
975
Mathias Agopian65ab4712010-07-14 17:59:35 -0700976 // check calling permissions
977 if (!settingsAllowed()) {
978 return PERMISSION_DENIED;
979 }
980
981 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800982 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700983 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700984 mHardwareStatus = AUDIO_HW_IDLE;
985
986 return ret;
987}
988
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800989status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
990 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700991{
992 status_t status;
993
994 Mutex::Autolock _l(mLock);
995
996 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
997 if (playbackThread != NULL) {
998 return playbackThread->getRenderPosition(halFrames, dspFrames);
999 }
1000
1001 return BAD_VALUE;
1002}
1003
1004void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1005{
1006
1007 Mutex::Autolock _l(mLock);
1008
Glenn Kastenbb001922012-02-03 11:10:26 -08001009 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001010 if (mNotificationClients.indexOfKey(pid) < 0) {
1011 sp<NotificationClient> notificationClient = new NotificationClient(this,
1012 client,
1013 pid);
Steve Block3856b092011-10-20 11:56:00 +01001014 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001015
1016 mNotificationClients.add(pid, notificationClient);
1017
1018 sp<IBinder> binder = client->asBinder();
1019 binder->linkToDeath(notificationClient);
1020
1021 // the config change is always sent from playback or record threads to avoid deadlock
1022 // with AudioSystem::gLock
1023 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1024 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1025 }
1026
1027 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1028 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1029 }
1030 }
1031}
1032
1033void AudioFlinger::removeNotificationClient(pid_t pid)
1034{
1035 Mutex::Autolock _l(mLock);
1036
Glenn Kastena3b09252012-01-20 09:19:01 -08001037 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001038
Steve Block3856b092011-10-20 11:56:00 +01001039 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001040 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001041 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001042 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001043 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001044 ALOGV(" pid %d @ %d", ref->mPid, i);
1045 if (ref->mPid == pid) {
1046 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001047 mAudioSessionRefs.removeAt(i);
1048 delete ref;
1049 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001050 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001051 } else {
1052 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001053 }
1054 }
1055 if (removed) {
1056 purgeStaleEffects_l();
1057 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058}
1059
1060// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001061void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001062{
1063 size_t size = mNotificationClients.size();
1064 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001065 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1066 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001067 }
1068}
1069
1070// removeClient_l() must be called with AudioFlinger::mLock held
1071void AudioFlinger::removeClient_l(pid_t pid)
1072{
Steve Block3856b092011-10-20 11:56:00 +01001073 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001074 mClients.removeItem(pid);
1075}
1076
1077
1078// ----------------------------------------------------------------------------
1079
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001080AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1081 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001082 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001083 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001084 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001085 // mChannelMask
1086 mChannelCount(0),
1087 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1088 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001089 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001090 mDevice(device),
1091 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001092{
1093}
1094
1095AudioFlinger::ThreadBase::~ThreadBase()
1096{
1097 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001098 // do not lock the mutex in destructor
1099 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001100 if (mPowerManager != 0) {
1101 sp<IBinder> binder = mPowerManager->asBinder();
1102 binder->unlinkToDeath(mDeathRecipient);
1103 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001104}
1105
1106void AudioFlinger::ThreadBase::exit()
1107{
Steve Block3856b092011-10-20 11:56:00 +01001108 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001109 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001110 // This lock prevents the following race in thread (uniprocessor for illustration):
1111 // if (!exitPending()) {
1112 // // context switch from here to exit()
1113 // // exit() calls requestExit(), what exitPending() observes
1114 // // exit() calls signal(), which is dropped since no waiters
1115 // // context switch back from exit() to here
1116 // mWaitWorkCV.wait(...);
1117 // // now thread is hung
1118 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001119 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001120 requestExit();
1121 mWaitWorkCV.signal();
1122 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001123 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1124 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001125 requestExitAndWait();
1126}
1127
Mathias Agopian65ab4712010-07-14 17:59:35 -07001128status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1129{
1130 status_t status;
1131
Steve Block3856b092011-10-20 11:56:00 +01001132 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133 Mutex::Autolock _l(mLock);
1134
1135 mNewParameters.add(keyValuePairs);
1136 mWaitWorkCV.signal();
1137 // wait condition with timeout in case the thread loop has exited
1138 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001139 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001140 status = mParamStatus;
1141 mWaitWorkCV.signal();
1142 } else {
1143 status = TIMED_OUT;
1144 }
1145 return status;
1146}
1147
1148void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1149{
1150 Mutex::Autolock _l(mLock);
1151 sendConfigEvent_l(event, param);
1152}
1153
1154// sendConfigEvent_l() must be called with ThreadBase::mLock held
1155void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1156{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001157 ConfigEvent configEvent;
1158 configEvent.mEvent = event;
1159 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001160 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001161 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001162 mWaitWorkCV.signal();
1163}
1164
1165void AudioFlinger::ThreadBase::processConfigEvents()
1166{
1167 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001168 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001169 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001170 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001171 mConfigEvents.removeAt(0);
1172 // release mLock before locking AudioFlinger mLock: lock order is always
1173 // AudioFlinger then ThreadBase to avoid cross deadlock
1174 mLock.unlock();
1175 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001176 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001177 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001178 mLock.lock();
1179 }
1180 mLock.unlock();
1181}
1182
1183status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1184{
1185 const size_t SIZE = 256;
1186 char buffer[SIZE];
1187 String8 result;
1188
1189 bool locked = tryLock(mLock);
1190 if (!locked) {
1191 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1192 write(fd, buffer, strlen(buffer));
1193 }
1194
Eric Laurent612bbb52012-03-14 15:03:26 -07001195 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1196 result.append(buffer);
1197 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1198 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001199 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1200 result.append(buffer);
1201 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1202 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001203 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1204 result.append(buffer);
1205 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001206 result.append(buffer);
1207 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1208 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001209 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1210 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001211 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1212 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001213 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001214 result.append(buffer);
1215
1216 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1217 result.append(buffer);
1218 result.append(" Index Command");
1219 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1220 snprintf(buffer, SIZE, "\n %02d ", i);
1221 result.append(buffer);
1222 result.append(mNewParameters[i]);
1223 }
1224
1225 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1226 result.append(buffer);
1227 snprintf(buffer, SIZE, " Index event param\n");
1228 result.append(buffer);
1229 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001230 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001231 result.append(buffer);
1232 }
1233 result.append("\n");
1234
1235 write(fd, result.string(), result.size());
1236
1237 if (locked) {
1238 mLock.unlock();
1239 }
1240 return NO_ERROR;
1241}
1242
Eric Laurent1d2bff02011-07-24 17:49:51 -07001243status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1244{
1245 const size_t SIZE = 256;
1246 char buffer[SIZE];
1247 String8 result;
1248
1249 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1250 write(fd, buffer, strlen(buffer));
1251
1252 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1253 sp<EffectChain> chain = mEffectChains[i];
1254 if (chain != 0) {
1255 chain->dump(fd, args);
1256 }
1257 }
1258 return NO_ERROR;
1259}
1260
Eric Laurentfeb0db62011-07-22 09:04:31 -07001261void AudioFlinger::ThreadBase::acquireWakeLock()
1262{
1263 Mutex::Autolock _l(mLock);
1264 acquireWakeLock_l();
1265}
1266
1267void AudioFlinger::ThreadBase::acquireWakeLock_l()
1268{
1269 if (mPowerManager == 0) {
1270 // use checkService() to avoid blocking if power service is not up yet
1271 sp<IBinder> binder =
1272 defaultServiceManager()->checkService(String16("power"));
1273 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001274 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001275 } else {
1276 mPowerManager = interface_cast<IPowerManager>(binder);
1277 binder->linkToDeath(mDeathRecipient);
1278 }
1279 }
1280 if (mPowerManager != 0) {
1281 sp<IBinder> binder = new BBinder();
1282 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1283 binder,
1284 String16(mName));
1285 if (status == NO_ERROR) {
1286 mWakeLockToken = binder;
1287 }
Steve Block3856b092011-10-20 11:56:00 +01001288 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001289 }
1290}
1291
1292void AudioFlinger::ThreadBase::releaseWakeLock()
1293{
1294 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001295 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001296}
1297
1298void AudioFlinger::ThreadBase::releaseWakeLock_l()
1299{
1300 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001301 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001302 if (mPowerManager != 0) {
1303 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1304 }
1305 mWakeLockToken.clear();
1306 }
1307}
1308
1309void AudioFlinger::ThreadBase::clearPowerManager()
1310{
1311 Mutex::Autolock _l(mLock);
1312 releaseWakeLock_l();
1313 mPowerManager.clear();
1314}
1315
1316void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1317{
1318 sp<ThreadBase> thread = mThread.promote();
1319 if (thread != 0) {
1320 thread->clearPowerManager();
1321 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001322 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001323}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001324
Eric Laurent59255e42011-07-27 19:49:51 -07001325void AudioFlinger::ThreadBase::setEffectSuspended(
1326 const effect_uuid_t *type, bool suspend, int sessionId)
1327{
1328 Mutex::Autolock _l(mLock);
1329 setEffectSuspended_l(type, suspend, sessionId);
1330}
1331
1332void AudioFlinger::ThreadBase::setEffectSuspended_l(
1333 const effect_uuid_t *type, bool suspend, int sessionId)
1334{
Glenn Kasten090f0192012-01-30 13:00:02 -08001335 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001336 if (chain != 0) {
1337 if (type != NULL) {
1338 chain->setEffectSuspended_l(type, suspend);
1339 } else {
1340 chain->setEffectSuspendedAll_l(suspend);
1341 }
1342 }
1343
1344 updateSuspendedSessions_l(type, suspend, sessionId);
1345}
1346
1347void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1348{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001349 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001350 if (index < 0) {
1351 return;
1352 }
1353
1354 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1355 mSuspendedSessions.editValueAt(index);
1356
1357 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001358 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001359 for (int j = 0; j < desc->mRefCount; j++) {
1360 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1361 chain->setEffectSuspendedAll_l(true);
1362 } else {
Steve Block3856b092011-10-20 11:56:00 +01001363 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001364 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001365 chain->setEffectSuspended_l(&desc->mType, true);
1366 }
1367 }
1368 }
1369}
1370
Eric Laurent59255e42011-07-27 19:49:51 -07001371void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1372 bool suspend,
1373 int sessionId)
1374{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001375 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001376
1377 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1378
1379 if (suspend) {
1380 if (index >= 0) {
1381 sessionEffects = mSuspendedSessions.editValueAt(index);
1382 } else {
1383 mSuspendedSessions.add(sessionId, sessionEffects);
1384 }
1385 } else {
1386 if (index < 0) {
1387 return;
1388 }
1389 sessionEffects = mSuspendedSessions.editValueAt(index);
1390 }
1391
1392
1393 int key = EffectChain::kKeyForSuspendAll;
1394 if (type != NULL) {
1395 key = type->timeLow;
1396 }
1397 index = sessionEffects.indexOfKey(key);
1398
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001399 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001400 if (suspend) {
1401 if (index >= 0) {
1402 desc = sessionEffects.valueAt(index);
1403 } else {
1404 desc = new SuspendedSessionDesc();
1405 if (type != NULL) {
1406 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1407 }
1408 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001409 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001410 }
1411 desc->mRefCount++;
1412 } else {
1413 if (index < 0) {
1414 return;
1415 }
1416 desc = sessionEffects.valueAt(index);
1417 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001418 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001419 sessionEffects.removeItemsAt(index);
1420 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001421 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001422 sessionId);
1423 mSuspendedSessions.removeItem(sessionId);
1424 }
1425 }
1426 }
1427 if (!sessionEffects.isEmpty()) {
1428 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1429 }
1430}
1431
1432void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1433 bool enabled,
1434 int sessionId)
1435{
1436 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001437 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1438}
Eric Laurent59255e42011-07-27 19:49:51 -07001439
Eric Laurenta85a74a2011-10-19 11:44:54 -07001440void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1441 bool enabled,
1442 int sessionId)
1443{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001444 if (mType != RECORD) {
1445 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1446 // another session. This gives the priority to well behaved effect control panels
1447 // and applications not using global effects.
1448 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1449 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1450 }
1451 }
Eric Laurent59255e42011-07-27 19:49:51 -07001452
1453 sp<EffectChain> chain = getEffectChain_l(sessionId);
1454 if (chain != 0) {
1455 chain->checkSuspendOnEffectEnabled(effect, enabled);
1456 }
1457}
1458
Mathias Agopian65ab4712010-07-14 17:59:35 -07001459// ----------------------------------------------------------------------------
1460
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001461AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1462 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001463 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001464 uint32_t device,
1465 type_t type)
1466 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001467 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1468 // Assumes constructor is called by AudioFlinger with it's mLock held,
1469 // but it would be safer to explicitly pass initial masterMute as parameter
1470 mMasterMute(audioFlinger->masterMute_l()),
1471 // mStreamTypes[] initialized in constructor body
1472 mOutput(output),
1473 // Assumes constructor is called by AudioFlinger with it's mLock held,
1474 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001475 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001476 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001477 mMixerStatus(MIXER_IDLE),
Glenn Kasten66fcab92012-02-24 14:59:21 -08001478 mPrevMixerStatus(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001479 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
1480 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1481 mFastTrackNewMask(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001482{
Glenn Kasten58912562012-04-03 10:45:00 -07001483#if !LOG_NDEBUG
1484 memset(mFastTrackNewArray, 0, sizeof(mFastTrackNewArray));
1485#endif
Glenn Kasten480b4682012-02-28 12:30:08 -08001486 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001487
Mathias Agopian65ab4712010-07-14 17:59:35 -07001488 readOutputParameters();
1489
Glenn Kasten263709e2012-01-06 08:40:01 -08001490 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001491 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1492 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1493 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001494 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1495 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001496 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001497 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1498 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499}
1500
1501AudioFlinger::PlaybackThread::~PlaybackThread()
1502{
1503 delete [] mMixBuffer;
1504}
1505
1506status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1507{
1508 dumpInternals(fd, args);
1509 dumpTracks(fd, args);
1510 dumpEffectChains(fd, args);
1511 return NO_ERROR;
1512}
1513
1514status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1515{
1516 const size_t SIZE = 256;
1517 char buffer[SIZE];
1518 String8 result;
1519
Glenn Kasten58912562012-04-03 10:45:00 -07001520 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1521 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1522 const stream_type_t *st = &mStreamTypes[i];
1523 if (i > 0) {
1524 result.appendFormat(", ");
1525 }
1526 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1527 if (st->mute) {
1528 result.append("M");
1529 }
1530 }
1531 result.append("\n");
1532 write(fd, result.string(), result.length());
1533 result.clear();
1534
Mathias Agopian65ab4712010-07-14 17:59:35 -07001535 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1536 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001537 result.append(" Name Client Type Fmt Chn mask Session Frames S M F SRate L dB R dB "
1538 "Server User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001539 for (size_t i = 0; i < mTracks.size(); ++i) {
1540 sp<Track> track = mTracks[i];
1541 if (track != 0) {
1542 track->dump(buffer, SIZE);
1543 result.append(buffer);
1544 }
1545 }
1546
1547 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1548 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001549 result.append(" Name Client Type Fmt Chn mask Session Frames S M F SRate L dB R dB "
1550 "Server User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001551 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001552 sp<Track> track = mActiveTracks[i].promote();
1553 if (track != 0) {
1554 track->dump(buffer, SIZE);
1555 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001556 }
1557 }
1558 write(fd, result.string(), result.size());
1559 return NO_ERROR;
1560}
1561
Mathias Agopian65ab4712010-07-14 17:59:35 -07001562status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1563{
1564 const size_t SIZE = 256;
1565 char buffer[SIZE];
1566 String8 result;
1567
1568 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1569 result.append(buffer);
1570 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1571 result.append(buffer);
1572 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1573 result.append(buffer);
1574 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1575 result.append(buffer);
1576 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1577 result.append(buffer);
1578 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1579 result.append(buffer);
1580 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1581 result.append(buffer);
1582 write(fd, result.string(), result.size());
1583
1584 dumpBase(fd, args);
1585
1586 return NO_ERROR;
1587}
1588
1589// Thread virtuals
1590status_t AudioFlinger::PlaybackThread::readyToRun()
1591{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001592 status_t status = initCheck();
1593 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001594 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001595 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001596 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001597 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001598 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001599}
1600
1601void AudioFlinger::PlaybackThread::onFirstRef()
1602{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001603 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001604}
1605
1606// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001607sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001608 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001609 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001611 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001612 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001613 int frameCount,
1614 const sp<IMemory>& sharedBuffer,
1615 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001616 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001617 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001618 status_t *status)
1619{
1620 sp<Track> track;
1621 status_t lStatus;
1622
Glenn Kasten73d22752012-03-19 13:38:30 -07001623 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1624
1625 // client expresses a preference for FAST, but we get the final say
1626 if ((flags & IAudioFlinger::TRACK_FAST) &&
1627 !(
1628 // not timed
1629 (!isTimed) &&
1630 // either of these use cases:
1631 (
1632 // use case 1: shared buffer with any frame count
1633 (
1634 (sharedBuffer != 0)
1635 ) ||
Glenn Kasten58912562012-04-03 10:45:00 -07001636 // use case 2: callback handler and frame count at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001637 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001638 (tid != -1) &&
Glenn Kasten73d22752012-03-19 13:38:30 -07001639 // FIXME supported frame counts should not be hard-coded
Glenn Kasten58912562012-04-03 10:45:00 -07001640 frameCount >= (int) mFrameCount // FIXME int cast is due to wrong parameter type
Glenn Kasten73d22752012-03-19 13:38:30 -07001641 )
1642 ) &&
1643 // PCM data
1644 audio_is_linear_pcm(format) &&
1645 // mono or stereo
1646 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1647 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001648#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001649 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001650 (sampleRate == mSampleRate) &&
1651#endif
1652 // normal mixer has an associated fast mixer
1653 hasFastMixer() &&
1654 // there are sufficient fast track slots available
1655 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001656 // FIXME test that MixerThread for this fast track has a capable output HAL
1657 // FIXME add a permission test also?
1658 ) ) {
Glenn Kasten58912562012-04-03 10:45:00 -07001659 ALOGW("AUDIO_POLICY_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
1660 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1661 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1662 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1663 audio_is_linear_pcm(format),
1664 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001665 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kasten58912562012-04-03 10:45:00 -07001666 if (0 < frameCount && frameCount < (int) mNormalFrameCount) {
1667 frameCount = mNormalFrameCount;
1668 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001669 }
1670
Mathias Agopian65ab4712010-07-14 17:59:35 -07001671 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001672 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1673 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001674 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001675 "for output %p with format %d",
1676 sampleRate, format, channelMask, mOutput, mFormat);
1677 lStatus = BAD_VALUE;
1678 goto Exit;
1679 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001680 }
1681 } else {
1682 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1683 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001684 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685 lStatus = BAD_VALUE;
1686 goto Exit;
1687 }
1688 }
1689
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001690 lStatus = initCheck();
1691 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001692 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001693 goto Exit;
1694 }
1695
1696 { // scope for mLock
1697 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001698
1699 // all tracks in same audio session must share the same routing strategy otherwise
1700 // conflicts will happen when tracks are moved from one output to another by audio policy
1701 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001702 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001703 for (size_t i = 0; i < mTracks.size(); ++i) {
1704 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001705 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001706 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001707 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001708 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001709 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001710 lStatus = BAD_VALUE;
1711 goto Exit;
1712 }
1713 }
1714 }
1715
John Grossman4ff14ba2012-02-08 16:37:41 -08001716 if (!isTimed) {
1717 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001718 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001719 } else {
1720 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1721 channelMask, frameCount, sharedBuffer, sessionId);
1722 }
1723 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001724 lStatus = NO_MEMORY;
1725 goto Exit;
1726 }
1727 mTracks.add(track);
1728
1729 sp<EffectChain> chain = getEffectChain_l(sessionId);
1730 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001731 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001732 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001733 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001734 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001735 }
1736 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001737
1738#ifdef HAVE_REQUEST_PRIORITY
1739 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1740 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1741 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1742 // so ask activity manager to do this on our behalf
1743 int err = requestPriority(callingPid, tid, 1);
1744 if (err != 0) {
1745 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1746 1, callingPid, tid, err);
1747 }
1748 }
1749#endif
1750
Mathias Agopian65ab4712010-07-14 17:59:35 -07001751 lStatus = NO_ERROR;
1752
1753Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001754 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001755 *status = lStatus;
1756 }
1757 return track;
1758}
1759
1760uint32_t AudioFlinger::PlaybackThread::latency() const
1761{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001762 Mutex::Autolock _l(mLock);
1763 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001764 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001765 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001766 return 0;
1767 }
1768}
1769
Glenn Kasten6637baa2012-01-09 09:40:36 -08001770void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001771{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001772 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001774}
1775
Glenn Kasten6637baa2012-01-09 09:40:36 -08001776void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001777{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001778 Mutex::Autolock _l(mLock);
1779 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001780}
1781
Glenn Kasten6637baa2012-01-09 09:40:36 -08001782void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001783{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001784 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001785 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786}
1787
Glenn Kasten6637baa2012-01-09 09:40:36 -08001788void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001789{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001790 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001791 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001792}
1793
Glenn Kastenfff6d712012-01-12 16:38:12 -08001794float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001795{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001796 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001797 return mStreamTypes[stream].volume;
1798}
1799
Mathias Agopian65ab4712010-07-14 17:59:35 -07001800// addTrack_l() must be called with ThreadBase::mLock held
1801status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1802{
1803 status_t status = ALREADY_EXISTS;
1804
1805 // set retry count for buffer fill
1806 track->mRetryCount = kMaxTrackStartupRetries;
1807 if (mActiveTracks.indexOf(track) < 0) {
1808 // the track is newly added, make sure it fills up all its
1809 // buffers before playing. This is to ensure the client will
1810 // effectively get the latency it requested.
1811 track->mFillingUpStatus = Track::FS_FILLING;
1812 track->mResetDone = false;
1813 mActiveTracks.add(track);
1814 if (track->mainBuffer() != mMixBuffer) {
1815 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1816 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001817 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001818 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001819 }
1820 }
1821
1822 status = NO_ERROR;
1823 }
1824
Steve Block3856b092011-10-20 11:56:00 +01001825 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001826 mWaitWorkCV.broadcast();
1827
1828 return status;
1829}
1830
1831// destroyTrack_l() must be called with ThreadBase::mLock held
1832void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1833{
1834 track->mState = TrackBase::TERMINATED;
1835 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001836 removeTrack_l(track);
1837 }
1838}
1839
1840void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1841{
1842 mTracks.remove(track);
1843 deleteTrackName_l(track->name());
1844 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1845 if (chain != 0) {
1846 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001847 }
1848}
1849
1850String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1851{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001852 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001853 char *s;
1854
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001855 Mutex::Autolock _l(mLock);
1856 if (initCheck() != NO_ERROR) {
1857 return out_s8;
1858 }
1859
Dima Zavin799a70e2011-04-18 16:57:27 -07001860 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001861 out_s8 = String8(s);
1862 free(s);
1863 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864}
1865
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001866// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001867void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1868 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001869 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001870
Steve Block3856b092011-10-20 11:56:00 +01001871 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001872
1873 switch (event) {
1874 case AudioSystem::OUTPUT_OPENED:
1875 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001876 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001877 desc.samplingRate = mSampleRate;
1878 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001879 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001880 desc.latency = latency();
1881 param2 = &desc;
1882 break;
1883
1884 case AudioSystem::STREAM_CONFIG_CHANGED:
1885 param2 = &param;
1886 case AudioSystem::OUTPUT_CLOSED:
1887 default:
1888 break;
1889 }
1890 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1891}
1892
1893void AudioFlinger::PlaybackThread::readOutputParameters()
1894{
Dima Zavin799a70e2011-04-18 16:57:27 -07001895 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001896 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1897 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001898 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001899 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001900 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001901 if (mFrameCount & 15) {
1902 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1903 mFrameCount);
1904 }
1905
1906 // Calculate size of normal mix buffer
1907 if (mType == MIXER) {
1908 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1909 mNormalFrameCount = ((minNormalFrameCount + mFrameCount - 1) / mFrameCount) * mFrameCount;
1910 if (mNormalFrameCount & 15) {
1911 ALOGW("Normal mix buffer size is %u frames but AudioMixer requires multiples of 16 "
1912 "frames", mNormalFrameCount);
1913 }
1914 } else {
1915 mNormalFrameCount = mFrameCount;
1916 }
1917 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918
1919 // FIXME - Current mixer implementation only supports stereo output: Always
1920 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001921 delete[] mMixBuffer;
Glenn Kasten58912562012-04-03 10:45:00 -07001922 mMixBuffer = new int16_t[mNormalFrameCount * 2];
1923 memset(mMixBuffer, 0, mNormalFrameCount * 2 * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001924
Eric Laurentde070132010-07-13 04:45:46 -07001925 // force reconfiguration of effect chains and engines to take new buffer size and audio
1926 // parameters into account
1927 // Note that mLock is not held when readOutputParameters() is called from the constructor
1928 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1929 // matter.
1930 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1931 Vector< sp<EffectChain> > effectChains = mEffectChains;
1932 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001933 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001934 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001935}
1936
1937status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1938{
Glenn Kastena0d68332012-01-27 16:47:15 -08001939 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001940 return BAD_VALUE;
1941 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001942 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001943 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001944 return INVALID_OPERATION;
1945 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001946 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001947
Dima Zavin799a70e2011-04-18 16:57:27 -07001948 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949}
1950
Eric Laurent39e94f82010-07-28 01:32:47 -07001951uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001952{
1953 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001954 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001955 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001956 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001957 }
1958
1959 for (size_t i = 0; i < mTracks.size(); ++i) {
1960 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001961 if (sessionId == track->sessionId() &&
1962 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001963 result |= TRACK_SESSION;
1964 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001965 }
1966 }
1967
Eric Laurent39e94f82010-07-28 01:32:47 -07001968 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001969}
1970
Eric Laurentde070132010-07-13 04:45:46 -07001971uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1972{
Dima Zavinfce7a472011-04-19 22:30:36 -07001973 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001974 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001975 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1976 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001977 }
1978 for (size_t i = 0; i < mTracks.size(); i++) {
1979 sp<Track> track = mTracks[i];
1980 if (sessionId == track->sessionId() &&
1981 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001982 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001983 }
1984 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001985 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001986}
1987
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988
Glenn Kastenaed850d2012-01-26 09:46:34 -08001989AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001990{
1991 Mutex::Autolock _l(mLock);
1992 return mOutput;
1993}
1994
1995AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1996{
1997 Mutex::Autolock _l(mLock);
1998 AudioStreamOut *output = mOutput;
1999 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002000 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2001 // must push a NULL and wait for ack
2002 mOutputSink.clear();
2003 mPipeSink.clear();
2004 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002005 return output;
2006}
2007
2008// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002009audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002010{
2011 if (mOutput == NULL) {
2012 return NULL;
2013 }
2014 return &mOutput->stream->common;
2015}
2016
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002017uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002018{
2019 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
2020 // decoding and transfer time. So sleeping for half of the latency would likely cause
2021 // underruns
2022 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002023 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002024 } else {
2025 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
2026 }
2027}
2028
Eric Laurenta011e352012-03-29 15:51:43 -07002029status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2030{
2031 if (!isValidSyncEvent(event)) {
2032 return BAD_VALUE;
2033 }
2034
2035 Mutex::Autolock _l(mLock);
2036
2037 for (size_t i = 0; i < mTracks.size(); ++i) {
2038 sp<Track> track = mTracks[i];
2039 if (event->triggerSession() == track->sessionId()) {
2040 track->setSyncEvent(event);
2041 return NO_ERROR;
2042 }
2043 }
2044
2045 return NAME_NOT_FOUND;
2046}
2047
2048bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2049{
2050 switch (event->type()) {
2051 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2052 return true;
2053 default:
2054 break;
2055 }
2056 return false;
2057}
2058
Mathias Agopian65ab4712010-07-14 17:59:35 -07002059// ----------------------------------------------------------------------------
2060
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002061AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002062 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002063 : PlaybackThread(audioFlinger, output, id, device, type),
2064 // mAudioMixer below
2065#ifdef SOAKER
2066 mSoaker(NULL),
2067#endif
2068 // mFastMixer below
2069 mFastMixerFutex(0)
2070 // mOutputSink below
2071 // mPipeSink below
2072 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002073{
Glenn Kasten58912562012-04-03 10:45:00 -07002074 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2075 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2076 "mFrameCount=%d, mNormalFrameCount=%d",
2077 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2078 mNormalFrameCount);
2079 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2080
Mathias Agopian65ab4712010-07-14 17:59:35 -07002081 // FIXME - Current mixer implementation only supports stereo output
2082 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002083 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002084 }
Glenn Kasten58912562012-04-03 10:45:00 -07002085
2086 // create an NBAIO sink for the HAL output stream, and negotiate
2087 mOutputSink = new AudioStreamOutSink(output->stream);
2088 size_t numCounterOffers = 0;
2089 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2090 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2091 ALOG_ASSERT(index == 0);
2092
2093 // initialize fast mixer if needed
2094 if (mFrameCount < mNormalFrameCount) {
2095
2096 // create a MonoPipe to connect our submix to FastMixer
2097 NBAIO_Format format = mOutputSink->format();
2098 // frame count will be rounded up to a power of 2, so this formula should work well
2099 MonoPipe *monoPipe = new MonoPipe((mNormalFrameCount * 3) / 2, format,
2100 true /*writeCanBlock*/);
2101 const NBAIO_Format offers[1] = {format};
2102 size_t numCounterOffers = 0;
2103 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2104 ALOG_ASSERT(index == 0);
2105 mPipeSink = monoPipe;
2106
2107#ifdef SOAKER
2108 // create a soaker as workaround for governor issues
2109 mSoaker = new Soaker();
2110 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE
2111 mSoaker->run("Soaker", PRIORITY_LOWEST);
2112#endif
2113
2114 // create fast mixer and configure it initially with just one fast track for our submix
2115 mFastMixer = new FastMixer();
2116 FastMixerStateQueue *sq = mFastMixer->sq();
2117 FastMixerState *state = sq->begin();
2118 FastTrack *fastTrack = &state->mFastTracks[0];
2119 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2120 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2121 fastTrack->mVolumeProvider = NULL;
2122 fastTrack->mGeneration++;
2123 state->mFastTracksGen++;
2124 state->mTrackMask = 1;
2125 // fast mixer will use the HAL output sink
2126 state->mOutputSink = mOutputSink.get();
2127 state->mOutputSinkGen++;
2128 state->mFrameCount = mFrameCount;
2129 state->mCommand = FastMixerState::COLD_IDLE;
2130 // already done in constructor initialization list
2131 //mFastMixerFutex = 0;
2132 state->mColdFutexAddr = &mFastMixerFutex;
2133 state->mColdGen++;
2134 state->mDumpState = &mFastMixerDumpState;
2135 sq->end();
2136 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2137
2138 // start the fast mixer
2139 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2140#ifdef HAVE_REQUEST_PRIORITY
2141 pid_t tid = mFastMixer->getTid();
2142 int err = requestPriority(getpid_cached, tid, 2);
2143 if (err != 0) {
2144 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2145 2, getpid_cached, tid, err);
2146 }
2147#endif
2148
2149 } else {
2150 mFastMixer = NULL;
2151 }
2152 mNormalSink = mOutputSink;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002153}
2154
2155AudioFlinger::MixerThread::~MixerThread()
2156{
Glenn Kasten58912562012-04-03 10:45:00 -07002157 if (mFastMixer != NULL) {
2158 FastMixerStateQueue *sq = mFastMixer->sq();
2159 FastMixerState *state = sq->begin();
2160 if (state->mCommand == FastMixerState::COLD_IDLE) {
2161 int32_t old = android_atomic_inc(&mFastMixerFutex);
2162 if (old == -1) {
2163 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2164 }
2165 }
2166 state->mCommand = FastMixerState::EXIT;
2167 sq->end();
2168 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2169 mFastMixer->join();
2170 // Though the fast mixer thread has exited, it's state queue is still valid.
2171 // We'll use that extract the final state which contains one remaining fast track
2172 // corresponding to our sub-mix.
2173 state = sq->begin();
2174 ALOG_ASSERT(state->mTrackMask == 1);
2175 FastTrack *fastTrack = &state->mFastTracks[0];
2176 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2177 delete fastTrack->mBufferProvider;
2178 sq->end(false /*didModify*/);
2179 delete mFastMixer;
2180#ifdef SOAKER
2181 if (mSoaker != NULL) {
2182 mSoaker->requestExitAndWait();
2183 }
2184 delete mSoaker;
2185#endif
2186 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002187 delete mAudioMixer;
2188}
2189
Glenn Kasten83efdd02012-02-24 07:21:32 -08002190class CpuStats {
2191public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002192 CpuStats();
2193 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002194#ifdef DEBUG_CPU_USAGE
2195private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002196 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2197 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2198
2199 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2200
2201 int mCpuNum; // thread's current CPU number
2202 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002203#endif
2204};
2205
Glenn Kasten190a46f2012-03-06 11:27:10 -08002206CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002207#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002208 : mCpuNum(-1), mCpukHz(-1)
2209#endif
2210{
2211}
2212
2213void CpuStats::sample(const String8 &title) {
2214#ifdef DEBUG_CPU_USAGE
2215 // get current thread's delta CPU time in wall clock ns
2216 double wcNs;
2217 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2218
2219 // record sample for wall clock statistics
2220 if (valid) {
2221 mWcStats.sample(wcNs);
2222 }
2223
2224 // get the current CPU number
2225 int cpuNum = sched_getcpu();
2226
2227 // get the current CPU frequency in kHz
2228 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2229
2230 // check if either CPU number or frequency changed
2231 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2232 mCpuNum = cpuNum;
2233 mCpukHz = cpukHz;
2234 // ignore sample for purposes of cycles
2235 valid = false;
2236 }
2237
2238 // if no change in CPU number or frequency, then record sample for cycle statistics
2239 if (valid && mCpukHz > 0) {
2240 double cycles = wcNs * cpukHz * 0.000001;
2241 mHzStats.sample(cycles);
2242 }
2243
2244 unsigned n = mWcStats.n();
2245 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002246 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002247 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002248 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2249 double perLoop = elapsed / (double) n;
2250 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002251 double perLoop1k = perLoop * 0.001;
2252 double mean = mWcStats.mean();
2253 double stddev = mWcStats.stddev();
2254 double minimum = mWcStats.minimum();
2255 double maximum = mWcStats.maximum();
2256 double meanCycles = mHzStats.mean();
2257 double stddevCycles = mHzStats.stddev();
2258 double minCycles = mHzStats.minimum();
2259 double maxCycles = mHzStats.maximum();
2260 mCpuUsage.resetElapsed();
2261 mWcStats.reset();
2262 mHzStats.reset();
2263 ALOGD("CPU usage for %s over past %.1f secs\n"
2264 " (%u mixer loops at %.1f mean ms per loop):\n"
2265 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2266 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2267 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2268 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002269 elapsed * .000000001, n, perLoop * .000001,
2270 mean * .001,
2271 stddev * .001,
2272 minimum * .001,
2273 maximum * .001,
2274 mean / perLoop100,
2275 stddev / perLoop100,
2276 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002277 maximum / perLoop100,
2278 meanCycles / perLoop1k,
2279 stddevCycles / perLoop1k,
2280 minCycles / perLoop1k,
2281 maxCycles / perLoop1k);
2282
Glenn Kasten83efdd02012-02-24 07:21:32 -08002283 }
2284 }
2285#endif
2286};
2287
Glenn Kasten37d825e2012-02-24 07:21:48 -08002288void AudioFlinger::PlaybackThread::checkSilentMode_l()
2289{
2290 if (!mMasterMute) {
2291 char value[PROPERTY_VALUE_MAX];
2292 if (property_get("ro.audio.silent", value, "0") > 0) {
2293 char *endptr;
2294 unsigned long ul = strtoul(value, &endptr, 0);
2295 if (*endptr == '\0' && ul != 0) {
2296 ALOGD("Silence is golden");
2297 // The setprop command will not allow a property to be changed after
2298 // the first time it is set, so we don't have to worry about un-muting.
2299 setMasterMute_l(true);
2300 }
2301 }
2302 }
2303}
2304
Glenn Kasten000f0e32012-03-01 17:10:56 -08002305bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002306{
2307 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002308
Glenn Kasten000f0e32012-03-01 17:10:56 -08002309 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002310
2311 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002312 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002313if (mType == MIXER) {
2314 longStandbyExit = false;
2315}
Glenn Kasten688a6402012-02-29 07:57:06 -08002316
Glenn Kasten000f0e32012-03-01 17:10:56 -08002317 // DUPLICATING
2318 // FIXME could this be made local to while loop?
2319 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002320
Glenn Kasten66fcab92012-02-24 14:59:21 -08002321 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002322 sleepTime = idleSleepTime;
2323
2324if (mType == MIXER) {
2325 sleepTimeShift = 0;
2326}
2327
Glenn Kasten83efdd02012-02-24 07:21:32 -08002328 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002329 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002330
Eric Laurentfeb0db62011-07-22 09:04:31 -07002331 acquireWakeLock();
2332
Mathias Agopian65ab4712010-07-14 17:59:35 -07002333 while (!exitPending())
2334 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002335 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002336
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002337 Vector< sp<EffectChain> > effectChains;
2338
Mathias Agopian65ab4712010-07-14 17:59:35 -07002339 processConfigEvents();
2340
Mathias Agopian65ab4712010-07-14 17:59:35 -07002341 { // scope for mLock
2342
2343 Mutex::Autolock _l(mLock);
2344
2345 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002346 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002347 }
2348
Glenn Kastenfa26a852012-03-06 11:28:04 -08002349 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002350
Mathias Agopian65ab4712010-07-14 17:59:35 -07002351 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002352 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002353 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002354 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002355
2356 threadLoop_standby();
2357
Mathias Agopian65ab4712010-07-14 17:59:35 -07002358 mStandby = true;
2359 mBytesWritten = 0;
2360 }
2361
Glenn Kasten3e074702012-02-28 18:40:35 -08002362 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002363 // we're about to wait, flush the binder command buffer
2364 IPCThreadState::self()->flushCommands();
2365
Glenn Kastenfa26a852012-03-06 11:28:04 -08002366 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002367
Mathias Agopian65ab4712010-07-14 17:59:35 -07002368 if (exitPending()) break;
2369
Eric Laurentfeb0db62011-07-22 09:04:31 -07002370 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002371 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002372 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002373 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002374 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002375 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002376
Eric Laurent27741442012-01-17 19:20:12 -08002377 mPrevMixerStatus = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002378
Glenn Kasten37d825e2012-02-24 07:21:48 -08002379 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002380
Glenn Kasten000f0e32012-03-01 17:10:56 -08002381 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002382 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002383 if (mType == MIXER) {
2384 sleepTimeShift = 0;
2385 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002386
Mathias Agopian65ab4712010-07-14 17:59:35 -07002387 continue;
2388 }
2389 }
2390
Glenn Kastenfec279f2012-03-08 07:47:15 -08002391 mixer_state newMixerStatus = prepareTracks_l(&tracksToRemove);
2392 // Shift in the new status; this could be a queue if it's
2393 // useful to filter the mixer status over several cycles.
2394 mPrevMixerStatus = mMixerStatus;
2395 mMixerStatus = newMixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002396
2397 // prevent any changes in effect chain list and in each effect chain
2398 // during mixing and effect process as the audio buffers could be deleted
2399 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002400 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002401 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002402
Glenn Kastenfec279f2012-03-08 07:47:15 -08002403 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002404 threadLoop_mix();
2405 } else {
2406 threadLoop_sleepTime();
2407 }
2408
2409 if (mSuspended > 0) {
2410 sleepTime = suspendSleepTimeUs();
2411 }
2412
2413 // only process effects if we're going to write
2414 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002415 for (size_t i = 0; i < effectChains.size(); i ++) {
2416 effectChains[i]->process_l();
2417 }
2418 }
2419
2420 // enable changes in effect chain
2421 unlockEffectChains(effectChains);
2422
2423 // sleepTime == 0 means we must write to audio hardware
2424 if (sleepTime == 0) {
2425
2426 threadLoop_write();
2427
2428if (mType == MIXER) {
2429 // write blocked detection
2430 nsecs_t now = systemTime();
2431 nsecs_t delta = now - mLastWriteTime;
2432 if (!mStandby && delta > maxPeriod) {
2433 mNumDelayedWrites++;
2434 if ((now - lastWarning) > kWarningThrottleNs) {
2435 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2436 ns2ms(delta), mNumDelayedWrites, this);
2437 lastWarning = now;
2438 }
2439 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2440 // a different threshold. Or completely removed for what it is worth anyway...
2441 if (mStandby) {
2442 longStandbyExit = true;
2443 }
2444 }
2445}
2446
2447 mStandby = false;
2448 } else {
2449 usleep(sleepTime);
2450 }
2451
Glenn Kasten58912562012-04-03 10:45:00 -07002452 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002453 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002454 // same lock. This will also mutate and push a new fast mixer state.
2455 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002456 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002457
Glenn Kastenfa26a852012-03-06 11:28:04 -08002458 // FIXME I don't understand the need for this here;
2459 // it was in the original code but maybe the
2460 // assignment in saveOutputTracks() makes this unnecessary?
2461 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002462
2463 // Effect chains will be actually deleted here if they were removed from
2464 // mEffectChains list during mixing or effects processing
2465 effectChains.clear();
2466
2467 // FIXME Note that the above .clear() is no longer necessary since effectChains
2468 // is now local to this block, but will keep it for now (at least until merge done).
2469 }
2470
2471if (mType == MIXER || mType == DIRECT) {
2472 // put output stream into standby mode
2473 if (!mStandby) {
2474 mOutput->stream->common.standby(&mOutput->stream->common);
2475 }
2476}
2477if (mType == DUPLICATING) {
2478 // for DuplicatingThread, standby mode is handled by the outputTracks
2479}
2480
2481 releaseWakeLock();
2482
2483 ALOGV("Thread %p type %d exiting", this, mType);
2484 return false;
2485}
2486
Glenn Kasten58912562012-04-03 10:45:00 -07002487// FIXME This method needs a better name.
2488// It pushes a new fast mixer state and returns (via tracksToRemove) a set of tracks to remove.
2489void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2490{
2491 // were any of the removed tracks also fast tracks?
2492 unsigned removedMask = 0;
2493 for (size_t i = 0; i < tracksToRemove.size(); ++i) {
2494 if (tracksToRemove[i]->isFastTrack()) {
2495 int j = tracksToRemove[i]->mFastIndex;
2496 ALOG_ASSERT(0 < j && j < FastMixerState::kMaxFastTracks);
2497 removedMask |= 1 << j;
2498 }
2499 }
2500 Track* newArray[FastMixerState::kMaxFastTracks];
2501 unsigned newMask;
2502 {
2503 AutoMutex _l(mLock);
2504 mFastTrackAvailMask |= removedMask;
2505 newMask = mFastTrackNewMask;
2506 if (newMask) {
2507 mFastTrackNewMask = 0;
2508 memcpy(newArray, mFastTrackNewArray, sizeof(mFastTrackNewArray));
2509#if !LOG_NDEBUG
2510 memset(mFastTrackNewArray, 0, sizeof(mFastTrackNewArray));
2511#endif
2512 }
2513 }
2514 unsigned changedMask = newMask | removedMask;
2515 // are there any newly added or removed fast tracks?
2516 if (changedMask) {
2517
2518 // This assert would be incorrect because it's theoretically possible (though unlikely)
2519 // for a track to be created and then removed within the same normal mix cycle:
2520 // ALOG_ASSERT(!(newMask & removedMask));
2521 // The converse, of removing a track and then creating a new track at the identical slot
2522 // within the same normal mix cycle, is impossible because the slot isn't marked available.
2523
2524 // prepare a new state to push
2525 FastMixerStateQueue *sq = mFastMixer->sq();
2526 FastMixerState *state = sq->begin();
2527 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2528 while (changedMask) {
2529 int j = __builtin_ctz(changedMask);
2530 ALOG_ASSERT(0 < j && j < FastMixerState::kMaxFastTracks);
2531 changedMask &= ~(1 << j);
2532 FastTrack *fastTrack = &state->mFastTracks[j];
2533 // must first do new tracks, then removed tracks, in case same track in both
2534 if (newMask & (1 << j)) {
2535 ALOG_ASSERT(!(state->mTrackMask & (1 << j)));
2536 ALOG_ASSERT(fastTrack->mBufferProvider == NULL &&
2537 fastTrack->mVolumeProvider == NULL);
2538 Track *track = newArray[j];
2539 AudioBufferProvider *abp = track;
2540 VolumeProvider *vp = track;
2541 fastTrack->mBufferProvider = abp;
2542 fastTrack->mVolumeProvider = vp;
2543 fastTrack->mSampleRate = track->mSampleRate;
2544 fastTrack->mChannelMask = track->mChannelMask;
2545 state->mTrackMask |= 1 << j;
2546 }
2547 if (removedMask & (1 << j)) {
2548 ALOG_ASSERT(state->mTrackMask & (1 << j));
2549 ALOG_ASSERT(fastTrack->mBufferProvider != NULL &&
2550 fastTrack->mVolumeProvider != NULL);
2551 fastTrack->mBufferProvider = NULL;
2552 fastTrack->mVolumeProvider = NULL;
2553 fastTrack->mSampleRate = mSampleRate;
2554 fastTrack->mChannelMask = AUDIO_CHANNEL_OUT_STEREO;
2555 state->mTrackMask &= ~(1 << j);
2556 }
2557 fastTrack->mGeneration++;
2558 }
2559 state->mFastTracksGen++;
2560 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
2561 if (state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
2562 state->mCommand = FastMixerState::COLD_IDLE;
2563 state->mColdFutexAddr = &mFastMixerFutex;
2564 state->mColdGen++;
2565 mFastMixerFutex = 0;
2566 mNormalSink = mOutputSink;
2567 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2568 }
2569 sq->end();
2570 // If any fast tracks were removed, we must wait for acknowledgement
2571 // because we're about to decrement the last sp<> on those tracks.
2572 // Similarly if we put it into cold idle, need to wait for acknowledgement
2573 // so that it stops doing I/O.
2574 if (removedMask) {
2575 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2576 }
2577 sq->push(block);
2578 }
2579 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2580}
2581
2582void AudioFlinger::MixerThread::threadLoop_write()
2583{
2584 // FIXME we should only do one push per cycle; confirm this is true
2585 // Start the fast mixer if it's not already running
2586 if (mFastMixer != NULL) {
2587 FastMixerStateQueue *sq = mFastMixer->sq();
2588 FastMixerState *state = sq->begin();
2589 if (state->mCommand != FastMixerState::MIX_WRITE && state->mTrackMask > 1) {
2590 if (state->mCommand == FastMixerState::COLD_IDLE) {
2591 int32_t old = android_atomic_inc(&mFastMixerFutex);
2592 if (old == -1) {
2593 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2594 }
2595 }
2596 state->mCommand = FastMixerState::MIX_WRITE;
2597 sq->end();
2598 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2599 mNormalSink = mPipeSink;
2600 } else {
2601 sq->end(false /*didModify*/);
2602 }
2603 }
2604 PlaybackThread::threadLoop_write();
2605}
2606
Glenn Kasten000f0e32012-03-01 17:10:56 -08002607// shared by MIXER and DIRECT, overridden by DUPLICATING
2608void AudioFlinger::PlaybackThread::threadLoop_write()
2609{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002610 // FIXME rewrite to reduce number of system calls
2611 mLastWriteTime = systemTime();
2612 mInWrite = true;
Glenn Kasten58912562012-04-03 10:45:00 -07002613 int bytesWritten;
2614
2615 // If an NBAIO sink is present, use it to write the normal mixer's submix
2616 if (mNormalSink != 0) {
2617#define mBitShift 2 // FIXME
2618 size_t count = mixBufferSize >> mBitShift;
2619 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
2620 if (framesWritten > 0) {
2621 bytesWritten = framesWritten << mBitShift;
2622 } else {
2623 bytesWritten = framesWritten;
2624 }
2625
2626 // otherwise use the HAL / AudioStreamOut directly
2627 } else {
2628 // FIXME legacy, remove
2629 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2630 }
2631
2632 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002633 mNumWrites++;
2634 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002635}
2636
Glenn Kasten58912562012-04-03 10:45:00 -07002637void AudioFlinger::MixerThread::threadLoop_standby()
2638{
2639 // Idle the fast mixer if it's currently running
2640 if (mFastMixer != NULL) {
2641 FastMixerStateQueue *sq = mFastMixer->sq();
2642 FastMixerState *state = sq->begin();
2643 if (!(state->mCommand & FastMixerState::IDLE)) {
2644 state->mCommand = FastMixerState::COLD_IDLE;
2645 state->mColdFutexAddr = &mFastMixerFutex;
2646 state->mColdGen++;
2647 mFastMixerFutex = 0;
2648 sq->end();
2649 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2650 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2651 mNormalSink = mOutputSink;
2652 } else {
2653 sq->end(false /*didModify*/);
2654 }
2655 }
2656 PlaybackThread::threadLoop_standby();
2657}
2658
Glenn Kasten000f0e32012-03-01 17:10:56 -08002659// shared by MIXER and DIRECT, overridden by DUPLICATING
2660void AudioFlinger::PlaybackThread::threadLoop_standby()
2661{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002662 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2663 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002664}
2665
2666void AudioFlinger::MixerThread::threadLoop_mix()
2667{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002668 // obtain the presentation timestamp of the next output buffer
2669 int64_t pts;
2670 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002671
Glenn Kasten952eeb22012-03-06 11:30:57 -08002672 if (NULL != mOutput->stream->get_next_write_timestamp) {
2673 status = mOutput->stream->get_next_write_timestamp(
2674 mOutput->stream, &pts);
2675 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002676
Glenn Kasten952eeb22012-03-06 11:30:57 -08002677 if (status != NO_ERROR) {
2678 pts = AudioBufferProvider::kInvalidPTS;
2679 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002680
Glenn Kasten952eeb22012-03-06 11:30:57 -08002681 // mix buffers...
2682 mAudioMixer->process(pts);
2683 // increase sleep time progressively when application underrun condition clears.
2684 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2685 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2686 // such that we would underrun the audio HAL.
2687 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2688 sleepTimeShift--;
2689 }
2690 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002691 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002692 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002693}
2694
2695void AudioFlinger::MixerThread::threadLoop_sleepTime()
2696{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002697 // If no tracks are ready, sleep once for the duration of an output
2698 // buffer size, then write 0s to the output
2699 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002700 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002701 sleepTime = activeSleepTime >> sleepTimeShift;
2702 if (sleepTime < kMinThreadSleepTimeUs) {
2703 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002704 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002705 // reduce sleep time in case of consecutive application underruns to avoid
2706 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2707 // duration we would end up writing less data than needed by the audio HAL if
2708 // the condition persists.
2709 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2710 sleepTimeShift++;
2711 }
2712 } else {
2713 sleepTime = idleSleepTime;
2714 }
2715 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002716 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002717 memset (mMixBuffer, 0, mixBufferSize);
2718 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002719 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002720 }
2721 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002722}
2723
2724// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002725AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002726 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002727{
2728
Glenn Kasten29c23c32012-01-26 13:37:52 -08002729 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002730 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002731 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002732 size_t mixedTracks = 0;
2733 size_t tracksWithEffect = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07002734 size_t fastTracks = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002735
2736 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002737 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002738
Eric Laurent571d49c2010-08-11 05:20:11 -07002739 if (masterMute) {
2740 masterVolume = 0;
2741 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002742 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002743 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002744 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002745 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002746 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002747 masterVolume = (float)((v + (1 << 23)) >> 24);
2748 chain.clear();
2749 }
2750
2751 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002752 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002753 if (t == 0) continue;
2754
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002755 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002756 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002757
2758 if (track->isFastTrack()) {
2759 // cache the combined master volume and stream type volume for fast mixer;
2760 // this lacks any synchronization or barrier so VolumeProvider may read a stale value
2761 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
2762 ++fastTracks;
2763 if (track->isTerminated()) {
2764 tracksToRemove->add(track);
2765 }
2766 continue;
2767 }
2768
2769 { // local variable scope to avoid goto warning
2770
Mathias Agopian65ab4712010-07-14 17:59:35 -07002771 audio_track_cblk_t* cblk = track->cblk();
2772
2773 // The first time a track is added we wait
2774 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002775 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002776 // make sure that we have enough frames to mix one full buffer.
2777 // enforce this condition only once to enable draining the buffer in case the client
2778 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002779 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002780 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002781 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002782 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002783 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002784 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07002785 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07002786 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002787 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07002788 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08002789 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07002790 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08002791 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2792 // the minimum track buffer size is normally twice the number of frames necessary
2793 // to fill one buffer and the resampler should not leave more than one buffer worth
2794 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002795 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002796 }
2797 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002798 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002799 !track->isPaused() && !track->isTerminated())
2800 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002801 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002802
2803 mixedTracks++;
2804
2805 // track->mainBuffer() != mMixBuffer means there is an effect chain
2806 // connected to the track
2807 chain.clear();
2808 if (track->mainBuffer() != mMixBuffer) {
2809 chain = getEffectChain_l(track->sessionId());
2810 // Delegate volume control to effect in track effect chain if needed
2811 if (chain != 0) {
2812 tracksWithEffect++;
2813 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002814 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002815 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002816 }
2817 }
2818
2819
2820 int param = AudioMixer::VOLUME;
2821 if (track->mFillingUpStatus == Track::FS_FILLED) {
2822 // no ramp for the first volume setting
2823 track->mFillingUpStatus = Track::FS_ACTIVE;
2824 if (track->mState == TrackBase::RESUMING) {
2825 track->mState = TrackBase::ACTIVE;
2826 param = AudioMixer::RAMP_VOLUME;
2827 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002828 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002829 } else if (cblk->server != 0) {
2830 // If the track is stopped before the first frame was mixed,
2831 // do not apply ramp
2832 param = AudioMixer::RAMP_VOLUME;
2833 }
2834
2835 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002836 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002837 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002838 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002839 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002840 if (track->isPausing()) {
2841 track->setPaused();
2842 }
2843 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002844
Mathias Agopian65ab4712010-07-14 17:59:35 -07002845 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002846 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002847 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002848 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002849 vl = vlr & 0xFFFF;
2850 vr = vlr >> 16;
2851 // track volumes come from shared memory, so can't be trusted and must be clamped
2852 if (vl > MAX_GAIN_INT) {
2853 ALOGV("Track left volume out of range: %04X", vl);
2854 vl = MAX_GAIN_INT;
2855 }
2856 if (vr > MAX_GAIN_INT) {
2857 ALOGV("Track right volume out of range: %04X", vr);
2858 vr = MAX_GAIN_INT;
2859 }
2860 // now apply the master volume and stream type volume
2861 vl = (uint32_t)(v * vl) << 12;
2862 vr = (uint32_t)(v * vr) << 12;
2863 // assuming master volume and stream type volume each go up to 1.0,
2864 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002865
Glenn Kasten05632a52012-01-03 14:22:33 -08002866 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2867 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002868 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002869 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002870 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002871 }
2872 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002873 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002874 // Delegate volume control to effect in track effect chain if needed
2875 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2876 // Do not ramp volume if volume is controlled by effect
2877 param = AudioMixer::VOLUME;
2878 track->mHasVolumeController = true;
2879 } else {
2880 // force no volume ramp when volume controller was just disabled or removed
2881 // from effect chain to avoid volume spike
2882 if (track->mHasVolumeController) {
2883 param = AudioMixer::VOLUME;
2884 }
2885 track->mHasVolumeController = false;
2886 }
2887
2888 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002889 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002890 vl = (vl + (1 << 11)) >> 12;
2891 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2892 vr = (vr + (1 << 11)) >> 12;
2893 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002894
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002895 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 -07002896
Mathias Agopian65ab4712010-07-14 17:59:35 -07002897 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002898 mAudioMixer->setBufferProvider(name, track);
2899 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002900
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002901 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2902 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2903 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002904 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002905 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002906 AudioMixer::TRACK,
2907 AudioMixer::FORMAT, (void *)track->format());
2908 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002909 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002910 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002911 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002912 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002913 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002914 AudioMixer::RESAMPLE,
2915 AudioMixer::SAMPLE_RATE,
2916 (void *)(cblk->sampleRate));
2917 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002918 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002919 AudioMixer::TRACK,
2920 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2921 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002922 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923 AudioMixer::TRACK,
2924 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2925
2926 // reset retry count
2927 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002928
Eric Laurent27741442012-01-17 19:20:12 -08002929 // If one track is ready, set the mixer ready if:
2930 // - the mixer was not ready during previous round OR
2931 // - no other track is not ready
2932 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2933 mixerStatus != MIXER_TRACKS_ENABLED) {
2934 mixerStatus = MIXER_TRACKS_READY;
2935 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002936 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002937 //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 -07002938 if (track->isStopped()) {
2939 track->reset();
2940 }
2941 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2942 // We have consumed all the buffers of this track.
2943 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07002944 // TODO: use actual buffer filling status instead of latency when available from
2945 // audio HAL
2946 size_t audioHALFrames =
2947 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2948 size_t framesWritten =
2949 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2950 if (track->presentationComplete(framesWritten, audioHALFrames)) {
2951 tracksToRemove->add(track);
2952 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002953 } else {
2954 // No buffers for this track. Give it a few chances to
2955 // fill a buffer, then remove it from active list.
2956 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002957 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002958 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002959 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002960 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002961 // If one track is not ready, mark the mixer also not ready if:
2962 // - the mixer was ready during previous round OR
2963 // - no other track is ready
2964 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2965 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002966 mixerStatus = MIXER_TRACKS_ENABLED;
2967 }
2968 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002969 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002970 }
Glenn Kasten58912562012-04-03 10:45:00 -07002971
2972 } // local variable scope to avoid goto warning
2973track_is_ready: ;
2974
Mathias Agopian65ab4712010-07-14 17:59:35 -07002975 }
2976
Glenn Kasten58912562012-04-03 10:45:00 -07002977 // FIXME Here is where we would push the new FastMixer state if necessary
2978
Mathias Agopian65ab4712010-07-14 17:59:35 -07002979 // remove all the tracks that need to be...
2980 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002981 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002982 for (size_t i=0 ; i<count ; i++) {
2983 const sp<Track>& track = tracksToRemove->itemAt(i);
2984 mActiveTracks.remove(track);
2985 if (track->mainBuffer() != mMixBuffer) {
2986 chain = getEffectChain_l(track->sessionId());
2987 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002988 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002989 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002990 }
2991 }
2992 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002993 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002994 }
2995 }
2996 }
2997
2998 // mix buffer must be cleared if all tracks are connected to an
2999 // effect chain as in this case the mixer will not write to
3000 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003001 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3002 // FIXME as a performance optimization, should remember previous zero status
3003 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003004 }
3005
Glenn Kasten58912562012-04-03 10:45:00 -07003006 // if any fast tracks, then status is ready
3007 if (fastTracks > 0) {
3008 mixerStatus = MIXER_TRACKS_READY;
3009 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003010 return mixerStatus;
3011}
3012
Glenn Kasten66fcab92012-02-24 14:59:21 -08003013/*
3014The derived values that are cached:
3015 - mixBufferSize from frame count * frame size
3016 - activeSleepTime from activeSleepTimeUs()
3017 - idleSleepTime from idleSleepTimeUs()
3018 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3019 - maxPeriod from frame count and sample rate (MIXER only)
3020
3021The parameters that affect these derived values are:
3022 - frame count
3023 - frame size
3024 - sample rate
3025 - device type: A2DP or not
3026 - device latency
3027 - format: PCM or not
3028 - active sleep time
3029 - idle sleep time
3030*/
3031
3032void AudioFlinger::PlaybackThread::cacheParameters_l()
3033{
Glenn Kasten58912562012-04-03 10:45:00 -07003034 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003035 activeSleepTime = activeSleepTimeUs();
3036 idleSleepTime = idleSleepTimeUs();
3037}
3038
Glenn Kastenfff6d712012-01-12 16:38:12 -08003039void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003040{
Steve Block3856b092011-10-20 11:56:00 +01003041 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003042 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003043 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003044
Mathias Agopian65ab4712010-07-14 17:59:35 -07003045 size_t size = mTracks.size();
3046 for (size_t i = 0; i < size; i++) {
3047 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003048 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003049 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003050 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003051 }
3052 }
3053}
3054
Mathias Agopian65ab4712010-07-14 17:59:35 -07003055// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003056int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003057{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003058 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003059}
3060
3061// deleteTrackName_l() must be called with ThreadBase::mLock held
3062void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3063{
Steve Block3856b092011-10-20 11:56:00 +01003064 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003065 mAudioMixer->deleteTrackName(name);
3066}
3067
3068// checkForNewParameters_l() must be called with ThreadBase::mLock held
3069bool AudioFlinger::MixerThread::checkForNewParameters_l()
3070{
Glenn Kasten58912562012-04-03 10:45:00 -07003071 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3072 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003073 bool reconfig = false;
3074
3075 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003076
3077 if (mFastMixer != NULL) {
3078 FastMixerStateQueue *sq = mFastMixer->sq();
3079 FastMixerState *state = sq->begin();
3080 if (!(state->mCommand & FastMixerState::IDLE)) {
3081 previousCommand = state->mCommand;
3082 state->mCommand = FastMixerState::HOT_IDLE;
3083 sq->end();
3084 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3085 } else {
3086 sq->end(false /*didModify*/);
3087 }
3088 }
3089
Mathias Agopian65ab4712010-07-14 17:59:35 -07003090 status_t status = NO_ERROR;
3091 String8 keyValuePair = mNewParameters[0];
3092 AudioParameter param = AudioParameter(keyValuePair);
3093 int value;
3094
3095 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3096 reconfig = true;
3097 }
3098 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003099 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003100 status = BAD_VALUE;
3101 } else {
3102 reconfig = true;
3103 }
3104 }
3105 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003106 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003107 status = BAD_VALUE;
3108 } else {
3109 reconfig = true;
3110 }
3111 }
3112 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3113 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003114 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003115 // if frame count is changed after track creation
3116 if (!mTracks.isEmpty()) {
3117 status = INVALID_OPERATION;
3118 } else {
3119 reconfig = true;
3120 }
3121 }
3122 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003123#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003124 // when changing the audio output device, call addBatteryData to notify
3125 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003126 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003127 uint32_t params = 0;
3128 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003129 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003130 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3131 }
3132
3133 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003134 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003135 // check if any other device (except speaker) is on
3136 if (value & deviceWithoutSpeaker ) {
3137 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3138 }
3139
3140 if (params != 0) {
3141 addBatteryData(params);
3142 }
3143 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003144#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003145
Mathias Agopian65ab4712010-07-14 17:59:35 -07003146 // forward device change to effects that have requested to be
3147 // aware of attached audio device.
3148 mDevice = (uint32_t)value;
3149 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003150 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003151 }
3152 }
3153
3154 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003155 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003156 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003157 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003158 mOutput->stream->common.standby(&mOutput->stream->common);
3159 mStandby = true;
3160 mBytesWritten = 0;
3161 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003162 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003163 }
3164 if (status == NO_ERROR && reconfig) {
3165 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003166 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3167 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003168 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003169 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003170 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003171 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003172 if (name < 0) break;
3173 mTracks[i]->mName = name;
3174 // limit track sample rate to 2 x new output sample rate
3175 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3176 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3177 }
3178 }
3179 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3180 }
3181 }
3182
3183 mNewParameters.removeAt(0);
3184
3185 mParamStatus = status;
3186 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003187 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3188 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003189 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003190 }
Glenn Kasten58912562012-04-03 10:45:00 -07003191
3192 if (!(previousCommand & FastMixerState::IDLE)) {
3193 ALOG_ASSERT(mFastMixer != NULL);
3194 FastMixerStateQueue *sq = mFastMixer->sq();
3195 FastMixerState *state = sq->begin();
3196 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3197 state->mCommand = previousCommand;
3198 sq->end();
3199 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3200 }
3201
Mathias Agopian65ab4712010-07-14 17:59:35 -07003202 return reconfig;
3203}
3204
3205status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3206{
3207 const size_t SIZE = 256;
3208 char buffer[SIZE];
3209 String8 result;
3210
3211 PlaybackThread::dumpInternals(fd, args);
3212
3213 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3214 result.append(buffer);
3215 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003216
3217 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3218 FastMixerDumpState copy = mFastMixerDumpState;
3219 copy.dump(fd);
3220
Mathias Agopian65ab4712010-07-14 17:59:35 -07003221 return NO_ERROR;
3222}
3223
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003224uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003225{
Glenn Kasten58912562012-04-03 10:45:00 -07003226 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003227}
3228
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003229uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003230{
Glenn Kasten58912562012-04-03 10:45:00 -07003231 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003232}
3233
Glenn Kasten66fcab92012-02-24 14:59:21 -08003234void AudioFlinger::MixerThread::cacheParameters_l()
3235{
3236 PlaybackThread::cacheParameters_l();
3237
3238 // FIXME: Relaxed timing because of a certain device that can't meet latency
3239 // Should be reduced to 2x after the vendor fixes the driver issue
3240 // increase threshold again due to low power audio mode. The way this warning
3241 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003242 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003243}
3244
Mathias Agopian65ab4712010-07-14 17:59:35 -07003245// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003246AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3247 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003248 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003249 // mLeftVolFloat, mRightVolFloat
3250 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07003251{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003252}
3253
3254AudioFlinger::DirectOutputThread::~DirectOutputThread()
3255{
3256}
3257
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003258AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3259 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003260)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003261{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003262 sp<Track> trackToRemove;
3263
Glenn Kastenfec279f2012-03-08 07:47:15 -08003264 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003265
Glenn Kasten952eeb22012-03-06 11:30:57 -08003266 // find out which tracks need to be processed
3267 if (mActiveTracks.size() != 0) {
3268 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003269 // The track died recently
3270 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003271
Glenn Kasten952eeb22012-03-06 11:30:57 -08003272 Track* const track = t.get();
3273 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003274
Glenn Kasten952eeb22012-03-06 11:30:57 -08003275 // The first time a track is added we wait
3276 // for all its buffers to be filled before processing it
3277 if (cblk->framesReady() && track->isReady() &&
3278 !track->isPaused() && !track->isTerminated())
3279 {
3280 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003281
Glenn Kasten952eeb22012-03-06 11:30:57 -08003282 if (track->mFillingUpStatus == Track::FS_FILLED) {
3283 track->mFillingUpStatus = Track::FS_ACTIVE;
3284 mLeftVolFloat = mRightVolFloat = 0;
3285 mLeftVolShort = mRightVolShort = 0;
3286 if (track->mState == TrackBase::RESUMING) {
3287 track->mState = TrackBase::ACTIVE;
3288 rampVolume = true;
3289 }
3290 } else if (cblk->server != 0) {
3291 // If the track is stopped before the first frame was mixed,
3292 // do not apply ramp
3293 rampVolume = true;
3294 }
3295 // compute volume for this track
3296 float left, right;
3297 if (track->isMuted() || mMasterMute || track->isPausing() ||
3298 mStreamTypes[track->streamType()].mute) {
3299 left = right = 0;
3300 if (track->isPausing()) {
3301 track->setPaused();
3302 }
3303 } else {
3304 float typeVolume = mStreamTypes[track->streamType()].volume;
3305 float v = mMasterVolume * typeVolume;
3306 uint32_t vlr = cblk->getVolumeLR();
3307 float v_clamped = v * (vlr & 0xFFFF);
3308 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3309 left = v_clamped/MAX_GAIN;
3310 v_clamped = v * (vlr >> 16);
3311 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3312 right = v_clamped/MAX_GAIN;
3313 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003314
Glenn Kasten952eeb22012-03-06 11:30:57 -08003315 if (left != mLeftVolFloat || right != mRightVolFloat) {
3316 mLeftVolFloat = left;
3317 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003318
Glenn Kasten952eeb22012-03-06 11:30:57 -08003319 // If audio HAL implements volume control,
3320 // force software volume to nominal value
3321 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
3322 left = 1.0f;
3323 right = 1.0f;
3324 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003325
Glenn Kasten952eeb22012-03-06 11:30:57 -08003326 // Convert volumes from float to 8.24
3327 uint32_t vl = (uint32_t)(left * (1 << 24));
3328 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003329
Glenn Kasten952eeb22012-03-06 11:30:57 -08003330 // Delegate volume control to effect in track effect chain if needed
3331 // only one effect chain can be present on DirectOutputThread, so if
3332 // there is one, the track is connected to it
3333 if (!mEffectChains.isEmpty()) {
3334 // Do not ramp volume if volume is controlled by effect
3335 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003336 rampVolume = false;
3337 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003338 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003339
Glenn Kasten952eeb22012-03-06 11:30:57 -08003340 // Convert volumes from 8.24 to 4.12 format
3341 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
3342 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3343 leftVol = (uint16_t)v_clamped;
3344 v_clamped = (vr + (1 << 11)) >> 12;
3345 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3346 rightVol = (uint16_t)v_clamped;
3347 } else {
3348 leftVol = mLeftVolShort;
3349 rightVol = mRightVolShort;
3350 rampVolume = false;
3351 }
3352
3353 // reset retry count
3354 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003355 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003356 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003357 } else {
3358 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
3359 if (track->isStopped()) {
3360 track->reset();
3361 }
3362 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
3363 // We have consumed all the buffers of this track.
3364 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003365 // TODO: implement behavior for compressed audio
3366 size_t audioHALFrames =
3367 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3368 size_t framesWritten =
3369 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3370 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3371 trackToRemove = track;
3372 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003373 } else {
3374 // No buffers for this track. Give it a few chances to
3375 // fill a buffer, then remove it from active list.
3376 if (--(track->mRetryCount) <= 0) {
3377 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3378 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003379 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003380 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003381 }
3382 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003383 }
3384 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003385
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003386 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003387 // remove all the tracks that need to be...
3388 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003389 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003390 mActiveTracks.remove(trackToRemove);
3391 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003392 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003393 trackToRemove->sessionId());
3394 mEffectChains[0]->decActiveTrackCnt();
3395 }
3396 if (trackToRemove->isTerminated()) {
3397 removeTrack_l(trackToRemove);
3398 }
3399 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003400
Glenn Kastenfec279f2012-03-08 07:47:15 -08003401 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003402}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003403
Glenn Kasten000f0e32012-03-01 17:10:56 -08003404void AudioFlinger::DirectOutputThread::threadLoop_mix()
3405{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003406 AudioBufferProvider::Buffer buffer;
3407 size_t frameCount = mFrameCount;
3408 int8_t *curBuf = (int8_t *)mMixBuffer;
3409 // output audio to hardware
3410 while (frameCount) {
3411 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003412 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003413 if (CC_UNLIKELY(buffer.raw == NULL)) {
3414 memset(curBuf, 0, frameCount * mFrameSize);
3415 break;
3416 }
3417 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3418 frameCount -= buffer.frameCount;
3419 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003420 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003421 }
3422 sleepTime = 0;
3423 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003424 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003425
3426 // apply volume
3427
3428 // Do not apply volume on compressed audio
3429 if (!audio_is_linear_pcm(mFormat)) {
3430 return;
3431 }
3432
3433 // convert to signed 16 bit before volume calculation
3434 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3435 size_t count = mFrameCount * mChannelCount;
3436 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
3437 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003438 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003439 *dst-- = (int16_t)(*src--^0x80) << 8;
3440 }
3441 }
3442
3443 frameCount = mFrameCount;
3444 int16_t *out = mMixBuffer;
3445 if (rampVolume) {
3446 if (mChannelCount == 1) {
3447 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3448 int32_t vlInc = d / (int32_t)frameCount;
3449 int32_t vl = ((int32_t)mLeftVolShort << 16);
3450 do {
3451 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3452 out++;
3453 vl += vlInc;
3454 } while (--frameCount);
3455
3456 } else {
3457 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3458 int32_t vlInc = d / (int32_t)frameCount;
3459 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3460 int32_t vrInc = d / (int32_t)frameCount;
3461 int32_t vl = ((int32_t)mLeftVolShort << 16);
3462 int32_t vr = ((int32_t)mRightVolShort << 16);
3463 do {
3464 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3465 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3466 out += 2;
3467 vl += vlInc;
3468 vr += vrInc;
3469 } while (--frameCount);
3470 }
3471 } else {
3472 if (mChannelCount == 1) {
3473 do {
3474 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3475 out++;
3476 } while (--frameCount);
3477 } else {
3478 do {
3479 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3480 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3481 out += 2;
3482 } while (--frameCount);
3483 }
3484 }
3485
3486 // convert back to unsigned 8 bit after volume calculation
3487 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3488 size_t count = mFrameCount * mChannelCount;
3489 int16_t *src = mMixBuffer;
3490 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003491 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003492 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3493 }
3494 }
3495
3496 mLeftVolShort = leftVol;
3497 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003498}
3499
3500void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3501{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003502 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003503 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003504 sleepTime = activeSleepTime;
3505 } else {
3506 sleepTime = idleSleepTime;
3507 }
3508 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003509 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003510 sleepTime = 0;
3511 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003512}
3513
3514// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003515int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003516{
3517 return 0;
3518}
3519
3520// deleteTrackName_l() must be called with ThreadBase::mLock held
3521void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3522{
3523}
3524
3525// checkForNewParameters_l() must be called with ThreadBase::mLock held
3526bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3527{
3528 bool reconfig = false;
3529
3530 while (!mNewParameters.isEmpty()) {
3531 status_t status = NO_ERROR;
3532 String8 keyValuePair = mNewParameters[0];
3533 AudioParameter param = AudioParameter(keyValuePair);
3534 int value;
3535
3536 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3537 // do not accept frame count changes if tracks are open as the track buffer
3538 // size depends on frame count and correct behavior would not be garantied
3539 // if frame count is changed after track creation
3540 if (!mTracks.isEmpty()) {
3541 status = INVALID_OPERATION;
3542 } else {
3543 reconfig = true;
3544 }
3545 }
3546 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003547 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003548 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003549 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003550 mOutput->stream->common.standby(&mOutput->stream->common);
3551 mStandby = true;
3552 mBytesWritten = 0;
3553 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003554 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003555 }
3556 if (status == NO_ERROR && reconfig) {
3557 readOutputParameters();
3558 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3559 }
3560 }
3561
3562 mNewParameters.removeAt(0);
3563
3564 mParamStatus = status;
3565 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003566 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3567 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003568 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003569 }
3570 return reconfig;
3571}
3572
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003573uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003574{
3575 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003576 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003577 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003578 } else {
3579 time = 10000;
3580 }
3581 return time;
3582}
3583
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003584uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003585{
3586 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003587 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003588 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003589 } else {
3590 time = 10000;
3591 }
3592 return time;
3593}
3594
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003595uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003596{
3597 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003598 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003599 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3600 } else {
3601 time = 10000;
3602 }
3603 return time;
3604}
3605
Glenn Kasten66fcab92012-02-24 14:59:21 -08003606void AudioFlinger::DirectOutputThread::cacheParameters_l()
3607{
3608 PlaybackThread::cacheParameters_l();
3609
3610 // use shorter standby delay as on normal output to release
3611 // hardware resources as soon as possible
3612 standbyDelay = microseconds(activeSleepTime*2);
3613}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003614
Mathias Agopian65ab4712010-07-14 17:59:35 -07003615// ----------------------------------------------------------------------------
3616
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003617AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003618 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003619 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3620 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003621{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003622 addOutputTrack(mainThread);
3623}
3624
3625AudioFlinger::DuplicatingThread::~DuplicatingThread()
3626{
3627 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3628 mOutputTracks[i]->destroy();
3629 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003630}
3631
Glenn Kasten000f0e32012-03-01 17:10:56 -08003632void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003633{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003634 // mix buffers...
3635 if (outputsReady(outputTracks)) {
3636 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3637 } else {
3638 memset(mMixBuffer, 0, mixBufferSize);
3639 }
3640 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003641 writeFrames = mNormalFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003642}
3643
3644void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3645{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003646 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003647 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003648 sleepTime = activeSleepTime;
3649 } else {
3650 sleepTime = idleSleepTime;
3651 }
3652 } else if (mBytesWritten != 0) {
3653 // flush remaining overflow buffers in output tracks
3654 for (size_t i = 0; i < outputTracks.size(); i++) {
3655 if (outputTracks[i]->isActive()) {
3656 sleepTime = 0;
3657 writeFrames = 0;
3658 memset(mMixBuffer, 0, mixBufferSize);
3659 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003660 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003661 }
3662 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003663}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003664
Glenn Kasten000f0e32012-03-01 17:10:56 -08003665void AudioFlinger::DuplicatingThread::threadLoop_write()
3666{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003667 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003668 for (size_t i = 0; i < outputTracks.size(); i++) {
3669 outputTracks[i]->write(mMixBuffer, writeFrames);
3670 }
3671 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003672}
Glenn Kasten688a6402012-02-29 07:57:06 -08003673
Glenn Kasten000f0e32012-03-01 17:10:56 -08003674void AudioFlinger::DuplicatingThread::threadLoop_standby()
3675{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003676 // DuplicatingThread implements standby by stopping all tracks
3677 for (size_t i = 0; i < outputTracks.size(); i++) {
3678 outputTracks[i]->stop();
3679 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003680}
3681
Glenn Kastenfa26a852012-03-06 11:28:04 -08003682void AudioFlinger::DuplicatingThread::saveOutputTracks()
3683{
3684 outputTracks = mOutputTracks;
3685}
3686
3687void AudioFlinger::DuplicatingThread::clearOutputTracks()
3688{
3689 outputTracks.clear();
3690}
3691
Mathias Agopian65ab4712010-07-14 17:59:35 -07003692void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3693{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003694 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003695 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003696 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003697 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003698 this,
3699 mSampleRate,
3700 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003701 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003702 frameCount);
3703 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003704 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003705 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003706 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003707 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003708 }
3709}
3710
3711void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3712{
3713 Mutex::Autolock _l(mLock);
3714 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003715 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003716 mOutputTracks[i]->destroy();
3717 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003718 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003719 return;
3720 }
3721 }
Steve Block3856b092011-10-20 11:56:00 +01003722 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003723}
3724
Glenn Kasten438b0362012-03-06 11:24:48 -08003725// caller must hold mLock
3726void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003727{
3728 mWaitTimeMs = UINT_MAX;
3729 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3730 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003731 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003732 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3733 if (waitTimeMs < mWaitTimeMs) {
3734 mWaitTimeMs = waitTimeMs;
3735 }
3736 }
3737 }
3738}
3739
3740
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003741bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003742{
3743 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003744 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003745 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003746 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003747 return false;
3748 }
3749 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3750 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003751 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003752 return false;
3753 }
3754 }
3755 return true;
3756}
3757
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003758uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003759{
3760 return (mWaitTimeMs * 1000) / 2;
3761}
3762
Glenn Kasten66fcab92012-02-24 14:59:21 -08003763void AudioFlinger::DuplicatingThread::cacheParameters_l()
3764{
3765 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3766 updateWaitTime_l();
3767
3768 MixerThread::cacheParameters_l();
3769}
3770
Mathias Agopian65ab4712010-07-14 17:59:35 -07003771// ----------------------------------------------------------------------------
3772
3773// TrackBase constructor must be called with AudioFlinger::mLock held
3774AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003775 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003776 const sp<Client>& client,
3777 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003778 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003779 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003780 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003781 const sp<IMemory>& sharedBuffer,
3782 int sessionId)
3783 : RefBase(),
3784 mThread(thread),
3785 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003786 mCblk(NULL),
3787 // mBuffer
3788 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003789 mFrameCount(0),
3790 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07003791 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003792 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003793 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003794 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003795 // mChannelCount
3796 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003797{
Steve Block3856b092011-10-20 11:56:00 +01003798 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003799
Steve Blockb8a80522011-12-20 16:23:08 +00003800 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003801 size_t size = sizeof(audio_track_cblk_t);
3802 uint8_t channelCount = popcount(channelMask);
3803 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3804 if (sharedBuffer == 0) {
3805 size += bufferSize;
3806 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003807
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003808 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003809 mCblkMemory = client->heap()->allocate(size);
3810 if (mCblkMemory != 0) {
3811 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003812 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003813 new(mCblk) audio_track_cblk_t();
3814 // clear all buffers
3815 mCblk->frameCount = frameCount;
3816 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003817// uncomment the following lines to quickly test 32-bit wraparound
3818// mCblk->user = 0xffff0000;
3819// mCblk->server = 0xffff0000;
3820// mCblk->userBase = 0xffff0000;
3821// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003822 mChannelCount = channelCount;
3823 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003824 if (sharedBuffer == 0) {
3825 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3826 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3827 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003828 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003829 mCblk->flags = CBLK_UNDERRUN_ON;
3830 } else {
3831 mBuffer = sharedBuffer->pointer();
3832 }
3833 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3834 }
3835 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003836 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003837 client->heap()->dump("AudioTrack");
3838 return;
3839 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003840 } else {
3841 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07003842 // construct the shared structure in-place.
3843 new(mCblk) audio_track_cblk_t();
3844 // clear all buffers
3845 mCblk->frameCount = frameCount;
3846 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003847// uncomment the following lines to quickly test 32-bit wraparound
3848// mCblk->user = 0xffff0000;
3849// mCblk->server = 0xffff0000;
3850// mCblk->userBase = 0xffff0000;
3851// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003852 mChannelCount = channelCount;
3853 mChannelMask = channelMask;
3854 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3855 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3856 // Force underrun condition to avoid false underrun callback until first data is
3857 // written to buffer (other flags are cleared)
3858 mCblk->flags = CBLK_UNDERRUN_ON;
3859 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003860 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003861}
3862
3863AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3864{
Glenn Kastena0d68332012-01-27 16:47:15 -08003865 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003866 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003867 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003868 } else {
3869 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003870 }
3871 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003872 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003873 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003874 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003875 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003876 // If the client's reference count drops to zero, the associated destructor
3877 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3878 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003879 mClient.clear();
3880 }
3881}
3882
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003883// AudioBufferProvider interface
3884// getNextBuffer() = 0;
3885// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003886void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3887{
Glenn Kastene0feee32011-12-13 11:53:26 -08003888 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003889 mFrameCount = buffer->frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003890 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003891 buffer->frameCount = 0;
3892}
3893
3894bool AudioFlinger::ThreadBase::TrackBase::step() {
3895 bool result;
3896 audio_track_cblk_t* cblk = this->cblk();
3897
3898 result = cblk->stepServer(mFrameCount);
3899 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003900 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003901 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003902 }
3903 return result;
3904}
3905
3906void AudioFlinger::ThreadBase::TrackBase::reset() {
3907 audio_track_cblk_t* cblk = this->cblk();
3908
3909 cblk->user = 0;
3910 cblk->server = 0;
3911 cblk->userBase = 0;
3912 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003913 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01003914 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003915}
3916
Mathias Agopian65ab4712010-07-14 17:59:35 -07003917int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3918 return (int)mCblk->sampleRate;
3919}
3920
Mathias Agopian65ab4712010-07-14 17:59:35 -07003921void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3922 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003923 size_t frameSize = cblk->frameSize;
3924 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3925 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003926
3927 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07003928 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
3929 "TrackBase::getBuffer buffer out of range:\n"
3930 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
3931 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003932 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07003933 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003934
3935 return bufferStart;
3936}
3937
Eric Laurenta011e352012-03-29 15:51:43 -07003938status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
3939{
3940 mSyncEvents.add(event);
3941 return NO_ERROR;
3942}
3943
Mathias Agopian65ab4712010-07-14 17:59:35 -07003944// ----------------------------------------------------------------------------
3945
3946// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3947AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003948 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003949 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003950 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003951 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003952 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003953 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003954 int frameCount,
3955 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07003956 int sessionId,
3957 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003958 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07003959 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07003960 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07003961 // mRetryCount initialized later when needed
3962 mSharedBuffer(sharedBuffer),
3963 mStreamType(streamType),
3964 mName(-1), // see note below
3965 mMainBuffer(thread->mixBuffer()),
3966 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07003967 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07003968 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07003969 mFlags(flags),
3970 mFastIndex(-1),
3971 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003972{
3973 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003974 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3975 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003976 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten58912562012-04-03 10:45:00 -07003977 if (flags & IAudioFlinger::TRACK_FAST) {
3978 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
3979 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
3980 int i = __builtin_ctz(thread->mFastTrackAvailMask);
3981 ALOG_ASSERT(0 < i && i < FastMixerState::kMaxFastTracks);
3982 mFastIndex = i;
3983 thread->mFastTrackAvailMask &= ~(1 << i);
3984 // Although we've allocated an index, we can't mutate or push a new fast track state
3985 // here, because that data structure can only be changed within the normal mixer
3986 // threadLoop(). So instead, make a note to mutate and push later.
3987 thread->mFastTrackNewArray[i] = this;
3988 thread->mFastTrackNewMask |= 1 << i;
3989 }
Glenn Kastenf9959012012-03-19 11:14:37 -07003990 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003991 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kastenf9959012012-03-19 11:14:37 -07003992 if (mName < 0) {
3993 ALOGE("no more track names available");
3994 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003995 }
Glenn Kastenf9959012012-03-19 11:14:37 -07003996 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003997}
3998
3999AudioFlinger::PlaybackThread::Track::~Track()
4000{
Steve Block3856b092011-10-20 11:56:00 +01004001 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004002 sp<ThreadBase> thread = mThread.promote();
4003 if (thread != 0) {
4004 Mutex::Autolock _l(thread->mLock);
4005 mState = TERMINATED;
4006 }
4007}
4008
4009void AudioFlinger::PlaybackThread::Track::destroy()
4010{
4011 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4012 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004013 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004014 // we must acquire a strong reference on this Track before locking mLock
4015 // here so that the destructor is called only when exiting this function.
4016 // On the other hand, as long as Track::destroy() is only called by
4017 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4018 // this Track with its member mTrack.
4019 sp<Track> keep(this);
4020 { // scope for mLock
4021 sp<ThreadBase> thread = mThread.promote();
4022 if (thread != 0) {
4023 if (!isOutputTrack()) {
4024 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004025 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004026
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004027#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004028 // to track the speaker usage
4029 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004030#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004031 }
4032 AudioSystem::releaseOutput(thread->id());
4033 }
4034 Mutex::Autolock _l(thread->mLock);
4035 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4036 playbackThread->destroyTrack_l(this);
4037 }
4038 }
4039}
4040
4041void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4042{
Glenn Kasten83d86532012-01-17 14:39:34 -08004043 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004044 if (isFastTrack()) {
4045 strcpy(buffer, " fast");
4046 } else {
4047 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4048 }
4049 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 -08004050 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004051 mStreamType,
4052 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004053 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004054 mSessionId,
4055 mFrameCount,
4056 mState,
4057 mMute,
4058 mFillingUpStatus,
4059 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004060 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4061 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004062 mCblk->server,
4063 mCblk->user,
4064 (int)mMainBuffer,
4065 (int)mAuxBuffer);
4066}
4067
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004068// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004069status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004070 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004071{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004072 audio_track_cblk_t* cblk = this->cblk();
4073 uint32_t framesReady;
4074 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004075
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004076 // Check if last stepServer failed, try to step now
4077 if (mStepServerFailed) {
4078 if (!step()) goto getNextBuffer_exit;
4079 ALOGV("stepServer recovered");
4080 mStepServerFailed = false;
4081 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004082
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004083 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004084
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004085 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004086 uint32_t s = cblk->server;
4087 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4088
4089 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4090 if (framesReq > framesReady) {
4091 framesReq = framesReady;
4092 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004093 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004094 framesReq = bufferEnd - s;
4095 }
4096
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004097 buffer->raw = getBuffer(s, framesReq);
4098 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004099
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004100 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004101 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004102 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004103
4104getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004105 buffer->raw = NULL;
4106 buffer->frameCount = 0;
4107 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4108 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004109}
4110
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004111uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004112 return mCblk->framesReady();
4113}
4114
Mathias Agopian65ab4712010-07-14 17:59:35 -07004115bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004116 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004117
John Grossman4ff14ba2012-02-08 16:37:41 -08004118 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004119 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4120 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004121 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004122 return true;
4123 }
4124 return false;
4125}
4126
Glenn Kasten3acbd052012-02-28 10:39:56 -08004127status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004128 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004129{
4130 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004131 ALOGV("start(%d), calling pid %d session %d",
4132 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004133
Mathias Agopian65ab4712010-07-14 17:59:35 -07004134 sp<ThreadBase> thread = mThread.promote();
4135 if (thread != 0) {
4136 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004137 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004138 // here the track could be either new, or restarted
4139 // in both cases "unstop" the track
4140 if (mState == PAUSED) {
4141 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004142 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004143 } else {
4144 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004145 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004146 }
4147
4148 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4149 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004150 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004151 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004152
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004153#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004154 // to track the speaker usage
4155 if (status == NO_ERROR) {
4156 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4157 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004158#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004159 }
4160 if (status == NO_ERROR) {
4161 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4162 playbackThread->addTrack_l(this);
4163 } else {
4164 mState = state;
4165 }
4166 } else {
4167 status = BAD_VALUE;
4168 }
4169 return status;
4170}
4171
4172void AudioFlinger::PlaybackThread::Track::stop()
4173{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004174 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004175 sp<ThreadBase> thread = mThread.promote();
4176 if (thread != 0) {
4177 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004178 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004179 if (mState > STOPPED) {
4180 mState = STOPPED;
4181 // If the track is not active (PAUSED and buffers full), flush buffers
4182 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4183 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4184 reset();
4185 }
Steve Block3856b092011-10-20 11:56:00 +01004186 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004187 }
4188 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4189 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004190 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004191 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004192
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004193#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004194 // to track the speaker usage
4195 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004196#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004197 }
4198 }
4199}
4200
4201void AudioFlinger::PlaybackThread::Track::pause()
4202{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004203 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004204 sp<ThreadBase> thread = mThread.promote();
4205 if (thread != 0) {
4206 Mutex::Autolock _l(thread->mLock);
4207 if (mState == ACTIVE || mState == RESUMING) {
4208 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004209 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004210 if (!isOutputTrack()) {
4211 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004212 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004213 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004214
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004215#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004216 // to track the speaker usage
4217 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004218#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004219 }
4220 }
4221 }
4222}
4223
4224void AudioFlinger::PlaybackThread::Track::flush()
4225{
Steve Block3856b092011-10-20 11:56:00 +01004226 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004227 sp<ThreadBase> thread = mThread.promote();
4228 if (thread != 0) {
4229 Mutex::Autolock _l(thread->mLock);
4230 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
4231 return;
4232 }
4233 // No point remaining in PAUSED state after a flush => go to
4234 // STOPPED state
4235 mState = STOPPED;
4236
Eric Laurent38ccae22011-03-28 18:37:07 -07004237 // do not reset the track if it is still in the process of being stopped or paused.
4238 // this will be done by prepareTracks_l() when the track is stopped.
4239 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4240 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4241 reset();
4242 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004243 }
4244}
4245
4246void AudioFlinger::PlaybackThread::Track::reset()
4247{
4248 // Do not reset twice to avoid discarding data written just after a flush and before
4249 // the audioflinger thread detects the track is stopped.
4250 if (!mResetDone) {
4251 TrackBase::reset();
4252 // Force underrun condition to avoid false underrun callback until first data is
4253 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004254 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4255 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004256 mFillingUpStatus = FS_FILLING;
4257 mResetDone = true;
Eric Laurenta011e352012-03-29 15:51:43 -07004258 mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004259 }
4260}
4261
4262void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4263{
4264 mMute = muted;
4265}
4266
Mathias Agopian65ab4712010-07-14 17:59:35 -07004267status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4268{
4269 status_t status = DEAD_OBJECT;
4270 sp<ThreadBase> thread = mThread.promote();
4271 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004272 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4273 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004274 }
4275 return status;
4276}
4277
4278void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4279{
4280 mAuxEffectId = EffectId;
4281 mAuxBuffer = buffer;
4282}
4283
Eric Laurenta011e352012-03-29 15:51:43 -07004284bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4285 size_t audioHalFrames)
4286{
4287 // a track is considered presented when the total number of frames written to audio HAL
4288 // corresponds to the number of frames written when presentationComplete() is called for the
4289 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4290 if (mPresentationCompleteFrames == 0) {
4291 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4292 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4293 mPresentationCompleteFrames, audioHalFrames);
4294 }
4295 if (framesWritten >= mPresentationCompleteFrames) {
4296 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4297 mSessionId, framesWritten);
4298 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
4299 mPresentationCompleteFrames = 0;
4300 return true;
4301 }
4302 return false;
4303}
4304
4305void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4306{
4307 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4308 if (mSyncEvents[i]->type() == type) {
4309 mSyncEvents[i]->trigger();
4310 mSyncEvents.removeAt(i);
4311 i--;
4312 }
4313 }
4314}
4315
Glenn Kasten58912562012-04-03 10:45:00 -07004316// implement VolumeBufferProvider interface
4317
4318uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4319{
4320 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4321 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4322 uint32_t vlr = mCblk->getVolumeLR();
4323 uint32_t vl = vlr & 0xFFFF;
4324 uint32_t vr = vlr >> 16;
4325 // track volumes come from shared memory, so can't be trusted and must be clamped
4326 if (vl > MAX_GAIN_INT) {
4327 vl = MAX_GAIN_INT;
4328 }
4329 if (vr > MAX_GAIN_INT) {
4330 vr = MAX_GAIN_INT;
4331 }
4332 // now apply the cached master volume and stream type volume;
4333 // this is trusted but lacks any synchronization or barrier so may be stale
4334 float v = mCachedVolume;
4335 vl *= v;
4336 vr *= v;
4337 // re-combine into U4.16
4338 vlr = (vr << 16) | (vl & 0xFFFF);
4339 // FIXME look at mute, pause, and stop flags
4340 return vlr;
4341}
Eric Laurenta011e352012-03-29 15:51:43 -07004342
John Grossman4ff14ba2012-02-08 16:37:41 -08004343// timed audio tracks
4344
4345sp<AudioFlinger::PlaybackThread::TimedTrack>
4346AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004347 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004348 const sp<Client>& client,
4349 audio_stream_type_t streamType,
4350 uint32_t sampleRate,
4351 audio_format_t format,
4352 uint32_t channelMask,
4353 int frameCount,
4354 const sp<IMemory>& sharedBuffer,
4355 int sessionId) {
4356 if (!client->reserveTimedTrack())
4357 return NULL;
4358
Glenn Kastena0356762012-03-19 10:38:51 -07004359 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004360 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4361 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004362}
4363
4364AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004365 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004366 const sp<Client>& client,
4367 audio_stream_type_t streamType,
4368 uint32_t sampleRate,
4369 audio_format_t format,
4370 uint32_t channelMask,
4371 int frameCount,
4372 const sp<IMemory>& sharedBuffer,
4373 int sessionId)
4374 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004375 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004376 mQueueHeadInFlight(false),
4377 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004378 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004379 mTimedSilenceBuffer(NULL),
4380 mTimedSilenceBufferSize(0),
4381 mTimedAudioOutputOnTime(false),
4382 mMediaTimeTransformValid(false)
4383{
4384 LocalClock lc;
4385 mLocalTimeFreq = lc.getLocalFreq();
4386
4387 mLocalTimeToSampleTransform.a_zero = 0;
4388 mLocalTimeToSampleTransform.b_zero = 0;
4389 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4390 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4391 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4392 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004393
4394 mMediaTimeToSampleTransform.a_zero = 0;
4395 mMediaTimeToSampleTransform.b_zero = 0;
4396 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4397 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4398 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4399 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004400}
4401
4402AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4403 mClient->releaseTimedTrack();
4404 delete [] mTimedSilenceBuffer;
4405}
4406
4407status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4408 size_t size, sp<IMemory>* buffer) {
4409
4410 Mutex::Autolock _l(mTimedBufferQueueLock);
4411
4412 trimTimedBufferQueue_l();
4413
4414 // lazily initialize the shared memory heap for timed buffers
4415 if (mTimedMemoryDealer == NULL) {
4416 const int kTimedBufferHeapSize = 512 << 10;
4417
4418 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4419 "AudioFlingerTimed");
4420 if (mTimedMemoryDealer == NULL)
4421 return NO_MEMORY;
4422 }
4423
4424 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4425 if (newBuffer == NULL) {
4426 newBuffer = mTimedMemoryDealer->allocate(size);
4427 if (newBuffer == NULL)
4428 return NO_MEMORY;
4429 }
4430
4431 *buffer = newBuffer;
4432 return NO_ERROR;
4433}
4434
4435// caller must hold mTimedBufferQueueLock
4436void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4437 int64_t mediaTimeNow;
4438 {
4439 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4440 if (!mMediaTimeTransformValid)
4441 return;
4442
4443 int64_t targetTimeNow;
4444 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4445 ? mCCHelper.getCommonTime(&targetTimeNow)
4446 : mCCHelper.getLocalTime(&targetTimeNow);
4447
4448 if (OK != res)
4449 return;
4450
4451 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4452 &mediaTimeNow)) {
4453 return;
4454 }
4455 }
4456
John Grossman1c345192012-03-27 14:00:17 -07004457 size_t trimEnd;
4458 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004459 int64_t bufEnd;
4460
John Grossmanc95cfbb2012-04-12 11:53:11 -07004461 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4462 // We have a next buffer. Just use its PTS as the PTS of the frame
4463 // following the last frame in this buffer. If the stream is sparse
4464 // (ie, there are deliberate gaps left in the stream which should be
4465 // filled with silence by the TimedAudioTrack), then this can result
4466 // in one extra buffer being left un-trimmed when it could have
4467 // been. In general, this is not typical, and we would rather
4468 // optimized away the TS calculation below for the more common case
4469 // where PTSes are contiguous.
4470 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4471 } else {
4472 // We have no next buffer. Compute the PTS of the frame following
4473 // the last frame in this buffer by computing the duration of of
4474 // this frame in media time units and adding it to the PTS of the
4475 // buffer.
4476 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4477 / mCblk->frameSize;
4478
4479 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4480 &bufEnd)) {
4481 ALOGE("Failed to convert frame count of %lld to media time"
4482 " duration" " (scale factor %d/%u) in %s",
4483 frameCount,
4484 mMediaTimeToSampleTransform.a_to_b_numer,
4485 mMediaTimeToSampleTransform.a_to_b_denom,
4486 __PRETTY_FUNCTION__);
4487 break;
4488 }
4489 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004490 }
John Grossman9fbdee12012-03-26 17:51:46 -07004491
4492 if (bufEnd > mediaTimeNow)
4493 break;
4494
4495 // Is the buffer we want to use in the middle of a mix operation right
4496 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4497 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004498 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004499 mTrimQueueHeadOnRelease = true;
4500 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004501 }
4502
John Grossman9fbdee12012-03-26 17:51:46 -07004503 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004504 if (trimStart < trimEnd) {
4505 // Update the bookkeeping for framesReady()
4506 for (size_t i = trimStart; i < trimEnd; ++i) {
4507 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4508 }
4509
4510 // Now actually remove the buffers from the queue.
4511 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004512 }
4513}
4514
John Grossman1c345192012-03-27 14:00:17 -07004515void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4516 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004517 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4518 "%s called (reason \"%s\"), but timed buffer queue has no"
4519 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004520
4521 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4522 mTimedBufferQueue.removeAt(0);
4523}
4524
4525void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4526 const TimedBuffer& buf,
4527 const char* logTag) {
4528 uint32_t bufBytes = buf.buffer()->size();
4529 uint32_t consumedAlready = buf.position();
4530
Eric Laurentb388e532012-04-14 13:32:48 -07004531 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004532 "Bad bookkeeping while updating frames pending. Timed buffer is"
4533 " only %u bytes long, but claims to have consumed %u"
4534 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004535 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004536
4537 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004538 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4539 "Bad bookkeeping while updating frames pending. Should have at"
4540 " least %u queued frames, but we think we have only %u. (update"
4541 " reason: \"%s\")",
4542 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004543
4544 mFramesPendingInQueue -= bufFrames;
4545}
4546
John Grossman4ff14ba2012-02-08 16:37:41 -08004547status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4548 const sp<IMemory>& buffer, int64_t pts) {
4549
4550 {
4551 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4552 if (!mMediaTimeTransformValid)
4553 return INVALID_OPERATION;
4554 }
4555
4556 Mutex::Autolock _l(mTimedBufferQueueLock);
4557
John Grossman1c345192012-03-27 14:00:17 -07004558 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4559 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004560 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4561
4562 return NO_ERROR;
4563}
4564
4565status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4566 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4567
John Grossman1c345192012-03-27 14:00:17 -07004568 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4569 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4570 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004571
4572 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4573 target == TimedAudioTrack::COMMON_TIME)) {
4574 return BAD_VALUE;
4575 }
4576
4577 Mutex::Autolock lock(mMediaTimeTransformLock);
4578 mMediaTimeTransform = xform;
4579 mMediaTimeTransformTarget = target;
4580 mMediaTimeTransformValid = true;
4581
4582 return NO_ERROR;
4583}
4584
4585#define min(a, b) ((a) < (b) ? (a) : (b))
4586
4587// implementation of getNextBuffer for tracks whose buffers have timestamps
4588status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4589 AudioBufferProvider::Buffer* buffer, int64_t pts)
4590{
4591 if (pts == AudioBufferProvider::kInvalidPTS) {
4592 buffer->raw = 0;
4593 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07004594 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004595 return INVALID_OPERATION;
4596 }
4597
John Grossman4ff14ba2012-02-08 16:37:41 -08004598 Mutex::Autolock _l(mTimedBufferQueueLock);
4599
John Grossman9fbdee12012-03-26 17:51:46 -07004600 ALOG_ASSERT(!mQueueHeadInFlight,
4601 "getNextBuffer called without releaseBuffer!");
4602
John Grossman4ff14ba2012-02-08 16:37:41 -08004603 while (true) {
4604
4605 // if we have no timed buffers, then fail
4606 if (mTimedBufferQueue.isEmpty()) {
4607 buffer->raw = 0;
4608 buffer->frameCount = 0;
4609 return NOT_ENOUGH_DATA;
4610 }
4611
4612 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4613
4614 // calculate the PTS of the head of the timed buffer queue expressed in
4615 // local time
4616 int64_t headLocalPTS;
4617 {
4618 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4619
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004620 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004621
4622 if (mMediaTimeTransform.a_to_b_denom == 0) {
4623 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07004624 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004625 return NO_ERROR;
4626 }
4627
4628 int64_t transformedPTS;
4629 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4630 &transformedPTS)) {
4631 // the transform failed. this shouldn't happen, but if it does
4632 // then just drop this buffer
4633 ALOGW("timedGetNextBuffer transform failed");
4634 buffer->raw = 0;
4635 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07004636 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08004637 return NO_ERROR;
4638 }
4639
4640 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4641 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4642 &headLocalPTS)) {
4643 buffer->raw = 0;
4644 buffer->frameCount = 0;
4645 return INVALID_OPERATION;
4646 }
4647 } else {
4648 headLocalPTS = transformedPTS;
4649 }
4650 }
4651
4652 // adjust the head buffer's PTS to reflect the portion of the head buffer
4653 // that has already been consumed
4654 int64_t effectivePTS = headLocalPTS +
4655 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4656
4657 // Calculate the delta in samples between the head of the input buffer
4658 // queue and the start of the next output buffer that will be written.
4659 // If the transformation fails because of over or underflow, it means
4660 // that the sample's position in the output stream is so far out of
4661 // whack that it should just be dropped.
4662 int64_t sampleDelta;
4663 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4664 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004665 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
4666 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08004667 continue;
4668 }
4669 if (!mLocalTimeToSampleTransform.doForwardTransform(
4670 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07004671 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004672 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08004673 continue;
4674 }
4675
John Grossman1c345192012-03-27 14:00:17 -07004676 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
4677 " sampleDelta=[%d.%08x]",
4678 head.pts(), head.position(), pts,
4679 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
4680 + (sampleDelta >> 32)),
4681 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08004682
4683 // if the delta between the ideal placement for the next input sample and
4684 // the current output position is within this threshold, then we will
4685 // concatenate the next input samples to the previous output
4686 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07004687 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08004688
4689 // if this is the first buffer of audio that we're emitting from this track
4690 // then it should be almost exactly on time.
4691 const int64_t kSampleStartupThreshold = 1LL << 32;
4692
4693 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07004694 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004695 // the next input is close enough to being on time, so concatenate it
4696 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07004697 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004698
John Grossman1c345192012-03-27 14:00:17 -07004699 ALOGVV("*** on time: head.pos=%d frameCount=%u",
4700 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08004701 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07004702 }
4703
4704 // Looks like our output is not on time. Reset our on timed status.
4705 // Next time we mix samples from our input queue, then should be within
4706 // the StartupThreshold.
4707 mTimedAudioOutputOnTime = false;
4708 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004709 // the gap between the current output position and the proper start of
4710 // the next input sample is too big, so fill it with silence
4711 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4712
John Grossman9fbdee12012-03-26 17:51:46 -07004713 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004714 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4715 return NO_ERROR;
4716 } else {
4717 // the next input sample is late
4718 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4719 size_t onTimeSamplePosition =
4720 head.position() + lateFrames * mCblk->frameSize;
4721
4722 if (onTimeSamplePosition > head.buffer()->size()) {
4723 // all the remaining samples in the head are too late, so
4724 // drop it and move on
4725 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004726 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08004727 continue;
4728 } else {
4729 // skip over the late samples
4730 head.setPosition(onTimeSamplePosition);
4731
4732 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07004733 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004734
4735 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4736 return NO_ERROR;
4737 }
4738 }
4739 }
4740}
4741
4742// Yield samples from the timed buffer queue head up to the given output
4743// buffer's capacity.
4744//
4745// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004746void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004747 AudioBufferProvider::Buffer* buffer) {
4748
4749 const TimedBuffer& head = mTimedBufferQueue[0];
4750
4751 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4752 head.position());
4753
4754 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4755 mCblk->frameSize);
4756 size_t framesRequested = buffer->frameCount;
4757 buffer->frameCount = min(framesLeftInHead, framesRequested);
4758
John Grossman9fbdee12012-03-26 17:51:46 -07004759 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08004760 mTimedAudioOutputOnTime = true;
4761}
4762
4763// Yield samples of silence up to the given output buffer's capacity
4764//
4765// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004766void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004767 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4768
4769 // lazily allocate a buffer filled with silence
4770 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4771 delete [] mTimedSilenceBuffer;
4772 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4773 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4774 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4775 }
4776
4777 buffer->raw = mTimedSilenceBuffer;
4778 size_t framesRequested = buffer->frameCount;
4779 buffer->frameCount = min(numFrames, framesRequested);
4780
4781 mTimedAudioOutputOnTime = false;
4782}
4783
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004784// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004785void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4786 AudioBufferProvider::Buffer* buffer) {
4787
4788 Mutex::Autolock _l(mTimedBufferQueueLock);
4789
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004790 // If the buffer which was just released is part of the buffer at the head
4791 // of the queue, be sure to update the amt of the buffer which has been
4792 // consumed. If the buffer being returned is not part of the head of the
4793 // queue, its either because the buffer is part of the silence buffer, or
4794 // because the head of the timed queue was trimmed after the mixer called
4795 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07004796 if (buffer->raw == mTimedSilenceBuffer) {
4797 ALOG_ASSERT(!mQueueHeadInFlight,
4798 "Queue head in flight during release of silence buffer!");
4799 goto done;
4800 }
4801
4802 ALOG_ASSERT(mQueueHeadInFlight,
4803 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
4804 " head in flight.");
4805
4806 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004807 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004808
4809 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07004810 void* end = reinterpret_cast<void*>(
4811 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
4812 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004813
John Grossman9fbdee12012-03-26 17:51:46 -07004814 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
4815 "released buffer not within the head of the timed buffer"
4816 " queue; qHead = [%p, %p], released buffer = %p",
4817 start, end, buffer->raw);
4818
4819 head.setPosition(head.position() +
4820 (buffer->frameCount * mCblk->frameSize));
4821 mQueueHeadInFlight = false;
4822
John Grossman1c345192012-03-27 14:00:17 -07004823 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
4824 "Bad bookkeeping during releaseBuffer! Should have at"
4825 " least %u queued frames, but we think we have only %u",
4826 buffer->frameCount, mFramesPendingInQueue);
4827
4828 mFramesPendingInQueue -= buffer->frameCount;
4829
John Grossman9fbdee12012-03-26 17:51:46 -07004830 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
4831 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07004832 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07004833 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004834 }
John Grossman9fbdee12012-03-26 17:51:46 -07004835 } else {
4836 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
4837 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08004838 }
4839
John Grossman9fbdee12012-03-26 17:51:46 -07004840done:
John Grossman4ff14ba2012-02-08 16:37:41 -08004841 buffer->raw = 0;
4842 buffer->frameCount = 0;
4843}
4844
4845uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4846 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07004847 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08004848}
4849
4850AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4851 : mPTS(0), mPosition(0) {}
4852
4853AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4854 const sp<IMemory>& buffer, int64_t pts)
4855 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4856
Mathias Agopian65ab4712010-07-14 17:59:35 -07004857// ----------------------------------------------------------------------------
4858
4859// RecordTrack constructor must be called with AudioFlinger::mLock held
4860AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004861 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004862 const sp<Client>& client,
4863 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004864 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004865 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004866 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004867 int sessionId)
4868 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004869 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004870 mOverflow(false)
4871{
4872 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004873 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
4874 if (format == AUDIO_FORMAT_PCM_16_BIT) {
4875 mCblk->frameSize = mChannelCount * sizeof(int16_t);
4876 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
4877 mCblk->frameSize = mChannelCount * sizeof(int8_t);
4878 } else {
4879 mCblk->frameSize = sizeof(int8_t);
4880 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004881 }
4882}
4883
4884AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4885{
4886 sp<ThreadBase> thread = mThread.promote();
4887 if (thread != 0) {
4888 AudioSystem::releaseInput(thread->id());
4889 }
4890}
4891
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004892// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004893status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004894{
4895 audio_track_cblk_t* cblk = this->cblk();
4896 uint32_t framesAvail;
4897 uint32_t framesReq = buffer->frameCount;
4898
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004899 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004900 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004901 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004902 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004903 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004904 }
4905
4906 framesAvail = cblk->framesAvailable_l();
4907
Glenn Kastenf6b16782011-12-15 09:51:17 -08004908 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004909 uint32_t s = cblk->server;
4910 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4911
4912 if (framesReq > framesAvail) {
4913 framesReq = framesAvail;
4914 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004915 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004916 framesReq = bufferEnd - s;
4917 }
4918
4919 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004920 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004921
4922 buffer->frameCount = framesReq;
4923 return NO_ERROR;
4924 }
4925
4926getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004927 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004928 buffer->frameCount = 0;
4929 return NOT_ENOUGH_DATA;
4930}
4931
Glenn Kasten3acbd052012-02-28 10:39:56 -08004932status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004933 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004934{
4935 sp<ThreadBase> thread = mThread.promote();
4936 if (thread != 0) {
4937 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08004938 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004939 } else {
4940 return BAD_VALUE;
4941 }
4942}
4943
4944void AudioFlinger::RecordThread::RecordTrack::stop()
4945{
4946 sp<ThreadBase> thread = mThread.promote();
4947 if (thread != 0) {
4948 RecordThread *recordThread = (RecordThread *)thread.get();
4949 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004950 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08004951 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07004952 // read from buffer
4953 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004954 }
4955}
4956
4957void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4958{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004959 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004960 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004961 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004962 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004963 mSessionId,
4964 mFrameCount,
4965 mState,
4966 mCblk->sampleRate,
4967 mCblk->server,
4968 mCblk->user);
4969}
4970
4971
4972// ----------------------------------------------------------------------------
4973
4974AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004975 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004976 DuplicatingThread *sourceThread,
4977 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004978 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004979 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004980 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07004981 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
4982 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004983 mActive(false), mSourceThread(sourceThread)
4984{
4985
Mathias Agopian65ab4712010-07-14 17:59:35 -07004986 if (mCblk != NULL) {
4987 mCblk->flags |= CBLK_DIRECTION_OUT;
4988 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004989 mOutBuffer.frameCount = 0;
4990 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01004991 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004992 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4993 mCblk, mBuffer, mCblk->buffers,
4994 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004995 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00004996 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004997 }
4998}
4999
5000AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5001{
5002 clearBufferQueue();
5003}
5004
Glenn Kasten3acbd052012-02-28 10:39:56 -08005005status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005006 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005007{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005008 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005009 if (status != NO_ERROR) {
5010 return status;
5011 }
5012
5013 mActive = true;
5014 mRetryCount = 127;
5015 return status;
5016}
5017
5018void AudioFlinger::PlaybackThread::OutputTrack::stop()
5019{
5020 Track::stop();
5021 clearBufferQueue();
5022 mOutBuffer.frameCount = 0;
5023 mActive = false;
5024}
5025
5026bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5027{
5028 Buffer *pInBuffer;
5029 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005030 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005031 bool outputBufferFull = false;
5032 inBuffer.frameCount = frames;
5033 inBuffer.i16 = data;
5034
5035 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5036
5037 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005038 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005039 sp<ThreadBase> thread = mThread.promote();
5040 if (thread != 0) {
5041 MixerThread *mixerThread = (MixerThread *)thread.get();
5042 if (mCblk->frameCount > frames){
5043 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5044 uint32_t startFrames = (mCblk->frameCount - frames);
5045 pInBuffer = new Buffer;
5046 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5047 pInBuffer->frameCount = startFrames;
5048 pInBuffer->i16 = pInBuffer->mBuffer;
5049 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5050 mBufferQueue.add(pInBuffer);
5051 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005052 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005053 }
5054 }
5055 }
5056 }
5057
5058 while (waitTimeLeftMs) {
5059 // First write pending buffers, then new data
5060 if (mBufferQueue.size()) {
5061 pInBuffer = mBufferQueue.itemAt(0);
5062 } else {
5063 pInBuffer = &inBuffer;
5064 }
5065
5066 if (pInBuffer->frameCount == 0) {
5067 break;
5068 }
5069
5070 if (mOutBuffer.frameCount == 0) {
5071 mOutBuffer.frameCount = pInBuffer->frameCount;
5072 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005073 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005074 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005075 outputBufferFull = true;
5076 break;
5077 }
5078 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5079 if (waitTimeLeftMs >= waitTimeMs) {
5080 waitTimeLeftMs -= waitTimeMs;
5081 } else {
5082 waitTimeLeftMs = 0;
5083 }
5084 }
5085
5086 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5087 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5088 mCblk->stepUser(outFrames);
5089 pInBuffer->frameCount -= outFrames;
5090 pInBuffer->i16 += outFrames * channelCount;
5091 mOutBuffer.frameCount -= outFrames;
5092 mOutBuffer.i16 += outFrames * channelCount;
5093
5094 if (pInBuffer->frameCount == 0) {
5095 if (mBufferQueue.size()) {
5096 mBufferQueue.removeAt(0);
5097 delete [] pInBuffer->mBuffer;
5098 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005099 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005100 } else {
5101 break;
5102 }
5103 }
5104 }
5105
5106 // If we could not write all frames, allocate a buffer and queue it for next time.
5107 if (inBuffer.frameCount) {
5108 sp<ThreadBase> thread = mThread.promote();
5109 if (thread != 0 && !thread->standby()) {
5110 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5111 pInBuffer = new Buffer;
5112 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5113 pInBuffer->frameCount = inBuffer.frameCount;
5114 pInBuffer->i16 = pInBuffer->mBuffer;
5115 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5116 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005117 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005118 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005119 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005120 }
5121 }
5122 }
5123
5124 // Calling write() with a 0 length buffer, means that no more data will be written:
5125 // If no more buffers are pending, fill output track buffer to make sure it is started
5126 // by output mixer.
5127 if (frames == 0 && mBufferQueue.size() == 0) {
5128 if (mCblk->user < mCblk->frameCount) {
5129 frames = mCblk->frameCount - mCblk->user;
5130 pInBuffer = new Buffer;
5131 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5132 pInBuffer->frameCount = frames;
5133 pInBuffer->i16 = pInBuffer->mBuffer;
5134 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5135 mBufferQueue.add(pInBuffer);
5136 } else if (mActive) {
5137 stop();
5138 }
5139 }
5140
5141 return outputBufferFull;
5142}
5143
5144status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5145{
5146 int active;
5147 status_t result;
5148 audio_track_cblk_t* cblk = mCblk;
5149 uint32_t framesReq = buffer->frameCount;
5150
Steve Block3856b092011-10-20 11:56:00 +01005151// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005152 buffer->frameCount = 0;
5153
5154 uint32_t framesAvail = cblk->framesAvailable();
5155
5156
5157 if (framesAvail == 0) {
5158 Mutex::Autolock _l(cblk->lock);
5159 goto start_loop_here;
5160 while (framesAvail == 0) {
5161 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005162 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005163 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005164 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005165 }
5166 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5167 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005168 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005169 }
5170 // read the server count again
5171 start_loop_here:
5172 framesAvail = cblk->framesAvailable_l();
5173 }
5174 }
5175
5176// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005177// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005178// }
5179
5180 if (framesReq > framesAvail) {
5181 framesReq = framesAvail;
5182 }
5183
5184 uint32_t u = cblk->user;
5185 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5186
Marco Nelissena1472d92012-03-30 14:36:54 -07005187 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005188 framesReq = bufferEnd - u;
5189 }
5190
5191 buffer->frameCount = framesReq;
5192 buffer->raw = (void *)cblk->buffer(u);
5193 return NO_ERROR;
5194}
5195
5196
5197void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5198{
5199 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005200
5201 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005202 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005203 delete [] pBuffer->mBuffer;
5204 delete pBuffer;
5205 }
5206 mBufferQueue.clear();
5207}
5208
5209// ----------------------------------------------------------------------------
5210
5211AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5212 : RefBase(),
5213 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005214 // 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 -07005215 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005216 mPid(pid),
5217 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005218{
5219 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5220}
5221
5222// Client destructor must be called with AudioFlinger::mLock held
5223AudioFlinger::Client::~Client()
5224{
5225 mAudioFlinger->removeClient_l(mPid);
5226}
5227
Glenn Kasten435dbe62012-01-30 10:15:48 -08005228sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005229{
5230 return mMemoryDealer;
5231}
5232
John Grossman4ff14ba2012-02-08 16:37:41 -08005233// Reserve one of the limited slots for a timed audio track associated
5234// with this client
5235bool AudioFlinger::Client::reserveTimedTrack()
5236{
5237 const int kMaxTimedTracksPerClient = 4;
5238
5239 Mutex::Autolock _l(mTimedTrackLock);
5240
5241 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5242 ALOGW("can not create timed track - pid %d has exceeded the limit",
5243 mPid);
5244 return false;
5245 }
5246
5247 mTimedTrackCount++;
5248 return true;
5249}
5250
5251// Release a slot for a timed audio track
5252void AudioFlinger::Client::releaseTimedTrack()
5253{
5254 Mutex::Autolock _l(mTimedTrackLock);
5255 mTimedTrackCount--;
5256}
5257
Mathias Agopian65ab4712010-07-14 17:59:35 -07005258// ----------------------------------------------------------------------------
5259
5260AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5261 const sp<IAudioFlingerClient>& client,
5262 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005263 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005264{
5265}
5266
5267AudioFlinger::NotificationClient::~NotificationClient()
5268{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005269}
5270
5271void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5272{
5273 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005274 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005275}
5276
5277// ----------------------------------------------------------------------------
5278
5279AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5280 : BnAudioTrack(),
5281 mTrack(track)
5282{
5283}
5284
5285AudioFlinger::TrackHandle::~TrackHandle() {
5286 // just stop the track on deletion, associated resources
5287 // will be freed from the main thread once all pending buffers have
5288 // been played. Unless it's not in the active track list, in which
5289 // case we free everything now...
5290 mTrack->destroy();
5291}
5292
Glenn Kasten90716c52012-01-26 13:40:12 -08005293sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5294 return mTrack->getCblk();
5295}
5296
Glenn Kasten3acbd052012-02-28 10:39:56 -08005297status_t AudioFlinger::TrackHandle::start() {
5298 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005299}
5300
5301void AudioFlinger::TrackHandle::stop() {
5302 mTrack->stop();
5303}
5304
5305void AudioFlinger::TrackHandle::flush() {
5306 mTrack->flush();
5307}
5308
5309void AudioFlinger::TrackHandle::mute(bool e) {
5310 mTrack->mute(e);
5311}
5312
5313void AudioFlinger::TrackHandle::pause() {
5314 mTrack->pause();
5315}
5316
Mathias Agopian65ab4712010-07-14 17:59:35 -07005317status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5318{
5319 return mTrack->attachAuxEffect(EffectId);
5320}
5321
John Grossman4ff14ba2012-02-08 16:37:41 -08005322status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5323 sp<IMemory>* buffer) {
5324 if (!mTrack->isTimedTrack())
5325 return INVALID_OPERATION;
5326
5327 PlaybackThread::TimedTrack* tt =
5328 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5329 return tt->allocateTimedBuffer(size, buffer);
5330}
5331
5332status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5333 int64_t pts) {
5334 if (!mTrack->isTimedTrack())
5335 return INVALID_OPERATION;
5336
5337 PlaybackThread::TimedTrack* tt =
5338 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5339 return tt->queueTimedBuffer(buffer, pts);
5340}
5341
5342status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5343 const LinearTransform& xform, int target) {
5344
5345 if (!mTrack->isTimedTrack())
5346 return INVALID_OPERATION;
5347
5348 PlaybackThread::TimedTrack* tt =
5349 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5350 return tt->setMediaTimeTransform(
5351 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5352}
5353
Mathias Agopian65ab4712010-07-14 17:59:35 -07005354status_t AudioFlinger::TrackHandle::onTransact(
5355 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5356{
5357 return BnAudioTrack::onTransact(code, data, reply, flags);
5358}
5359
5360// ----------------------------------------------------------------------------
5361
5362sp<IAudioRecord> AudioFlinger::openRecord(
5363 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005364 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005365 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005366 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005367 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005368 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005369 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005370 int *sessionId,
5371 status_t *status)
5372{
5373 sp<RecordThread::RecordTrack> recordTrack;
5374 sp<RecordHandle> recordHandle;
5375 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005376 status_t lStatus;
5377 RecordThread *thread;
5378 size_t inFrameCount;
5379 int lSessionId;
5380
5381 // check calling permissions
5382 if (!recordingAllowed()) {
5383 lStatus = PERMISSION_DENIED;
5384 goto Exit;
5385 }
5386
5387 // add client to list
5388 { // scope for mLock
5389 Mutex::Autolock _l(mLock);
5390 thread = checkRecordThread_l(input);
5391 if (thread == NULL) {
5392 lStatus = BAD_VALUE;
5393 goto Exit;
5394 }
5395
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005396 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005397
5398 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005399 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005400 lSessionId = *sessionId;
5401 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005402 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005403 if (sessionId != NULL) {
5404 *sessionId = lSessionId;
5405 }
5406 }
5407 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005408 recordTrack = thread->createRecordTrack_l(client,
5409 sampleRate,
5410 format,
5411 channelMask,
5412 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005413 lSessionId,
5414 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005415 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005416 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005417 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5418 // destructor is called by the TrackBase destructor with mLock held
5419 client.clear();
5420 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005421 goto Exit;
5422 }
5423
5424 // return to handle to client
5425 recordHandle = new RecordHandle(recordTrack);
5426 lStatus = NO_ERROR;
5427
5428Exit:
5429 if (status) {
5430 *status = lStatus;
5431 }
5432 return recordHandle;
5433}
5434
5435// ----------------------------------------------------------------------------
5436
5437AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5438 : BnAudioRecord(),
5439 mRecordTrack(recordTrack)
5440{
5441}
5442
5443AudioFlinger::RecordHandle::~RecordHandle() {
5444 stop();
5445}
5446
Glenn Kasten90716c52012-01-26 13:40:12 -08005447sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5448 return mRecordTrack->getCblk();
5449}
5450
Glenn Kasten3acbd052012-02-28 10:39:56 -08005451status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005452 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005453 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005454}
5455
5456void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005457 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005458 mRecordTrack->stop();
5459}
5460
Mathias Agopian65ab4712010-07-14 17:59:35 -07005461status_t AudioFlinger::RecordHandle::onTransact(
5462 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5463{
5464 return BnAudioRecord::onTransact(code, data, reply, flags);
5465}
5466
5467// ----------------------------------------------------------------------------
5468
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005469AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5470 AudioStreamIn *input,
5471 uint32_t sampleRate,
5472 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005473 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005474 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005475 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005476 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5477 // mRsmpInIndex and mInputBytes set by readInputParameters()
5478 mReqChannelCount(popcount(channels)),
5479 mReqSampleRate(sampleRate)
5480 // mBytesRead is only meaningful while active, and so is cleared in start()
5481 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005482{
Glenn Kasten480b4682012-02-28 12:30:08 -08005483 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005484
Mathias Agopian65ab4712010-07-14 17:59:35 -07005485 readInputParameters();
5486}
5487
5488
5489AudioFlinger::RecordThread::~RecordThread()
5490{
5491 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005492 delete mResampler;
5493 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005494}
5495
5496void AudioFlinger::RecordThread::onFirstRef()
5497{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005498 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005499}
5500
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005501status_t AudioFlinger::RecordThread::readyToRun()
5502{
5503 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005504 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005505 return status;
5506}
5507
Mathias Agopian65ab4712010-07-14 17:59:35 -07005508bool AudioFlinger::RecordThread::threadLoop()
5509{
5510 AudioBufferProvider::Buffer buffer;
5511 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005512 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005513
Eric Laurent44d98482010-09-30 16:12:31 -07005514 nsecs_t lastWarning = 0;
5515
Eric Laurentfeb0db62011-07-22 09:04:31 -07005516 acquireWakeLock();
5517
Mathias Agopian65ab4712010-07-14 17:59:35 -07005518 // start recording
5519 while (!exitPending()) {
5520
5521 processConfigEvents();
5522
5523 { // scope for mLock
5524 Mutex::Autolock _l(mLock);
5525 checkForNewParameters_l();
5526 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5527 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005528 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005529 mStandby = true;
5530 }
5531
5532 if (exitPending()) break;
5533
Eric Laurentfeb0db62011-07-22 09:04:31 -07005534 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005535 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005536 // go to sleep
5537 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005538 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005539 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005540 continue;
5541 }
5542 if (mActiveTrack != 0) {
5543 if (mActiveTrack->mState == TrackBase::PAUSING) {
5544 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005545 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005546 mStandby = true;
5547 }
5548 mActiveTrack.clear();
5549 mStartStopCond.broadcast();
5550 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5551 if (mReqChannelCount != mActiveTrack->channelCount()) {
5552 mActiveTrack.clear();
5553 mStartStopCond.broadcast();
5554 } else if (mBytesRead != 0) {
5555 // record start succeeds only if first read from audio input
5556 // succeeds
5557 if (mBytesRead > 0) {
5558 mActiveTrack->mState = TrackBase::ACTIVE;
5559 } else {
5560 mActiveTrack.clear();
5561 }
5562 mStartStopCond.broadcast();
5563 }
5564 mStandby = false;
5565 }
5566 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005567 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005568 }
5569
5570 if (mActiveTrack != 0) {
5571 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5572 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005573 unlockEffectChains(effectChains);
5574 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005575 continue;
5576 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005577 for (size_t i = 0; i < effectChains.size(); i ++) {
5578 effectChains[i]->process_l();
5579 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005580
Mathias Agopian65ab4712010-07-14 17:59:35 -07005581 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005582 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005583 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08005584 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005585 // no resampling
5586 while (framesOut) {
5587 size_t framesIn = mFrameCount - mRsmpInIndex;
5588 if (framesIn) {
5589 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5590 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5591 if (framesIn > framesOut)
5592 framesIn = framesOut;
5593 mRsmpInIndex += framesIn;
5594 framesOut -= framesIn;
5595 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07005596 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005597 memcpy(dst, src, framesIn * mFrameSize);
5598 } else {
5599 int16_t *src16 = (int16_t *)src;
5600 int16_t *dst16 = (int16_t *)dst;
5601 if (mChannelCount == 1) {
5602 while (framesIn--) {
5603 *dst16++ = *src16;
5604 *dst16++ = *src16++;
5605 }
5606 } else {
5607 while (framesIn--) {
5608 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5609 src16 += 2;
5610 }
5611 }
5612 }
5613 }
5614 if (framesOut && mFrameCount == mRsmpInIndex) {
5615 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005616 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005617 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005618 framesOut = 0;
5619 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005620 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005621 mRsmpInIndex = 0;
5622 }
5623 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005624 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005625 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5626 // Force input into standby so that it tries to
5627 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005628 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005629 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005630 }
5631 mRsmpInIndex = mFrameCount;
5632 framesOut = 0;
5633 buffer.frameCount = 0;
5634 }
5635 }
5636 }
5637 } else {
5638 // resampling
5639
5640 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5641 // alter output frame count as if we were expecting stereo samples
5642 if (mChannelCount == 1 && mReqChannelCount == 1) {
5643 framesOut >>= 1;
5644 }
5645 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5646 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5647 // are 32 bit aligned which should be always true.
5648 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005649 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005650 // the resampler always outputs stereo samples: do post stereo to mono conversion
5651 int16_t *src = (int16_t *)mRsmpOutBuffer;
5652 int16_t *dst = buffer.i16;
5653 while (framesOut--) {
5654 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5655 src += 2;
5656 }
5657 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005658 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005659 }
5660
5661 }
Eric Laurenta011e352012-03-29 15:51:43 -07005662 if (mFramestoDrop == 0) {
5663 mActiveTrack->releaseBuffer(&buffer);
5664 } else {
5665 if (mFramestoDrop > 0) {
5666 mFramestoDrop -= buffer.frameCount;
5667 if (mFramestoDrop < 0) {
5668 mFramestoDrop = 0;
5669 }
5670 }
5671 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005672 mActiveTrack->overflow();
5673 }
5674 // client isn't retrieving buffers fast enough
5675 else {
Eric Laurent44d98482010-09-30 16:12:31 -07005676 if (!mActiveTrack->setOverflow()) {
5677 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08005678 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005679 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07005680 lastWarning = now;
5681 }
5682 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005683 // Release the processor for a while before asking for a new buffer.
5684 // This will give the application more chance to read from the buffer and
5685 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005686 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005687 }
5688 }
Eric Laurentec437d82011-07-26 20:54:46 -07005689 // enable changes in effect chain
5690 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005691 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005692 }
5693
5694 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005695 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005696 }
5697 mActiveTrack.clear();
5698
5699 mStartStopCond.broadcast();
5700
Eric Laurentfeb0db62011-07-22 09:04:31 -07005701 releaseWakeLock();
5702
Steve Block3856b092011-10-20 11:56:00 +01005703 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704 return false;
5705}
5706
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005707
5708sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5709 const sp<AudioFlinger::Client>& client,
5710 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005711 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005712 int channelMask,
5713 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005714 int sessionId,
5715 status_t *status)
5716{
5717 sp<RecordTrack> track;
5718 status_t lStatus;
5719
5720 lStatus = initCheck();
5721 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005722 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005723 goto Exit;
5724 }
5725
5726 { // scope for mLock
5727 Mutex::Autolock _l(mLock);
5728
5729 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005730 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005731
Glenn Kasten7378ca52012-01-20 13:44:40 -08005732 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005733 lStatus = NO_MEMORY;
5734 goto Exit;
5735 }
5736
5737 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005738 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5739 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005740 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005741 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5742 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005743 }
5744 lStatus = NO_ERROR;
5745
5746Exit:
5747 if (status) {
5748 *status = lStatus;
5749 }
5750 return track;
5751}
5752
Eric Laurenta011e352012-03-29 15:51:43 -07005753status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08005754 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005755 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005756{
Glenn Kasten58912562012-04-03 10:45:00 -07005757 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005758 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005759 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07005760
5761 if (event == AudioSystem::SYNC_EVENT_NONE) {
5762 mSyncStartEvent.clear();
5763 mFramestoDrop = 0;
5764 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
5765 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
5766 triggerSession,
5767 recordTrack->sessionId(),
5768 syncStartEventCallback,
5769 this);
5770 mFramestoDrop = -1;
5771 }
5772
Mathias Agopian65ab4712010-07-14 17:59:35 -07005773 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005774 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005775 if (mActiveTrack != 0) {
5776 if (recordTrack != mActiveTrack.get()) {
5777 status = -EBUSY;
5778 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5779 mActiveTrack->mState = TrackBase::ACTIVE;
5780 }
5781 return status;
5782 }
5783
5784 recordTrack->mState = TrackBase::IDLE;
5785 mActiveTrack = recordTrack;
5786 mLock.unlock();
5787 status_t status = AudioSystem::startInput(mId);
5788 mLock.lock();
5789 if (status != NO_ERROR) {
5790 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07005791 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005792 return status;
5793 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005794 mRsmpInIndex = mFrameCount;
5795 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005796 if (mResampler != NULL) {
5797 mResampler->reset();
5798 }
5799 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005800 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005801 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005802 mWaitWorkCV.signal();
5803 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005804 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005805 mActiveTrack.clear();
5806 status = INVALID_OPERATION;
5807 goto startError;
5808 }
5809 mStartStopCond.wait(mLock);
5810 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005811 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005812 status = BAD_VALUE;
5813 goto startError;
5814 }
Steve Block3856b092011-10-20 11:56:00 +01005815 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005816 return status;
5817 }
5818startError:
5819 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07005820 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005821 return status;
5822}
5823
Eric Laurenta011e352012-03-29 15:51:43 -07005824void AudioFlinger::RecordThread::clearSyncStartEvent()
5825{
5826 if (mSyncStartEvent != 0) {
5827 mSyncStartEvent->cancel();
5828 }
5829 mSyncStartEvent.clear();
5830}
5831
5832void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5833{
5834 sp<SyncEvent> strongEvent = event.promote();
5835
5836 if (strongEvent != 0) {
5837 RecordThread *me = (RecordThread *)strongEvent->cookie();
5838 me->handleSyncStartEvent(strongEvent);
5839 }
5840}
5841
5842void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
5843{
5844 ALOGV("handleSyncStartEvent() mActiveTrack %p session %d event->listenerSession() %d",
5845 mActiveTrack.get(),
5846 mActiveTrack.get() ? mActiveTrack->sessionId() : 0,
5847 event->listenerSession());
5848
5849 if (mActiveTrack != 0 &&
5850 event == mSyncStartEvent) {
5851 // TODO: use actual buffer filling status instead of 2 buffers when info is available
5852 // from audio HAL
5853 mFramestoDrop = mFrameCount * 2;
5854 mSyncStartEvent.clear();
5855 }
5856}
5857
Mathias Agopian65ab4712010-07-14 17:59:35 -07005858void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005859 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005860 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005861 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005862 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005863 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5864 mActiveTrack->mState = TrackBase::PAUSING;
5865 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005866 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005867 return;
5868 }
5869 mStartStopCond.wait(mLock);
5870 // if we have been restarted, recordTrack == mActiveTrack.get() here
5871 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5872 mLock.unlock();
5873 AudioSystem::stopInput(mId);
5874 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005875 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005876 }
5877 }
5878 }
5879}
5880
Eric Laurenta011e352012-03-29 15:51:43 -07005881bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
5882{
5883 return false;
5884}
5885
5886status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
5887{
5888 if (!isValidSyncEvent(event)) {
5889 return BAD_VALUE;
5890 }
5891
5892 Mutex::Autolock _l(mLock);
5893
5894 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
5895 mTrack->setSyncEvent(event);
5896 return NO_ERROR;
5897 }
5898 return NAME_NOT_FOUND;
5899}
5900
Mathias Agopian65ab4712010-07-14 17:59:35 -07005901status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5902{
5903 const size_t SIZE = 256;
5904 char buffer[SIZE];
5905 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005906
5907 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5908 result.append(buffer);
5909
5910 if (mActiveTrack != 0) {
5911 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005912 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005913 mActiveTrack->dump(buffer, SIZE);
5914 result.append(buffer);
5915
5916 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5917 result.append(buffer);
5918 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5919 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005920 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005921 result.append(buffer);
5922 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5923 result.append(buffer);
5924 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5925 result.append(buffer);
5926
5927
5928 } else {
5929 result.append("No record client\n");
5930 }
5931 write(fd, result.string(), result.size());
5932
5933 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005934 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005935
5936 return NO_ERROR;
5937}
5938
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005939// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005940status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005941{
5942 size_t framesReq = buffer->frameCount;
5943 size_t framesReady = mFrameCount - mRsmpInIndex;
5944 int channelCount;
5945
5946 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005947 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005948 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005949 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005950 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5951 // Force input into standby so that it tries to
5952 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005953 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005954 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005955 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005956 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005957 buffer->frameCount = 0;
5958 return NOT_ENOUGH_DATA;
5959 }
5960 mRsmpInIndex = 0;
5961 framesReady = mFrameCount;
5962 }
5963
5964 if (framesReq > framesReady) {
5965 framesReq = framesReady;
5966 }
5967
5968 if (mChannelCount == 1 && mReqChannelCount == 2) {
5969 channelCount = 1;
5970 } else {
5971 channelCount = 2;
5972 }
5973 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5974 buffer->frameCount = framesReq;
5975 return NO_ERROR;
5976}
5977
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005978// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07005979void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5980{
5981 mRsmpInIndex += buffer->frameCount;
5982 buffer->frameCount = 0;
5983}
5984
5985bool AudioFlinger::RecordThread::checkForNewParameters_l()
5986{
5987 bool reconfig = false;
5988
5989 while (!mNewParameters.isEmpty()) {
5990 status_t status = NO_ERROR;
5991 String8 keyValuePair = mNewParameters[0];
5992 AudioParameter param = AudioParameter(keyValuePair);
5993 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08005994 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005995 int reqSamplingRate = mReqSampleRate;
5996 int reqChannelCount = mReqChannelCount;
5997
5998 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5999 reqSamplingRate = value;
6000 reconfig = true;
6001 }
6002 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006003 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006004 reconfig = true;
6005 }
6006 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006007 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006008 reconfig = true;
6009 }
6010 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6011 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006012 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006013 // if frame count is changed after track creation
6014 if (mActiveTrack != 0) {
6015 status = INVALID_OPERATION;
6016 } else {
6017 reconfig = true;
6018 }
6019 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006020 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6021 // forward device change to effects that have requested to be
6022 // aware of attached audio device.
6023 for (size_t i = 0; i < mEffectChains.size(); i++) {
6024 mEffectChains[i]->setDevice_l(value);
6025 }
6026 // store input device and output device but do not forward output device to audio HAL.
6027 // Note that status is ignored by the caller for output device
6028 // (see AudioFlinger::setParameters()
6029 if (value & AUDIO_DEVICE_OUT_ALL) {
6030 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6031 status = BAD_VALUE;
6032 } else {
6033 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006034 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6035 if (mTrack != NULL) {
6036 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006037 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006038 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6039 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6040 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006041 }
6042 mDevice |= (uint32_t)value;
6043 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006044 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006045 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006046 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006047 mInput->stream->common.standby(&mInput->stream->common);
6048 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6049 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006050 }
6051 if (reconfig) {
6052 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006053 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006054 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006055 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006056 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6057 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006058 status = NO_ERROR;
6059 }
6060 if (status == NO_ERROR) {
6061 readInputParameters();
6062 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6063 }
6064 }
6065 }
6066
6067 mNewParameters.removeAt(0);
6068
6069 mParamStatus = status;
6070 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006071 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6072 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006073 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074 }
6075 return reconfig;
6076}
6077
6078String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6079{
Dima Zavinfce7a472011-04-19 22:30:36 -07006080 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006081 String8 out_s8 = String8();
6082
6083 Mutex::Autolock _l(mLock);
6084 if (initCheck() != NO_ERROR) {
6085 return out_s8;
6086 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006087
Dima Zavin799a70e2011-04-18 16:57:27 -07006088 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006089 out_s8 = String8(s);
6090 free(s);
6091 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006092}
6093
6094void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6095 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006096 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006097
6098 switch (event) {
6099 case AudioSystem::INPUT_OPENED:
6100 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006101 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006102 desc.samplingRate = mSampleRate;
6103 desc.format = mFormat;
6104 desc.frameCount = mFrameCount;
6105 desc.latency = 0;
6106 param2 = &desc;
6107 break;
6108
6109 case AudioSystem::INPUT_CLOSED:
6110 default:
6111 break;
6112 }
6113 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6114}
6115
6116void AudioFlinger::RecordThread::readInputParameters()
6117{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006118 delete mRsmpInBuffer;
6119 // mRsmpInBuffer is always assigned a new[] below
6120 delete mRsmpOutBuffer;
6121 mRsmpOutBuffer = NULL;
6122 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006123 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006124
Dima Zavin799a70e2011-04-18 16:57:27 -07006125 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006126 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6127 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006128 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006129 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006130 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006131 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006132 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006133 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6134
Glenn Kasten53d76db2012-03-08 12:32:47 -08006135 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006136 {
6137 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006138 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6139 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006140 if (mChannelCount == 1 && mReqChannelCount == 2) {
6141 channelCount = 1;
6142 } else {
6143 channelCount = 2;
6144 }
6145 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6146 mResampler->setSampleRate(mSampleRate);
6147 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6148 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6149
6150 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6151 if (mChannelCount == 1 && mReqChannelCount == 1) {
6152 mFrameCount >>= 1;
6153 }
6154
6155 }
6156 mRsmpInIndex = mFrameCount;
6157}
6158
6159unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6160{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006161 Mutex::Autolock _l(mLock);
6162 if (initCheck() != NO_ERROR) {
6163 return 0;
6164 }
6165
Dima Zavin799a70e2011-04-18 16:57:27 -07006166 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006167}
6168
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006169uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6170{
6171 Mutex::Autolock _l(mLock);
6172 uint32_t result = 0;
6173 if (getEffectChain_l(sessionId) != 0) {
6174 result = EFFECT_SESSION;
6175 }
6176
6177 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6178 result |= TRACK_SESSION;
6179 }
6180
6181 return result;
6182}
6183
Eric Laurent59bd0da2011-08-01 09:52:20 -07006184AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6185{
6186 Mutex::Autolock _l(mLock);
6187 return mTrack;
6188}
6189
Glenn Kastenaed850d2012-01-26 09:46:34 -08006190AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006191{
6192 Mutex::Autolock _l(mLock);
6193 return mInput;
6194}
6195
6196AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6197{
6198 Mutex::Autolock _l(mLock);
6199 AudioStreamIn *input = mInput;
6200 mInput = NULL;
6201 return input;
6202}
6203
6204// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006205audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006206{
6207 if (mInput == NULL) {
6208 return NULL;
6209 }
6210 return &mInput->stream->common;
6211}
6212
6213
Mathias Agopian65ab4712010-07-14 17:59:35 -07006214// ----------------------------------------------------------------------------
6215
Eric Laurenta4c5a552012-03-29 10:12:40 -07006216audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6217{
6218 if (!settingsAllowed()) {
6219 return 0;
6220 }
6221 Mutex::Autolock _l(mLock);
6222 return loadHwModule_l(name);
6223}
6224
6225// loadHwModule_l() must be called with AudioFlinger::mLock held
6226audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6227{
6228 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6229 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6230 ALOGW("loadHwModule() module %s already loaded", name);
6231 return mAudioHwDevs.keyAt(i);
6232 }
6233 }
6234
Eric Laurenta4c5a552012-03-29 10:12:40 -07006235 audio_hw_device_t *dev;
6236
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006237 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006238 if (rc) {
6239 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6240 return 0;
6241 }
6242
6243 mHardwareStatus = AUDIO_HW_INIT;
6244 rc = dev->init_check(dev);
6245 mHardwareStatus = AUDIO_HW_IDLE;
6246 if (rc) {
6247 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6248 return 0;
6249 }
6250
6251 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6252 (NULL != dev->set_master_volume)) {
6253 AutoMutex lock(mHardwareLock);
6254 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6255 dev->set_master_volume(dev, mMasterVolume);
6256 mHardwareStatus = AUDIO_HW_IDLE;
6257 }
6258
6259 audio_module_handle_t handle = nextUniqueId();
6260 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6261
6262 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006263 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006264
6265 return handle;
6266
6267}
6268
6269audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6270 audio_devices_t *pDevices,
6271 uint32_t *pSamplingRate,
6272 audio_format_t *pFormat,
6273 audio_channel_mask_t *pChannelMask,
6274 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006275 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006276{
6277 status_t status;
6278 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006279 struct audio_config config = {
6280 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6281 channel_mask: pChannelMask ? *pChannelMask : 0,
6282 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6283 };
6284 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006285 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006286
Eric Laurenta4c5a552012-03-29 10:12:40 -07006287 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6288 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006289 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006290 config.sample_rate,
6291 config.format,
6292 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006293 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006294
6295 if (pDevices == NULL || *pDevices == 0) {
6296 return 0;
6297 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006298
Mathias Agopian65ab4712010-07-14 17:59:35 -07006299 Mutex::Autolock _l(mLock);
6300
Eric Laurenta4c5a552012-03-29 10:12:40 -07006301 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006302 if (outHwDev == NULL)
6303 return 0;
6304
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006305 audio_io_handle_t id = nextUniqueId();
6306
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006307 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006308
6309 status = outHwDev->open_output_stream(outHwDev,
6310 id,
6311 *pDevices,
6312 (audio_output_flags_t)flags,
6313 &config,
6314 &outStream);
6315
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006316 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006317 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006318 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006319 config.sample_rate,
6320 config.format,
6321 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006322 status);
6323
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006324 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006325 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006326
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006327 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006328 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6329 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006330 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006331 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006332 } else {
6333 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006334 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006335 }
6336 mPlaybackThreads.add(id, thread);
6337
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006338 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6339 if (pFormat != NULL) *pFormat = config.format;
6340 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006341 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006342
6343 // notify client processes of the new output creation
6344 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006345
6346 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006347 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006348 ALOGI("Using module %d has the primary audio interface", module);
6349 mPrimaryHardwareDev = outHwDev;
6350
6351 AutoMutex lock(mHardwareLock);
6352 mHardwareStatus = AUDIO_HW_SET_MODE;
6353 outHwDev->set_mode(outHwDev, mMode);
6354
6355 // Determine the level of master volume support the primary audio HAL has,
6356 // and set the initial master volume at the same time.
6357 float initialVolume = 1.0;
6358 mMasterVolumeSupportLvl = MVS_NONE;
6359
6360 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6361 if ((NULL != outHwDev->get_master_volume) &&
6362 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6363 mMasterVolumeSupportLvl = MVS_FULL;
6364 } else {
6365 mMasterVolumeSupportLvl = MVS_SETONLY;
6366 initialVolume = 1.0;
6367 }
6368
6369 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6370 if ((NULL == outHwDev->set_master_volume) ||
6371 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6372 mMasterVolumeSupportLvl = MVS_NONE;
6373 }
6374 // now that we have a primary device, initialize master volume on other devices
6375 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6376 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6377
6378 if ((dev != mPrimaryHardwareDev) &&
6379 (NULL != dev->set_master_volume)) {
6380 dev->set_master_volume(dev, initialVolume);
6381 }
6382 }
6383 mHardwareStatus = AUDIO_HW_IDLE;
6384 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6385 ? initialVolume
6386 : 1.0;
6387 mMasterVolume = initialVolume;
6388 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006389 return id;
6390 }
6391
6392 return 0;
6393}
6394
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006395audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6396 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006397{
6398 Mutex::Autolock _l(mLock);
6399 MixerThread *thread1 = checkMixerThread_l(output1);
6400 MixerThread *thread2 = checkMixerThread_l(output2);
6401
6402 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006403 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006404 return 0;
6405 }
6406
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006407 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006408 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6409 thread->addOutputTrack(thread2);
6410 mPlaybackThreads.add(id, thread);
6411 // notify client processes of the new output creation
6412 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6413 return id;
6414}
6415
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006416status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006417{
6418 // keep strong reference on the playback thread so that
6419 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006420 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006421 {
6422 Mutex::Autolock _l(mLock);
6423 thread = checkPlaybackThread_l(output);
6424 if (thread == NULL) {
6425 return BAD_VALUE;
6426 }
6427
Steve Block3856b092011-10-20 11:56:00 +01006428 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006429
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006430 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006431 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006432 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006433 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6434 dupThread->removeOutputTrack((MixerThread *)thread.get());
6435 }
6436 }
6437 }
Glenn Kastena1117922012-01-26 10:53:32 -08006438 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006439 mPlaybackThreads.removeItem(output);
6440 }
6441 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006442 // The thread entity (active unit of execution) is no longer running here,
6443 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006444
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006445 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006446 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006447 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006448 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006449 out->hwDev->close_output_stream(out->hwDev, out->stream);
6450 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006451 }
6452 return NO_ERROR;
6453}
6454
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006455status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006456{
6457 Mutex::Autolock _l(mLock);
6458 PlaybackThread *thread = checkPlaybackThread_l(output);
6459
6460 if (thread == NULL) {
6461 return BAD_VALUE;
6462 }
6463
Steve Block3856b092011-10-20 11:56:00 +01006464 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006465 thread->suspend();
6466
6467 return NO_ERROR;
6468}
6469
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006470status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006471{
6472 Mutex::Autolock _l(mLock);
6473 PlaybackThread *thread = checkPlaybackThread_l(output);
6474
6475 if (thread == NULL) {
6476 return BAD_VALUE;
6477 }
6478
Steve Block3856b092011-10-20 11:56:00 +01006479 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006480
6481 thread->restore();
6482
6483 return NO_ERROR;
6484}
6485
Eric Laurenta4c5a552012-03-29 10:12:40 -07006486audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6487 audio_devices_t *pDevices,
6488 uint32_t *pSamplingRate,
6489 audio_format_t *pFormat,
6490 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006491{
6492 status_t status;
6493 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006494 struct audio_config config = {
6495 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6496 channel_mask: pChannelMask ? *pChannelMask : 0,
6497 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6498 };
6499 uint32_t reqSamplingRate = config.sample_rate;
6500 audio_format_t reqFormat = config.format;
6501 audio_channel_mask_t reqChannels = config.channel_mask;
6502 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006503 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006504
6505 if (pDevices == NULL || *pDevices == 0) {
6506 return 0;
6507 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006508
Mathias Agopian65ab4712010-07-14 17:59:35 -07006509 Mutex::Autolock _l(mLock);
6510
Eric Laurenta4c5a552012-03-29 10:12:40 -07006511 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006512 if (inHwDev == NULL)
6513 return 0;
6514
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006515 audio_io_handle_t id = nextUniqueId();
6516
6517 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006518 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006519 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006520 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006521 config.sample_rate,
6522 config.format,
6523 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006524 status);
6525
6526 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6527 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6528 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006529 if (status == BAD_VALUE &&
6530 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6531 (config.sample_rate <= 2 * reqSamplingRate) &&
6532 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006533 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006534 inStream = NULL;
6535 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006536 }
6537
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006538 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006539 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6540
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006541 // Start record thread
6542 // RecorThread require both input and output device indication to forward to audio
6543 // pre processing modules
6544 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6545 thread = new RecordThread(this,
6546 input,
6547 reqSamplingRate,
6548 reqChannels,
6549 id,
6550 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006551 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006552 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006553 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006554 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006555 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006556
Dima Zavin799a70e2011-04-18 16:57:27 -07006557 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006558
6559 // notify client processes of the new input creation
6560 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6561 return id;
6562 }
6563
6564 return 0;
6565}
6566
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006567status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006568{
6569 // keep strong reference on the record thread so that
6570 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006571 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006572 {
6573 Mutex::Autolock _l(mLock);
6574 thread = checkRecordThread_l(input);
6575 if (thread == NULL) {
6576 return BAD_VALUE;
6577 }
6578
Steve Block3856b092011-10-20 11:56:00 +01006579 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08006580 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006581 mRecordThreads.removeItem(input);
6582 }
6583 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006584 // The thread entity (active unit of execution) is no longer running here,
6585 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006586
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006587 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006588 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006589 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006590 in->hwDev->close_input_stream(in->hwDev, in->stream);
6591 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006592
6593 return NO_ERROR;
6594}
6595
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006596status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006597{
6598 Mutex::Autolock _l(mLock);
6599 MixerThread *dstThread = checkMixerThread_l(output);
6600 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006601 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006602 return BAD_VALUE;
6603 }
6604
Steve Block3856b092011-10-20 11:56:00 +01006605 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006606 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
6607
6608 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6609 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08006610 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006611 MixerThread *srcThread = (MixerThread *)thread;
6612 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006613 }
Eric Laurentde070132010-07-13 04:45:46 -07006614 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006615
6616 return NO_ERROR;
6617}
6618
6619
6620int AudioFlinger::newAudioSessionId()
6621{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006622 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006623}
6624
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006625void AudioFlinger::acquireAudioSessionId(int audioSession)
6626{
6627 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006628 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006629 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006630 size_t num = mAudioSessionRefs.size();
6631 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006632 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006633 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6634 ref->mCnt++;
6635 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006636 return;
6637 }
6638 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006639 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6640 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006641}
6642
6643void AudioFlinger::releaseAudioSessionId(int audioSession)
6644{
6645 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006646 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006647 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006648 size_t num = mAudioSessionRefs.size();
6649 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006650 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006651 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6652 ref->mCnt--;
6653 ALOGV(" decremented refcount to %d", ref->mCnt);
6654 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006655 mAudioSessionRefs.removeAt(i);
6656 delete ref;
6657 purgeStaleEffects_l();
6658 }
6659 return;
6660 }
6661 }
Steve Block5ff1dd52012-01-05 23:22:43 +00006662 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006663}
6664
6665void AudioFlinger::purgeStaleEffects_l() {
6666
Steve Block3856b092011-10-20 11:56:00 +01006667 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006668
6669 Vector< sp<EffectChain> > chains;
6670
6671 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6672 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6673 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6674 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07006675 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6676 chains.push(ec);
6677 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006678 }
6679 }
6680 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6681 sp<RecordThread> t = mRecordThreads.valueAt(i);
6682 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6683 sp<EffectChain> ec = t->mEffectChains[j];
6684 chains.push(ec);
6685 }
6686 }
6687
6688 for (size_t i = 0; i < chains.size(); i++) {
6689 sp<EffectChain> ec = chains[i];
6690 int sessionid = ec->sessionId();
6691 sp<ThreadBase> t = ec->mThread.promote();
6692 if (t == 0) {
6693 continue;
6694 }
6695 size_t numsessionrefs = mAudioSessionRefs.size();
6696 bool found = false;
6697 for (size_t k = 0; k < numsessionrefs; k++) {
6698 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006699 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01006700 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006701 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006702 found = true;
6703 break;
6704 }
6705 }
6706 if (!found) {
6707 // remove all effects from the chain
6708 while (ec->mEffects.size()) {
6709 sp<EffectModule> effect = ec->mEffects[0];
6710 effect->unPin();
6711 Mutex::Autolock _l (t->mLock);
6712 t->removeEffect_l(effect);
6713 for (size_t j = 0; j < effect->mHandles.size(); j++) {
6714 sp<EffectHandle> handle = effect->mHandles[j].promote();
6715 if (handle != 0) {
6716 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07006717 if (handle->mHasControl && handle->mEnabled) {
6718 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
6719 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006720 }
6721 }
6722 AudioSystem::unregisterEffect(effect->id());
6723 }
6724 }
6725 }
6726 return;
6727}
6728
Mathias Agopian65ab4712010-07-14 17:59:35 -07006729// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006730AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006731{
Glenn Kastena1117922012-01-26 10:53:32 -08006732 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006733}
6734
6735// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006736AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006737{
6738 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08006739 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006740}
6741
6742// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006743AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006744{
Glenn Kastena1117922012-01-26 10:53:32 -08006745 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006746}
6747
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006748uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07006749{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006750 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006751}
6752
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006753AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006754{
6755 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6756 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006757 AudioStreamOut *output = thread->getOutput();
6758 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006759 return thread;
6760 }
6761 }
6762 return NULL;
6763}
6764
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006765uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006766{
6767 PlaybackThread *thread = primaryPlaybackThread_l();
6768
6769 if (thread == NULL) {
6770 return 0;
6771 }
6772
6773 return thread->device();
6774}
6775
Eric Laurenta011e352012-03-29 15:51:43 -07006776sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
6777 int triggerSession,
6778 int listenerSession,
6779 sync_event_callback_t callBack,
6780 void *cookie)
6781{
6782 Mutex::Autolock _l(mLock);
6783
6784 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
6785 status_t playStatus = NAME_NOT_FOUND;
6786 status_t recStatus = NAME_NOT_FOUND;
6787 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6788 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
6789 if (playStatus == NO_ERROR) {
6790 return event;
6791 }
6792 }
6793 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6794 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
6795 if (recStatus == NO_ERROR) {
6796 return event;
6797 }
6798 }
6799 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
6800 mPendingSyncEvents.add(event);
6801 } else {
6802 ALOGV("createSyncEvent() invalid event %d", event->type());
6803 event.clear();
6804 }
6805 return event;
6806}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006807
Mathias Agopian65ab4712010-07-14 17:59:35 -07006808// ----------------------------------------------------------------------------
6809// Effect management
6810// ----------------------------------------------------------------------------
6811
6812
Glenn Kastenf587ba52012-01-26 16:25:10 -08006813status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006814{
6815 Mutex::Autolock _l(mLock);
6816 return EffectQueryNumberEffects(numEffects);
6817}
6818
Glenn Kastenf587ba52012-01-26 16:25:10 -08006819status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006820{
6821 Mutex::Autolock _l(mLock);
6822 return EffectQueryEffect(index, descriptor);
6823}
6824
Glenn Kasten5e92a782012-01-30 07:40:52 -08006825status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08006826 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006827{
6828 Mutex::Autolock _l(mLock);
6829 return EffectGetDescriptor(pUuid, descriptor);
6830}
6831
6832
Mathias Agopian65ab4712010-07-14 17:59:35 -07006833sp<IEffect> AudioFlinger::createEffect(pid_t pid,
6834 effect_descriptor_t *pDesc,
6835 const sp<IEffectClient>& effectClient,
6836 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006837 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006838 int sessionId,
6839 status_t *status,
6840 int *id,
6841 int *enabled)
6842{
6843 status_t lStatus = NO_ERROR;
6844 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006845 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006846
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006847 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006848 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006849
6850 if (pDesc == NULL) {
6851 lStatus = BAD_VALUE;
6852 goto Exit;
6853 }
6854
Eric Laurent84e9a102010-09-23 16:10:16 -07006855 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006856 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006857 lStatus = PERMISSION_DENIED;
6858 goto Exit;
6859 }
6860
Dima Zavinfce7a472011-04-19 22:30:36 -07006861 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07006862 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08006863 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006864 lStatus = PERMISSION_DENIED;
6865 goto Exit;
6866 }
6867
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006868 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006869 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006870 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07006871 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07006872 lStatus = BAD_VALUE;
6873 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07006874 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006875 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006876 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07006877 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006878 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07006879 }
6880 }
6881
Mathias Agopian65ab4712010-07-14 17:59:35 -07006882 {
6883 Mutex::Autolock _l(mLock);
6884
Mathias Agopian65ab4712010-07-14 17:59:35 -07006885
6886 if (!EffectIsNullUuid(&pDesc->uuid)) {
6887 // if uuid is specified, request effect descriptor
6888 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
6889 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006890 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006891 goto Exit;
6892 }
6893 } else {
6894 // if uuid is not specified, look for an available implementation
6895 // of the required type in effect factory
6896 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006897 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006898 lStatus = BAD_VALUE;
6899 goto Exit;
6900 }
6901 uint32_t numEffects = 0;
6902 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006903 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07006904 bool found = false;
6905
6906 lStatus = EffectQueryNumberEffects(&numEffects);
6907 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006908 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006909 goto Exit;
6910 }
6911 for (uint32_t i = 0; i < numEffects; i++) {
6912 lStatus = EffectQueryEffect(i, &desc);
6913 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006914 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006915 continue;
6916 }
6917 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
6918 // If matching type found save effect descriptor. If the session is
6919 // 0 and the effect is not auxiliary, continue enumeration in case
6920 // an auxiliary version of this effect type is available
6921 found = true;
6922 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07006923 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006924 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6925 break;
6926 }
6927 }
6928 }
6929 if (!found) {
6930 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00006931 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006932 goto Exit;
6933 }
6934 // For same effect type, chose auxiliary version over insert version if
6935 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07006936 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006937 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6938 memcpy(&desc, &d, sizeof(effect_descriptor_t));
6939 }
6940 }
6941
6942 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07006943 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006944 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6945 lStatus = INVALID_OPERATION;
6946 goto Exit;
6947 }
6948
Eric Laurent59255e42011-07-27 19:49:51 -07006949 // check recording permission for visualizer
6950 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
6951 !recordingAllowed()) {
6952 lStatus = PERMISSION_DENIED;
6953 goto Exit;
6954 }
6955
Mathias Agopian65ab4712010-07-14 17:59:35 -07006956 // return effect descriptor
6957 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6958
6959 // If output is not specified try to find a matching audio session ID in one of the
6960 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07006961 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6962 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006963 // Note: io is never 0 when creating an effect on an input
6964 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006965 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07006966 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6967 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006968 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006969 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006970 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006971 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006972 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006973 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6974 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6975 io = mRecordThreads.keyAt(i);
6976 break;
6977 }
6978 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006979 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006980 // If no output thread contains the requested session ID, default to
6981 // first output. The effect chain will be moved to the correct output
6982 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006983 if (io == 0 && mPlaybackThreads.size()) {
6984 io = mPlaybackThreads.keyAt(0);
6985 }
Steve Block3856b092011-10-20 11:56:00 +01006986 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006987 }
6988 ThreadBase *thread = checkRecordThread_l(io);
6989 if (thread == NULL) {
6990 thread = checkPlaybackThread_l(io);
6991 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00006992 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006993 lStatus = BAD_VALUE;
6994 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006995 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006996 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006997
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006998 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006999
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007000 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007001 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7002 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007003 if (handle != 0 && id != NULL) {
7004 *id = handle->id();
7005 }
7006 }
7007
7008Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007009 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007010 *status = lStatus;
7011 }
7012 return handle;
7013}
7014
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007015status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7016 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007017{
Steve Block3856b092011-10-20 11:56:00 +01007018 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007019 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007020 Mutex::Autolock _l(mLock);
7021 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007022 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007023 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007024 }
Eric Laurentde070132010-07-13 04:45:46 -07007025 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7026 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007027 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007028 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007029 }
Eric Laurentde070132010-07-13 04:45:46 -07007030 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7031 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007032 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007033 return BAD_VALUE;
7034 }
7035
7036 Mutex::Autolock _dl(dstThread->mLock);
7037 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007038 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007039
Mathias Agopian65ab4712010-07-14 17:59:35 -07007040 return NO_ERROR;
7041}
7042
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007043// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007044status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007045 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007046 AudioFlinger::PlaybackThread *dstThread,
7047 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007048{
Steve Block3856b092011-10-20 11:56:00 +01007049 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007050 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007051
Eric Laurent59255e42011-07-27 19:49:51 -07007052 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007053 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007054 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007055 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007056 return INVALID_OPERATION;
7057 }
7058
Eric Laurent39e94f82010-07-28 01:32:47 -07007059 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007060 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007061 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007062 // removed.
7063 srcThread->removeEffectChain_l(chain);
7064
7065 // transfer all effects one by one so that new effect chain is created on new thread with
7066 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007067 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007068 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007069 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007070 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7071 while (effect != 0) {
7072 srcThread->removeEffect_l(effect);
7073 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007074 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7075 if (effect->state() == EffectModule::ACTIVE ||
7076 effect->state() == EffectModule::STOPPING) {
7077 effect->start();
7078 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007079 // if the move request is not received from audio policy manager, the effect must be
7080 // re-registered with the new strategy and output
7081 if (dstChain == 0) {
7082 dstChain = effect->chain().promote();
7083 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007084 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007085 srcThread->addEffect_l(effect);
7086 return NO_INIT;
7087 }
7088 strategy = dstChain->strategy();
7089 }
7090 if (reRegister) {
7091 AudioSystem::unregisterEffect(effect->id());
7092 AudioSystem::registerEffect(&effect->desc(),
7093 dstOutput,
7094 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007095 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007096 effect->id());
7097 }
Eric Laurentde070132010-07-13 04:45:46 -07007098 effect = chain->getEffectFromId_l(0);
7099 }
7100
7101 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007102}
7103
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007104
Mathias Agopian65ab4712010-07-14 17:59:35 -07007105// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007106sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007107 const sp<AudioFlinger::Client>& client,
7108 const sp<IEffectClient>& effectClient,
7109 int32_t priority,
7110 int sessionId,
7111 effect_descriptor_t *desc,
7112 int *enabled,
7113 status_t *status
7114 )
7115{
7116 sp<EffectModule> effect;
7117 sp<EffectHandle> handle;
7118 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007119 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007120 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007121 bool effectCreated = false;
7122 bool effectRegistered = false;
7123
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007124 lStatus = initCheck();
7125 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007126 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007127 goto Exit;
7128 }
7129
7130 // Do not allow effects with session ID 0 on direct output or duplicating threads
7131 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007132 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007133 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007134 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007135 lStatus = BAD_VALUE;
7136 goto Exit;
7137 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007138 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007139 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007140 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007141 desc->name, desc->flags, mType);
7142 lStatus = BAD_VALUE;
7143 goto Exit;
7144 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007145
Steve Block3856b092011-10-20 11:56:00 +01007146 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007147
7148 { // scope for mLock
7149 Mutex::Autolock _l(mLock);
7150
7151 // check for existing effect chain with the requested audio session
7152 chain = getEffectChain_l(sessionId);
7153 if (chain == 0) {
7154 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007155 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007156 chain = new EffectChain(this, sessionId);
7157 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007158 chain->setStrategy(getStrategyForSession_l(sessionId));
7159 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007160 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007161 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007162 }
7163
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007164 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007165
7166 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007167 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007168 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007169 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007170 if (lStatus != NO_ERROR) {
7171 goto Exit;
7172 }
7173 effectRegistered = true;
7174 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007175 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007176 lStatus = effect->status();
7177 if (lStatus != NO_ERROR) {
7178 goto Exit;
7179 }
Eric Laurentcab11242010-07-15 12:50:15 -07007180 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007181 if (lStatus != NO_ERROR) {
7182 goto Exit;
7183 }
7184 effectCreated = true;
7185
7186 effect->setDevice(mDevice);
7187 effect->setMode(mAudioFlinger->getMode());
7188 }
7189 // create effect handle and connect it to effect module
7190 handle = new EffectHandle(effect, client, effectClient, priority);
7191 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08007192 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007193 *enabled = (int)effect->isEnabled();
7194 }
7195 }
7196
7197Exit:
7198 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007199 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007200 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007201 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007202 }
7203 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007204 AudioSystem::unregisterEffect(effect->id());
7205 }
7206 if (chainCreated) {
7207 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007208 }
7209 handle.clear();
7210 }
7211
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007212 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007213 *status = lStatus;
7214 }
7215 return handle;
7216}
7217
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007218sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7219{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007220 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007221 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007222}
7223
Eric Laurentde070132010-07-13 04:45:46 -07007224// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7225// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007226status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007227{
7228 // check for existing effect chain with the requested audio session
7229 int sessionId = effect->sessionId();
7230 sp<EffectChain> chain = getEffectChain_l(sessionId);
7231 bool chainCreated = false;
7232
7233 if (chain == 0) {
7234 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007235 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007236 chain = new EffectChain(this, sessionId);
7237 addEffectChain_l(chain);
7238 chain->setStrategy(getStrategyForSession_l(sessionId));
7239 chainCreated = true;
7240 }
Steve Block3856b092011-10-20 11:56:00 +01007241 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007242
7243 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007244 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007245 this, effect->desc().name, chain.get());
7246 return BAD_VALUE;
7247 }
7248
7249 status_t status = chain->addEffect_l(effect);
7250 if (status != NO_ERROR) {
7251 if (chainCreated) {
7252 removeEffectChain_l(chain);
7253 }
7254 return status;
7255 }
7256
7257 effect->setDevice(mDevice);
7258 effect->setMode(mAudioFlinger->getMode());
7259 return NO_ERROR;
7260}
7261
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007262void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007263
Steve Block3856b092011-10-20 11:56:00 +01007264 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007265 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007266 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7267 detachAuxEffect_l(effect->id());
7268 }
7269
7270 sp<EffectChain> chain = effect->chain().promote();
7271 if (chain != 0) {
7272 // remove effect chain if removing last effect
7273 if (chain->removeEffect_l(effect) == 0) {
7274 removeEffectChain_l(chain);
7275 }
7276 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007277 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007278 }
7279}
7280
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007281void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007282 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007283{
7284 effectChains = mEffectChains;
7285 for (size_t i = 0; i < mEffectChains.size(); i++) {
7286 mEffectChains[i]->lock();
7287 }
7288}
7289
7290void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007291 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007292{
7293 for (size_t i = 0; i < effectChains.size(); i++) {
7294 effectChains[i]->unlock();
7295 }
7296}
7297
7298sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7299{
7300 Mutex::Autolock _l(mLock);
7301 return getEffectChain_l(sessionId);
7302}
7303
7304sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7305{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007306 size_t size = mEffectChains.size();
7307 for (size_t i = 0; i < size; i++) {
7308 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007309 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007310 }
7311 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007312 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007313}
7314
Glenn Kastenf78aee72012-01-04 11:00:47 -08007315void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007316{
7317 Mutex::Autolock _l(mLock);
7318 size_t size = mEffectChains.size();
7319 for (size_t i = 0; i < size; i++) {
7320 mEffectChains[i]->setMode_l(mode);
7321 }
7322}
7323
7324void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007325 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007326 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007327
Mathias Agopian65ab4712010-07-14 17:59:35 -07007328 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007329 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007330 // delete the effect module if removing last handle on it
7331 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007332 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007333 removeEffect_l(effect);
7334 AudioSystem::unregisterEffect(effect->id());
7335 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007336 }
7337}
7338
7339status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7340{
7341 int session = chain->sessionId();
7342 int16_t *buffer = mMixBuffer;
7343 bool ownsBuffer = false;
7344
Steve Block3856b092011-10-20 11:56:00 +01007345 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007346 if (session > 0) {
7347 // Only one effect chain can be present in direct output thread and it uses
7348 // the mix buffer as input
7349 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007350 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007351 buffer = new int16_t[numSamples];
7352 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007353 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007354 ownsBuffer = true;
7355 }
7356
7357 // Attach all tracks with same session ID to this chain.
7358 for (size_t i = 0; i < mTracks.size(); ++i) {
7359 sp<Track> track = mTracks[i];
7360 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007361 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007362 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007363 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007364 }
7365 }
7366
7367 // indicate all active tracks in the chain
7368 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7369 sp<Track> track = mActiveTracks[i].promote();
7370 if (track == 0) continue;
7371 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007372 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007373 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007374 }
7375 }
7376 }
7377
7378 chain->setInBuffer(buffer, ownsBuffer);
7379 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007380 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007381 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007382 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7383 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007384 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007385 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7386 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007387 // Effect chain for other sessions are inserted at beginning of effect
7388 // chains list to be processed before output mix effects. Relative order between other
7389 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007390 size_t size = mEffectChains.size();
7391 size_t i = 0;
7392 for (i = 0; i < size; i++) {
7393 if (mEffectChains[i]->sessionId() < session) break;
7394 }
7395 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007396 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007397
7398 return NO_ERROR;
7399}
7400
7401size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7402{
7403 int session = chain->sessionId();
7404
Steve Block3856b092011-10-20 11:56:00 +01007405 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007406
7407 for (size_t i = 0; i < mEffectChains.size(); i++) {
7408 if (chain == mEffectChains[i]) {
7409 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007410 // detach all active tracks from the chain
7411 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7412 sp<Track> track = mActiveTracks[i].promote();
7413 if (track == 0) continue;
7414 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007415 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007416 chain.get(), session);
7417 chain->decActiveTrackCnt();
7418 }
7419 }
7420
Mathias Agopian65ab4712010-07-14 17:59:35 -07007421 // detach all tracks with same session ID from this chain
7422 for (size_t i = 0; i < mTracks.size(); ++i) {
7423 sp<Track> track = mTracks[i];
7424 if (session == track->sessionId()) {
7425 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007426 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007427 }
7428 }
Eric Laurentde070132010-07-13 04:45:46 -07007429 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007430 }
7431 }
7432 return mEffectChains.size();
7433}
7434
Eric Laurentde070132010-07-13 04:45:46 -07007435status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7436 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007437{
7438 Mutex::Autolock _l(mLock);
7439 return attachAuxEffect_l(track, EffectId);
7440}
7441
Eric Laurentde070132010-07-13 04:45:46 -07007442status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7443 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007444{
7445 status_t status = NO_ERROR;
7446
7447 if (EffectId == 0) {
7448 track->setAuxBuffer(0, NULL);
7449 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007450 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7451 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007452 if (effect != 0) {
7453 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7454 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7455 } else {
7456 status = INVALID_OPERATION;
7457 }
7458 } else {
7459 status = BAD_VALUE;
7460 }
7461 }
7462 return status;
7463}
7464
7465void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7466{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007467 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007468 sp<Track> track = mTracks[i];
7469 if (track->auxEffectId() == effectId) {
7470 attachAuxEffect_l(track, 0);
7471 }
7472 }
7473}
7474
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007475status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7476{
7477 // only one chain per input thread
7478 if (mEffectChains.size() != 0) {
7479 return INVALID_OPERATION;
7480 }
Steve Block3856b092011-10-20 11:56:00 +01007481 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007482
7483 chain->setInBuffer(NULL);
7484 chain->setOutBuffer(NULL);
7485
Eric Laurent59255e42011-07-27 19:49:51 -07007486 checkSuspendOnAddEffectChain_l(chain);
7487
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007488 mEffectChains.add(chain);
7489
7490 return NO_ERROR;
7491}
7492
7493size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7494{
Steve Block3856b092011-10-20 11:56:00 +01007495 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007496 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007497 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7498 chain.get(), mEffectChains.size(), this);
7499 if (mEffectChains.size() == 1) {
7500 mEffectChains.removeAt(0);
7501 }
7502 return 0;
7503}
7504
Mathias Agopian65ab4712010-07-14 17:59:35 -07007505// ----------------------------------------------------------------------------
7506// EffectModule implementation
7507// ----------------------------------------------------------------------------
7508
7509#undef LOG_TAG
7510#define LOG_TAG "AudioFlinger::EffectModule"
7511
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007512AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007513 const wp<AudioFlinger::EffectChain>& chain,
7514 effect_descriptor_t *desc,
7515 int id,
7516 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007517 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007518 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007519{
Steve Block3856b092011-10-20 11:56:00 +01007520 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007521 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007522 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007523 return;
7524 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007525
7526 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7527
7528 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007529 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007530
7531 if (mStatus != NO_ERROR) {
7532 return;
7533 }
7534 lStatus = init();
7535 if (lStatus < 0) {
7536 mStatus = lStatus;
7537 goto Error;
7538 }
7539
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007540 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
7541 mPinned = true;
7542 }
Steve Block3856b092011-10-20 11:56:00 +01007543 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007544 return;
7545Error:
7546 EffectRelease(mEffectInterface);
7547 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007548 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007549}
7550
7551AudioFlinger::EffectModule::~EffectModule()
7552{
Steve Block3856b092011-10-20 11:56:00 +01007553 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007554 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007555 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7556 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7557 sp<ThreadBase> thread = mThread.promote();
7558 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007559 audio_stream_t *stream = thread->stream();
7560 if (stream != NULL) {
7561 stream->remove_audio_effect(stream, mEffectInterface);
7562 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007563 }
7564 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007565 // release effect engine
7566 EffectRelease(mEffectInterface);
7567 }
7568}
7569
Glenn Kasten435dbe62012-01-30 10:15:48 -08007570status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007571{
7572 status_t status;
7573
7574 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007575 int priority = handle->priority();
7576 size_t size = mHandles.size();
7577 sp<EffectHandle> h;
7578 size_t i;
7579 for (i = 0; i < size; i++) {
7580 h = mHandles[i].promote();
7581 if (h == 0) continue;
7582 if (h->priority() <= priority) break;
7583 }
7584 // if inserted in first place, move effect control from previous owner to this handle
7585 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007586 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007587 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007588 enabled = h->enabled();
7589 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007590 }
Eric Laurent59255e42011-07-27 19:49:51 -07007591 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007592 status = NO_ERROR;
7593 } else {
7594 status = ALREADY_EXISTS;
7595 }
Steve Block3856b092011-10-20 11:56:00 +01007596 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007597 mHandles.insertAt(handle, i);
7598 return status;
7599}
7600
7601size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
7602{
7603 Mutex::Autolock _l(mLock);
7604 size_t size = mHandles.size();
7605 size_t i;
7606 for (i = 0; i < size; i++) {
7607 if (mHandles[i] == handle) break;
7608 }
7609 if (i == size) {
7610 return size;
7611 }
Steve Block3856b092011-10-20 11:56:00 +01007612 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07007613
7614 bool enabled = false;
7615 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08007616 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01007617 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07007618 enabled = hdl->enabled();
7619 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007620 mHandles.removeAt(i);
7621 size = mHandles.size();
7622 // if removed from first place, move effect control from this handle to next in line
7623 if (i == 0 && size != 0) {
7624 sp<EffectHandle> h = mHandles[0].promote();
7625 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007626 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007627 }
7628 }
7629
Eric Laurentec437d82011-07-26 20:54:46 -07007630 // Prevent calls to process() and other functions on effect interface from now on.
7631 // The effect engine will be released by the destructor when the last strong reference on
7632 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007633 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07007634 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07007635 }
7636
Mathias Agopian65ab4712010-07-14 17:59:35 -07007637 return size;
7638}
7639
Eric Laurent59255e42011-07-27 19:49:51 -07007640sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7641{
7642 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08007643 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007644}
7645
Glenn Kasten58123c32012-02-03 10:32:24 -08007646void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007647{
Glenn Kasten90bebef2012-01-27 15:24:38 -08007648 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007649 // keep a strong reference on this EffectModule to avoid calling the
7650 // destructor before we exit
7651 sp<EffectModule> keep(this);
7652 {
7653 sp<ThreadBase> thread = mThread.promote();
7654 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007655 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007656 }
7657 }
7658}
7659
7660void AudioFlinger::EffectModule::updateState() {
7661 Mutex::Autolock _l(mLock);
7662
7663 switch (mState) {
7664 case RESTART:
7665 reset_l();
7666 // FALL THROUGH
7667
7668 case STARTING:
7669 // clear auxiliary effect input buffer for next accumulation
7670 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7671 memset(mConfig.inputCfg.buffer.raw,
7672 0,
7673 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7674 }
7675 start_l();
7676 mState = ACTIVE;
7677 break;
7678 case STOPPING:
7679 stop_l();
7680 mDisableWaitCnt = mMaxDisableWaitCnt;
7681 mState = STOPPED;
7682 break;
7683 case STOPPED:
7684 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
7685 // turn off sequence.
7686 if (--mDisableWaitCnt == 0) {
7687 reset_l();
7688 mState = IDLE;
7689 }
7690 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007691 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07007692 break;
7693 }
7694}
7695
7696void AudioFlinger::EffectModule::process()
7697{
7698 Mutex::Autolock _l(mLock);
7699
Eric Laurentec437d82011-07-26 20:54:46 -07007700 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007701 mConfig.inputCfg.buffer.raw == NULL ||
7702 mConfig.outputCfg.buffer.raw == NULL) {
7703 return;
7704 }
7705
Eric Laurent8f45bd72010-08-31 13:50:07 -07007706 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007707 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
7708 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08007709 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007710 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07007711 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007712 }
7713
7714 // do the actual processing in the effect engine
7715 int ret = (*mEffectInterface)->process(mEffectInterface,
7716 &mConfig.inputCfg.buffer,
7717 &mConfig.outputCfg.buffer);
7718
7719 // force transition to IDLE state when engine is ready
7720 if (mState == STOPPED && ret == -ENODATA) {
7721 mDisableWaitCnt = 1;
7722 }
7723
7724 // clear auxiliary effect input buffer for next accumulation
7725 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08007726 memset(mConfig.inputCfg.buffer.raw, 0,
7727 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007728 }
7729 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08007730 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7731 // If an insert effect is idle and input buffer is different from output buffer,
7732 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07007733 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07007734 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08007735 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
7736 int16_t *in = mConfig.inputCfg.buffer.s16;
7737 int16_t *out = mConfig.outputCfg.buffer.s16;
7738 for (size_t i = 0; i < frameCnt; i++) {
7739 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007740 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007741 }
7742 }
7743}
7744
7745void AudioFlinger::EffectModule::reset_l()
7746{
7747 if (mEffectInterface == NULL) {
7748 return;
7749 }
7750 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
7751}
7752
7753status_t AudioFlinger::EffectModule::configure()
7754{
7755 uint32_t channels;
7756 if (mEffectInterface == NULL) {
7757 return NO_INIT;
7758 }
7759
7760 sp<ThreadBase> thread = mThread.promote();
7761 if (thread == 0) {
7762 return DEAD_OBJECT;
7763 }
7764
7765 // TODO: handle configuration of effects replacing track process
7766 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007767 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007768 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07007769 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007770 }
7771
7772 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007773 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007774 } else {
7775 mConfig.inputCfg.channels = channels;
7776 }
7777 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07007778 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
7779 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007780 mConfig.inputCfg.samplingRate = thread->sampleRate();
7781 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
7782 mConfig.inputCfg.bufferProvider.cookie = NULL;
7783 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
7784 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
7785 mConfig.outputCfg.bufferProvider.cookie = NULL;
7786 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
7787 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
7788 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
7789 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07007790 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07007791 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07007792 // - in other sessions:
7793 // last effect in the chain accumulates in output buffer: input buffer != output buffer
7794 // other effect: overwrites output buffer: input buffer == output buffer
7795 // Auxiliary effect:
7796 // accumulates in output buffer: input buffer != output buffer
7797 // Therefore: accumulate <=> input buffer != output buffer
7798 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7799 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
7800 } else {
7801 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
7802 }
7803 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
7804 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
7805 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
7806 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
7807
Steve Block3856b092011-10-20 11:56:00 +01007808 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07007809 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
7810
Mathias Agopian65ab4712010-07-14 17:59:35 -07007811 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007812 uint32_t size = sizeof(int);
7813 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08007814 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07007815 sizeof(effect_config_t),
7816 &mConfig,
7817 &size,
7818 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007819 if (status == 0) {
7820 status = cmdStatus;
7821 }
7822
7823 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
7824 (1000 * mConfig.outputCfg.buffer.frameCount);
7825
7826 return status;
7827}
7828
7829status_t AudioFlinger::EffectModule::init()
7830{
7831 Mutex::Autolock _l(mLock);
7832 if (mEffectInterface == NULL) {
7833 return NO_INIT;
7834 }
7835 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007836 uint32_t size = sizeof(status_t);
7837 status_t status = (*mEffectInterface)->command(mEffectInterface,
7838 EFFECT_CMD_INIT,
7839 0,
7840 NULL,
7841 &size,
7842 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007843 if (status == 0) {
7844 status = cmdStatus;
7845 }
7846 return status;
7847}
7848
Eric Laurentec35a142011-10-05 17:42:25 -07007849status_t AudioFlinger::EffectModule::start()
7850{
7851 Mutex::Autolock _l(mLock);
7852 return start_l();
7853}
7854
Mathias Agopian65ab4712010-07-14 17:59:35 -07007855status_t AudioFlinger::EffectModule::start_l()
7856{
7857 if (mEffectInterface == NULL) {
7858 return NO_INIT;
7859 }
7860 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007861 uint32_t size = sizeof(status_t);
7862 status_t status = (*mEffectInterface)->command(mEffectInterface,
7863 EFFECT_CMD_ENABLE,
7864 0,
7865 NULL,
7866 &size,
7867 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007868 if (status == 0) {
7869 status = cmdStatus;
7870 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007871 if (status == 0 &&
7872 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7873 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7874 sp<ThreadBase> thread = mThread.promote();
7875 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007876 audio_stream_t *stream = thread->stream();
7877 if (stream != NULL) {
7878 stream->add_audio_effect(stream, mEffectInterface);
7879 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007880 }
7881 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007882 return status;
7883}
7884
Eric Laurentec437d82011-07-26 20:54:46 -07007885status_t AudioFlinger::EffectModule::stop()
7886{
7887 Mutex::Autolock _l(mLock);
7888 return stop_l();
7889}
7890
Mathias Agopian65ab4712010-07-14 17:59:35 -07007891status_t AudioFlinger::EffectModule::stop_l()
7892{
7893 if (mEffectInterface == NULL) {
7894 return NO_INIT;
7895 }
7896 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007897 uint32_t size = sizeof(status_t);
7898 status_t status = (*mEffectInterface)->command(mEffectInterface,
7899 EFFECT_CMD_DISABLE,
7900 0,
7901 NULL,
7902 &size,
7903 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007904 if (status == 0) {
7905 status = cmdStatus;
7906 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007907 if (status == 0 &&
7908 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7909 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7910 sp<ThreadBase> thread = mThread.promote();
7911 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007912 audio_stream_t *stream = thread->stream();
7913 if (stream != NULL) {
7914 stream->remove_audio_effect(stream, mEffectInterface);
7915 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007916 }
7917 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007918 return status;
7919}
7920
Eric Laurent25f43952010-07-28 05:40:18 -07007921status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
7922 uint32_t cmdSize,
7923 void *pCmdData,
7924 uint32_t *replySize,
7925 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007926{
7927 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007928// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007929
Eric Laurentec437d82011-07-26 20:54:46 -07007930 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007931 return NO_INIT;
7932 }
Eric Laurent25f43952010-07-28 05:40:18 -07007933 status_t status = (*mEffectInterface)->command(mEffectInterface,
7934 cmdCode,
7935 cmdSize,
7936 pCmdData,
7937 replySize,
7938 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007939 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007940 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007941 for (size_t i = 1; i < mHandles.size(); i++) {
7942 sp<EffectHandle> h = mHandles[i].promote();
7943 if (h != 0) {
7944 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7945 }
7946 }
7947 }
7948 return status;
7949}
7950
7951status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7952{
Eric Laurentdb7c0792011-08-10 10:37:50 -07007953
Mathias Agopian65ab4712010-07-14 17:59:35 -07007954 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007955 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007956
7957 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007958 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7959 if (enabled && status != NO_ERROR) {
7960 return status;
7961 }
7962
Mathias Agopian65ab4712010-07-14 17:59:35 -07007963 switch (mState) {
7964 // going from disabled to enabled
7965 case IDLE:
7966 mState = STARTING;
7967 break;
7968 case STOPPED:
7969 mState = RESTART;
7970 break;
7971 case STOPPING:
7972 mState = ACTIVE;
7973 break;
7974
7975 // going from enabled to disabled
7976 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007977 mState = STOPPED;
7978 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007979 case STARTING:
7980 mState = IDLE;
7981 break;
7982 case ACTIVE:
7983 mState = STOPPING;
7984 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007985 case DESTROYED:
7986 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007987 }
7988 for (size_t i = 1; i < mHandles.size(); i++) {
7989 sp<EffectHandle> h = mHandles[i].promote();
7990 if (h != 0) {
7991 h->setEnabled(enabled);
7992 }
7993 }
7994 }
7995 return NO_ERROR;
7996}
7997
Glenn Kastenc59c0042012-02-02 14:06:11 -08007998bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007999{
8000 switch (mState) {
8001 case RESTART:
8002 case STARTING:
8003 case ACTIVE:
8004 return true;
8005 case IDLE:
8006 case STOPPING:
8007 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008008 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008009 default:
8010 return false;
8011 }
8012}
8013
Glenn Kastenc59c0042012-02-02 14:06:11 -08008014bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008015{
8016 switch (mState) {
8017 case RESTART:
8018 case ACTIVE:
8019 case STOPPING:
8020 case STOPPED:
8021 return true;
8022 case IDLE:
8023 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008024 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008025 default:
8026 return false;
8027 }
8028}
8029
Mathias Agopian65ab4712010-07-14 17:59:35 -07008030status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8031{
8032 Mutex::Autolock _l(mLock);
8033 status_t status = NO_ERROR;
8034
8035 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8036 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008037 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008038 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8039 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008040 status_t cmdStatus;
8041 uint32_t volume[2];
8042 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008043 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008044 volume[0] = *left;
8045 volume[1] = *right;
8046 if (controller) {
8047 pVolume = volume;
8048 }
Eric Laurent25f43952010-07-28 05:40:18 -07008049 status = (*mEffectInterface)->command(mEffectInterface,
8050 EFFECT_CMD_SET_VOLUME,
8051 size,
8052 volume,
8053 &size,
8054 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008055 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8056 *left = volume[0];
8057 *right = volume[1];
8058 }
8059 }
8060 return status;
8061}
8062
8063status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8064{
8065 Mutex::Autolock _l(mLock);
8066 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008067 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8068 // audio pre processing modules on RecordThread can receive both output and
8069 // input device indication in the same call
8070 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8071 if (dev) {
8072 status_t cmdStatus;
8073 uint32_t size = sizeof(status_t);
8074
8075 status = (*mEffectInterface)->command(mEffectInterface,
8076 EFFECT_CMD_SET_DEVICE,
8077 sizeof(uint32_t),
8078 &dev,
8079 &size,
8080 &cmdStatus);
8081 if (status == NO_ERROR) {
8082 status = cmdStatus;
8083 }
8084 }
8085 dev = device & AUDIO_DEVICE_IN_ALL;
8086 if (dev) {
8087 status_t cmdStatus;
8088 uint32_t size = sizeof(status_t);
8089
8090 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8091 EFFECT_CMD_SET_INPUT_DEVICE,
8092 sizeof(uint32_t),
8093 &dev,
8094 &size,
8095 &cmdStatus);
8096 if (status2 == NO_ERROR) {
8097 status2 = cmdStatus;
8098 }
8099 if (status == NO_ERROR) {
8100 status = status2;
8101 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008102 }
8103 }
8104 return status;
8105}
8106
Glenn Kastenf78aee72012-01-04 11:00:47 -08008107status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008108{
8109 Mutex::Autolock _l(mLock);
8110 status_t status = NO_ERROR;
8111 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008112 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008113 uint32_t size = sizeof(status_t);
8114 status = (*mEffectInterface)->command(mEffectInterface,
8115 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008116 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008117 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008118 &size,
8119 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008120 if (status == NO_ERROR) {
8121 status = cmdStatus;
8122 }
8123 }
8124 return status;
8125}
8126
Eric Laurent59255e42011-07-27 19:49:51 -07008127void AudioFlinger::EffectModule::setSuspended(bool suspended)
8128{
8129 Mutex::Autolock _l(mLock);
8130 mSuspended = suspended;
8131}
Glenn Kastena3a85482012-01-04 11:01:11 -08008132
8133bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008134{
8135 Mutex::Autolock _l(mLock);
8136 return mSuspended;
8137}
8138
Mathias Agopian65ab4712010-07-14 17:59:35 -07008139status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8140{
8141 const size_t SIZE = 256;
8142 char buffer[SIZE];
8143 String8 result;
8144
8145 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8146 result.append(buffer);
8147
8148 bool locked = tryLock(mLock);
8149 // failed to lock - AudioFlinger is probably deadlocked
8150 if (!locked) {
8151 result.append("\t\tCould not lock Fx mutex:\n");
8152 }
8153
8154 result.append("\t\tSession Status State Engine:\n");
8155 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8156 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8157 result.append(buffer);
8158
8159 result.append("\t\tDescriptor:\n");
8160 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8161 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8162 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8163 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8164 result.append(buffer);
8165 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8166 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8167 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8168 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8169 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008170 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008171 mDescriptor.apiVersion,
8172 mDescriptor.flags);
8173 result.append(buffer);
8174 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8175 mDescriptor.name);
8176 result.append(buffer);
8177 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8178 mDescriptor.implementor);
8179 result.append(buffer);
8180
8181 result.append("\t\t- Input configuration:\n");
8182 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8183 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8184 (uint32_t)mConfig.inputCfg.buffer.raw,
8185 mConfig.inputCfg.buffer.frameCount,
8186 mConfig.inputCfg.samplingRate,
8187 mConfig.inputCfg.channels,
8188 mConfig.inputCfg.format);
8189 result.append(buffer);
8190
8191 result.append("\t\t- Output configuration:\n");
8192 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8193 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8194 (uint32_t)mConfig.outputCfg.buffer.raw,
8195 mConfig.outputCfg.buffer.frameCount,
8196 mConfig.outputCfg.samplingRate,
8197 mConfig.outputCfg.channels,
8198 mConfig.outputCfg.format);
8199 result.append(buffer);
8200
8201 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8202 result.append(buffer);
8203 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8204 for (size_t i = 0; i < mHandles.size(); ++i) {
8205 sp<EffectHandle> handle = mHandles[i].promote();
8206 if (handle != 0) {
8207 handle->dump(buffer, SIZE);
8208 result.append(buffer);
8209 }
8210 }
8211
8212 result.append("\n");
8213
8214 write(fd, result.string(), result.length());
8215
8216 if (locked) {
8217 mLock.unlock();
8218 }
8219
8220 return NO_ERROR;
8221}
8222
8223// ----------------------------------------------------------------------------
8224// EffectHandle implementation
8225// ----------------------------------------------------------------------------
8226
8227#undef LOG_TAG
8228#define LOG_TAG "AudioFlinger::EffectHandle"
8229
8230AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8231 const sp<AudioFlinger::Client>& client,
8232 const sp<IEffectClient>& effectClient,
8233 int32_t priority)
8234 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008235 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008236 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008237{
Steve Block3856b092011-10-20 11:56:00 +01008238 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008239
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008240 if (client == 0) {
8241 return;
8242 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008243 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8244 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8245 if (mCblkMemory != 0) {
8246 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8247
Glenn Kastena0d68332012-01-27 16:47:15 -08008248 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008249 new(mCblk) effect_param_cblk_t();
8250 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008251 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008252 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008253 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008254 return;
8255 }
8256}
8257
8258AudioFlinger::EffectHandle::~EffectHandle()
8259{
Steve Block3856b092011-10-20 11:56:00 +01008260 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008261 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01008262 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008263}
8264
8265status_t AudioFlinger::EffectHandle::enable()
8266{
Steve Block3856b092011-10-20 11:56:00 +01008267 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008268 if (!mHasControl) return INVALID_OPERATION;
8269 if (mEffect == 0) return DEAD_OBJECT;
8270
Eric Laurentdb7c0792011-08-10 10:37:50 -07008271 if (mEnabled) {
8272 return NO_ERROR;
8273 }
8274
Eric Laurent59255e42011-07-27 19:49:51 -07008275 mEnabled = true;
8276
8277 sp<ThreadBase> thread = mEffect->thread().promote();
8278 if (thread != 0) {
8279 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8280 }
8281
8282 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8283 if (mEffect->suspended()) {
8284 return NO_ERROR;
8285 }
8286
Eric Laurentdb7c0792011-08-10 10:37:50 -07008287 status_t status = mEffect->setEnabled(true);
8288 if (status != NO_ERROR) {
8289 if (thread != 0) {
8290 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8291 }
8292 mEnabled = false;
8293 }
8294 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008295}
8296
8297status_t AudioFlinger::EffectHandle::disable()
8298{
Steve Block3856b092011-10-20 11:56:00 +01008299 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008300 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008301 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008302
Eric Laurentdb7c0792011-08-10 10:37:50 -07008303 if (!mEnabled) {
8304 return NO_ERROR;
8305 }
Eric Laurent59255e42011-07-27 19:49:51 -07008306 mEnabled = false;
8307
8308 if (mEffect->suspended()) {
8309 return NO_ERROR;
8310 }
8311
8312 status_t status = mEffect->setEnabled(false);
8313
8314 sp<ThreadBase> thread = mEffect->thread().promote();
8315 if (thread != 0) {
8316 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8317 }
8318
8319 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008320}
8321
8322void AudioFlinger::EffectHandle::disconnect()
8323{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008324 disconnect(true);
8325}
8326
Glenn Kasten58123c32012-02-03 10:32:24 -08008327void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008328{
Glenn Kasten58123c32012-02-03 10:32:24 -08008329 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008330 if (mEffect == 0) {
8331 return;
8332 }
Glenn Kasten58123c32012-02-03 10:32:24 -08008333 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07008334
Eric Laurenta85a74a2011-10-19 11:44:54 -07008335 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008336 sp<ThreadBase> thread = mEffect->thread().promote();
8337 if (thread != 0) {
8338 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8339 }
Eric Laurent59255e42011-07-27 19:49:51 -07008340 }
8341
Mathias Agopian65ab4712010-07-14 17:59:35 -07008342 // release sp on module => module destructor can be called now
8343 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008344 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008345 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008346 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008347 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8348 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008349 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008350 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008351 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8352 mClient.clear();
8353 }
8354}
8355
Eric Laurent25f43952010-07-28 05:40:18 -07008356status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8357 uint32_t cmdSize,
8358 void *pCmdData,
8359 uint32_t *replySize,
8360 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008361{
Steve Block3856b092011-10-20 11:56:00 +01008362// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008363// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008364
8365 // only get parameter command is permitted for applications not controlling the effect
8366 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8367 return INVALID_OPERATION;
8368 }
8369 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008370 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008371
8372 // handle commands that are not forwarded transparently to effect engine
8373 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8374 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8375 // no risk to block the whole media server process or mixer threads is we are stuck here
8376 Mutex::Autolock _l(mCblk->lock);
8377 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8378 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8379 mCblk->serverIndex = 0;
8380 mCblk->clientIndex = 0;
8381 return BAD_VALUE;
8382 }
8383 status_t status = NO_ERROR;
8384 while (mCblk->serverIndex < mCblk->clientIndex) {
8385 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008386 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008387 int *p = (int *)(mBuffer + mCblk->serverIndex);
8388 int size = *p++;
8389 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008390 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008391 break;
8392 }
8393 effect_param_t *param = (effect_param_t *)p;
8394 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008395 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008396 mCblk->serverIndex += size;
8397 continue;
8398 }
Eric Laurent25f43952010-07-28 05:40:18 -07008399 uint32_t psize = sizeof(effect_param_t) +
8400 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8401 param->vsize;
8402 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8403 psize,
8404 p,
8405 &rsize,
8406 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008407 // stop at first error encountered
8408 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008409 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008410 *(int *)pReplyData = reply;
8411 break;
8412 } else if (reply != NO_ERROR) {
8413 *(int *)pReplyData = reply;
8414 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008415 }
8416 mCblk->serverIndex += size;
8417 }
8418 mCblk->serverIndex = 0;
8419 mCblk->clientIndex = 0;
8420 return status;
8421 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008422 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008423 return enable();
8424 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008425 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008426 return disable();
8427 }
8428
8429 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8430}
8431
Eric Laurent59255e42011-07-27 19:49:51 -07008432void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008433{
Steve Block3856b092011-10-20 11:56:00 +01008434 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008435
8436 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008437 mEnabled = enabled;
8438
Mathias Agopian65ab4712010-07-14 17:59:35 -07008439 if (signal && mEffectClient != 0) {
8440 mEffectClient->controlStatusChanged(hasControl);
8441 }
8442}
8443
Eric Laurent25f43952010-07-28 05:40:18 -07008444void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8445 uint32_t cmdSize,
8446 void *pCmdData,
8447 uint32_t replySize,
8448 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008449{
8450 if (mEffectClient != 0) {
8451 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8452 }
8453}
8454
8455
8456
8457void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8458{
8459 if (mEffectClient != 0) {
8460 mEffectClient->enableStatusChanged(enabled);
8461 }
8462}
8463
8464status_t AudioFlinger::EffectHandle::onTransact(
8465 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8466{
8467 return BnEffect::onTransact(code, data, reply, flags);
8468}
8469
8470
8471void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8472{
Glenn Kastena0d68332012-01-27 16:47:15 -08008473 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008474
8475 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008476 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008477 mPriority,
8478 mHasControl,
8479 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008480 mCblk ? mCblk->clientIndex : 0,
8481 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008482 );
8483
8484 if (locked) {
8485 mCblk->lock.unlock();
8486 }
8487}
8488
8489#undef LOG_TAG
8490#define LOG_TAG "AudioFlinger::EffectChain"
8491
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008492AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008493 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008494 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008495 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8496 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008497{
Dima Zavinfce7a472011-04-19 22:30:36 -07008498 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008499 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008500 return;
8501 }
8502 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8503 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008504}
8505
8506AudioFlinger::EffectChain::~EffectChain()
8507{
8508 if (mOwnInBuffer) {
8509 delete mInBuffer;
8510 }
8511
8512}
8513
Eric Laurent59255e42011-07-27 19:49:51 -07008514// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008515sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008516{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008517 size_t size = mEffects.size();
8518
8519 for (size_t i = 0; i < size; i++) {
8520 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008521 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008522 }
8523 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008524 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008525}
8526
Eric Laurent59255e42011-07-27 19:49:51 -07008527// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008528sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008529{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008530 size_t size = mEffects.size();
8531
8532 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07008533 // by convention, return first effect if id provided is 0 (0 is never a valid id)
8534 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008535 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008536 }
8537 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008538 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008539}
8540
Eric Laurent59255e42011-07-27 19:49:51 -07008541// getEffectFromType_l() must be called with ThreadBase::mLock held
8542sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
8543 const effect_uuid_t *type)
8544{
Eric Laurent59255e42011-07-27 19:49:51 -07008545 size_t size = mEffects.size();
8546
8547 for (size_t i = 0; i < size; i++) {
8548 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008549 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07008550 }
8551 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008552 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008553}
8554
Mathias Agopian65ab4712010-07-14 17:59:35 -07008555// Must be called with EffectChain::mLock locked
8556void AudioFlinger::EffectChain::process_l()
8557{
Eric Laurentdac69112010-09-28 14:09:57 -07008558 sp<ThreadBase> thread = mThread.promote();
8559 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008560 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07008561 return;
8562 }
Dima Zavinfce7a472011-04-19 22:30:36 -07008563 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
8564 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08008565 // always process effects unless no more tracks are on the session and the effect tail
8566 // has been rendered
8567 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07008568 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008569 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07008570
Eric Laurent544fe9b2011-11-11 15:42:52 -08008571 if (!tracksOnSession && mTailBufferCount == 0) {
8572 doProcess = false;
8573 }
8574
8575 if (activeTrackCnt() == 0) {
8576 // if no track is active and the effect tail has not been rendered,
8577 // the input buffer must be cleared here as the mixer process will not do it
8578 if (tracksOnSession || mTailBufferCount > 0) {
8579 size_t numSamples = thread->frameCount() * thread->channelCount();
8580 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
8581 if (mTailBufferCount > 0) {
8582 mTailBufferCount--;
8583 }
8584 }
8585 }
Eric Laurentdac69112010-09-28 14:09:57 -07008586 }
8587
Mathias Agopian65ab4712010-07-14 17:59:35 -07008588 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08008589 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07008590 for (size_t i = 0; i < size; i++) {
8591 mEffects[i]->process();
8592 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008593 }
8594 for (size_t i = 0; i < size; i++) {
8595 mEffects[i]->updateState();
8596 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008597}
8598
Eric Laurentcab11242010-07-15 12:50:15 -07008599// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07008600status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008601{
8602 effect_descriptor_t desc = effect->desc();
8603 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
8604
8605 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07008606 effect->setChain(this);
8607 sp<ThreadBase> thread = mThread.promote();
8608 if (thread == 0) {
8609 return NO_INIT;
8610 }
8611 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008612
8613 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8614 // Auxiliary effects are inserted at the beginning of mEffects vector as
8615 // they are processed first and accumulated in chain input buffer
8616 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07008617
Mathias Agopian65ab4712010-07-14 17:59:35 -07008618 // the input buffer for auxiliary effect contains mono samples in
8619 // 32 bit format. This is to avoid saturation in AudoMixer
8620 // accumulation stage. Saturation is done in EffectModule::process() before
8621 // calling the process in effect engine
8622 size_t numSamples = thread->frameCount();
8623 int32_t *buffer = new int32_t[numSamples];
8624 memset(buffer, 0, numSamples * sizeof(int32_t));
8625 effect->setInBuffer((int16_t *)buffer);
8626 // auxiliary effects output samples to chain input buffer for further processing
8627 // by insert effects
8628 effect->setOutBuffer(mInBuffer);
8629 } else {
8630 // Insert effects are inserted at the end of mEffects vector as they are processed
8631 // after track and auxiliary effects.
8632 // Insert effect order as a function of indicated preference:
8633 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8634 // another effect is present
8635 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8636 // last effect claiming first position
8637 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8638 // first effect claiming last position
8639 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8640 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8641 // already present
8642
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008643 size_t size = mEffects.size();
8644 size_t idx_insert = size;
8645 ssize_t idx_insert_first = -1;
8646 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008647
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008648 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008649 effect_descriptor_t d = mEffects[i]->desc();
8650 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8651 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8652 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8653 // check invalid effect chaining combinations
8654 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8655 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008656 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008657 return INVALID_OPERATION;
8658 }
8659 // remember position of first insert effect and by default
8660 // select this as insert position for new effect
8661 if (idx_insert == size) {
8662 idx_insert = i;
8663 }
8664 // remember position of last insert effect claiming
8665 // first position
8666 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8667 idx_insert_first = i;
8668 }
8669 // remember position of first insert effect claiming
8670 // last position
8671 if (iPref == EFFECT_FLAG_INSERT_LAST &&
8672 idx_insert_last == -1) {
8673 idx_insert_last = i;
8674 }
8675 }
8676 }
8677
8678 // modify idx_insert from first position if needed
8679 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8680 if (idx_insert_last != -1) {
8681 idx_insert = idx_insert_last;
8682 } else {
8683 idx_insert = size;
8684 }
8685 } else {
8686 if (idx_insert_first != -1) {
8687 idx_insert = idx_insert_first + 1;
8688 }
8689 }
8690
8691 // always read samples from chain input buffer
8692 effect->setInBuffer(mInBuffer);
8693
8694 // if last effect in the chain, output samples to chain
8695 // output buffer, otherwise to chain input buffer
8696 if (idx_insert == size) {
8697 if (idx_insert != 0) {
8698 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
8699 mEffects[idx_insert-1]->configure();
8700 }
8701 effect->setOutBuffer(mOutBuffer);
8702 } else {
8703 effect->setOutBuffer(mInBuffer);
8704 }
8705 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008706
Steve Block3856b092011-10-20 11:56:00 +01008707 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008708 }
8709 effect->configure();
8710 return NO_ERROR;
8711}
8712
Eric Laurentcab11242010-07-15 12:50:15 -07008713// removeEffect_l() must be called with PlaybackThread::mLock held
8714size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008715{
8716 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008717 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008718 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
8719
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008720 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008721 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07008722 // calling stop here will remove pre-processing effect from the audio HAL.
8723 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
8724 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07008725 if (mEffects[i]->state() == EffectModule::ACTIVE ||
8726 mEffects[i]->state() == EffectModule::STOPPING) {
8727 mEffects[i]->stop();
8728 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008729 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
8730 delete[] effect->inBuffer();
8731 } else {
8732 if (i == size - 1 && i != 0) {
8733 mEffects[i - 1]->setOutBuffer(mOutBuffer);
8734 mEffects[i - 1]->configure();
8735 }
8736 }
8737 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01008738 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008739 break;
8740 }
8741 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008742
8743 return mEffects.size();
8744}
8745
Eric Laurentcab11242010-07-15 12:50:15 -07008746// setDevice_l() must be called with PlaybackThread::mLock held
8747void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008748{
8749 size_t size = mEffects.size();
8750 for (size_t i = 0; i < size; i++) {
8751 mEffects[i]->setDevice(device);
8752 }
8753}
8754
Eric Laurentcab11242010-07-15 12:50:15 -07008755// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08008756void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008757{
8758 size_t size = mEffects.size();
8759 for (size_t i = 0; i < size; i++) {
8760 mEffects[i]->setMode(mode);
8761 }
8762}
8763
Eric Laurentcab11242010-07-15 12:50:15 -07008764// setVolume_l() must be called with PlaybackThread::mLock held
8765bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008766{
8767 uint32_t newLeft = *left;
8768 uint32_t newRight = *right;
8769 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07008770 int ctrlIdx = -1;
8771 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008772
Eric Laurentcab11242010-07-15 12:50:15 -07008773 // first update volume controller
8774 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07008775 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07008776 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
8777 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07008778 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07008779 break;
8780 }
8781 }
8782
8783 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07008784 if (hasControl) {
8785 *left = mNewLeftVolume;
8786 *right = mNewRightVolume;
8787 }
8788 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07008789 }
8790
8791 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07008792 mLeftVolume = newLeft;
8793 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008794
8795 // second get volume update from volume controller
8796 if (ctrlIdx >= 0) {
8797 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07008798 mNewLeftVolume = newLeft;
8799 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008800 }
8801 // then indicate volume to all other effects in chain.
8802 // Pass altered volume to effects before volume controller
8803 // and requested volume to effects after controller
8804 uint32_t lVol = newLeft;
8805 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008806
Mathias Agopian65ab4712010-07-14 17:59:35 -07008807 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07008808 if ((int)i == ctrlIdx) continue;
8809 // this also works for ctrlIdx == -1 when there is no volume controller
8810 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008811 lVol = *left;
8812 rVol = *right;
8813 }
8814 mEffects[i]->setVolume(&lVol, &rVol, false);
8815 }
8816 *left = newLeft;
8817 *right = newRight;
8818
8819 return hasControl;
8820}
8821
Mathias Agopian65ab4712010-07-14 17:59:35 -07008822status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
8823{
8824 const size_t SIZE = 256;
8825 char buffer[SIZE];
8826 String8 result;
8827
8828 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
8829 result.append(buffer);
8830
8831 bool locked = tryLock(mLock);
8832 // failed to lock - AudioFlinger is probably deadlocked
8833 if (!locked) {
8834 result.append("\tCould not lock mutex:\n");
8835 }
8836
Eric Laurentcab11242010-07-15 12:50:15 -07008837 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
8838 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008839 mEffects.size(),
8840 (uint32_t)mInBuffer,
8841 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008842 mActiveTrackCnt);
8843 result.append(buffer);
8844 write(fd, result.string(), result.size());
8845
8846 for (size_t i = 0; i < mEffects.size(); ++i) {
8847 sp<EffectModule> effect = mEffects[i];
8848 if (effect != 0) {
8849 effect->dump(fd, args);
8850 }
8851 }
8852
8853 if (locked) {
8854 mLock.unlock();
8855 }
8856
8857 return NO_ERROR;
8858}
8859
Eric Laurent59255e42011-07-27 19:49:51 -07008860// must be called with ThreadBase::mLock held
8861void AudioFlinger::EffectChain::setEffectSuspended_l(
8862 const effect_uuid_t *type, bool suspend)
8863{
8864 sp<SuspendedEffectDesc> desc;
8865 // use effect type UUID timelow as key as there is no real risk of identical
8866 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008867 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008868 if (suspend) {
8869 if (index >= 0) {
8870 desc = mSuspendedEffects.valueAt(index);
8871 } else {
8872 desc = new SuspendedEffectDesc();
8873 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
8874 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01008875 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008876 }
8877 if (desc->mRefCount++ == 0) {
8878 sp<EffectModule> effect = getEffectIfEnabled(type);
8879 if (effect != 0) {
8880 desc->mEffect = effect;
8881 effect->setSuspended(true);
8882 effect->setEnabled(false);
8883 }
8884 }
8885 } else {
8886 if (index < 0) {
8887 return;
8888 }
8889 desc = mSuspendedEffects.valueAt(index);
8890 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008891 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008892 desc->mRefCount = 1;
8893 }
8894 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01008895 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008896 if (desc->mEffect != 0) {
8897 sp<EffectModule> effect = desc->mEffect.promote();
8898 if (effect != 0) {
8899 effect->setSuspended(false);
8900 sp<EffectHandle> handle = effect->controlHandle();
8901 if (handle != 0) {
8902 effect->setEnabled(handle->enabled());
8903 }
8904 }
8905 desc->mEffect.clear();
8906 }
8907 mSuspendedEffects.removeItemsAt(index);
8908 }
8909 }
8910}
8911
8912// must be called with ThreadBase::mLock held
8913void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
8914{
8915 sp<SuspendedEffectDesc> desc;
8916
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008917 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07008918 if (suspend) {
8919 if (index >= 0) {
8920 desc = mSuspendedEffects.valueAt(index);
8921 } else {
8922 desc = new SuspendedEffectDesc();
8923 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01008924 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07008925 }
8926 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08008927 Vector< sp<EffectModule> > effects;
8928 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07008929 for (size_t i = 0; i < effects.size(); i++) {
8930 setEffectSuspended_l(&effects[i]->desc().type, true);
8931 }
8932 }
8933 } else {
8934 if (index < 0) {
8935 return;
8936 }
8937 desc = mSuspendedEffects.valueAt(index);
8938 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008939 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008940 desc->mRefCount = 1;
8941 }
8942 if (--desc->mRefCount == 0) {
8943 Vector<const effect_uuid_t *> types;
8944 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8945 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8946 continue;
8947 }
8948 types.add(&mSuspendedEffects.valueAt(i)->mType);
8949 }
8950 for (size_t i = 0; i < types.size(); i++) {
8951 setEffectSuspended_l(types[i], false);
8952 }
Steve Block3856b092011-10-20 11:56:00 +01008953 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008954 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8955 }
8956 }
8957}
8958
Eric Laurent6bffdb82011-09-23 08:40:41 -07008959
8960// The volume effect is used for automated tests only
8961#ifndef OPENSL_ES_H_
8962static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8963 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8964const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8965#endif //OPENSL_ES_H_
8966
Eric Laurentdb7c0792011-08-10 10:37:50 -07008967bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8968{
8969 // auxiliary effects and visualizer are never suspended on output mix
8970 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8971 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008972 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8973 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008974 return false;
8975 }
8976 return true;
8977}
8978
Glenn Kastend0539712012-01-30 12:56:03 -08008979void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008980{
Glenn Kastend0539712012-01-30 12:56:03 -08008981 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008982 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008983 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8984 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008985 }
Eric Laurent59255e42011-07-27 19:49:51 -07008986 }
Eric Laurent59255e42011-07-27 19:49:51 -07008987}
8988
8989sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8990 const effect_uuid_t *type)
8991{
Glenn Kasten090f0192012-01-30 13:00:02 -08008992 sp<EffectModule> effect = getEffectFromType_l(type);
8993 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008994}
8995
8996void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8997 bool enabled)
8998{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008999 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009000 if (enabled) {
9001 if (index < 0) {
9002 // if the effect is not suspend check if all effects are suspended
9003 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9004 if (index < 0) {
9005 return;
9006 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009007 if (!isEffectEligibleForSuspend(effect->desc())) {
9008 return;
9009 }
Eric Laurent59255e42011-07-27 19:49:51 -07009010 setEffectSuspended_l(&effect->desc().type, enabled);
9011 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009012 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009013 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009014 return;
9015 }
Eric Laurent59255e42011-07-27 19:49:51 -07009016 }
Steve Block3856b092011-10-20 11:56:00 +01009017 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009018 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009019 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9020 // if effect is requested to suspended but was not yet enabled, supend it now.
9021 if (desc->mEffect == 0) {
9022 desc->mEffect = effect;
9023 effect->setEnabled(false);
9024 effect->setSuspended(true);
9025 }
9026 } else {
9027 if (index < 0) {
9028 return;
9029 }
Steve Block3856b092011-10-20 11:56:00 +01009030 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009031 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009032 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9033 desc->mEffect.clear();
9034 effect->setSuspended(false);
9035 }
9036}
9037
Mathias Agopian65ab4712010-07-14 17:59:35 -07009038#undef LOG_TAG
9039#define LOG_TAG "AudioFlinger"
9040
9041// ----------------------------------------------------------------------------
9042
9043status_t AudioFlinger::onTransact(
9044 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9045{
9046 return BnAudioFlinger::onTransact(code, data, reply, flags);
9047}
9048
Mathias Agopian65ab4712010-07-14 17:59:35 -07009049}; // namespace android