blob: f7a252548b8839ca8ce6e08839e3626af03b5cf9 [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 Kasten58912562012-04-03 10:45:00 -07001478 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
1479 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1),
1480 mFastTrackNewMask(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001481{
Glenn Kasten58912562012-04-03 10:45:00 -07001482#if !LOG_NDEBUG
1483 memset(mFastTrackNewArray, 0, sizeof(mFastTrackNewArray));
1484#endif
Glenn Kasten480b4682012-02-28 12:30:08 -08001485 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001486
Mathias Agopian65ab4712010-07-14 17:59:35 -07001487 readOutputParameters();
1488
Glenn Kasten263709e2012-01-06 08:40:01 -08001489 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001490 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1491 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1492 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001493 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1494 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001495 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001496 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1497 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001498}
1499
1500AudioFlinger::PlaybackThread::~PlaybackThread()
1501{
1502 delete [] mMixBuffer;
1503}
1504
1505status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1506{
1507 dumpInternals(fd, args);
1508 dumpTracks(fd, args);
1509 dumpEffectChains(fd, args);
1510 return NO_ERROR;
1511}
1512
1513status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1514{
1515 const size_t SIZE = 256;
1516 char buffer[SIZE];
1517 String8 result;
1518
Glenn Kasten58912562012-04-03 10:45:00 -07001519 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1520 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1521 const stream_type_t *st = &mStreamTypes[i];
1522 if (i > 0) {
1523 result.appendFormat(", ");
1524 }
1525 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1526 if (st->mute) {
1527 result.append("M");
1528 }
1529 }
1530 result.append("\n");
1531 write(fd, result.string(), result.length());
1532 result.clear();
1533
Mathias Agopian65ab4712010-07-14 17:59:35 -07001534 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1535 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001536 result.append(" Name Client Type Fmt Chn mask Session Frames S M F SRate L dB R dB "
1537 "Server User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001538 for (size_t i = 0; i < mTracks.size(); ++i) {
1539 sp<Track> track = mTracks[i];
1540 if (track != 0) {
1541 track->dump(buffer, SIZE);
1542 result.append(buffer);
1543 }
1544 }
1545
1546 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1547 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001548 result.append(" Name Client Type Fmt Chn mask Session Frames S M F SRate L dB R dB "
1549 "Server User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001550 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001551 sp<Track> track = mActiveTracks[i].promote();
1552 if (track != 0) {
1553 track->dump(buffer, SIZE);
1554 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001555 }
1556 }
1557 write(fd, result.string(), result.size());
1558 return NO_ERROR;
1559}
1560
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1562{
1563 const size_t SIZE = 256;
1564 char buffer[SIZE];
1565 String8 result;
1566
1567 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1568 result.append(buffer);
1569 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1570 result.append(buffer);
1571 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1572 result.append(buffer);
1573 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1574 result.append(buffer);
1575 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1576 result.append(buffer);
1577 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1578 result.append(buffer);
1579 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1580 result.append(buffer);
1581 write(fd, result.string(), result.size());
1582
1583 dumpBase(fd, args);
1584
1585 return NO_ERROR;
1586}
1587
1588// Thread virtuals
1589status_t AudioFlinger::PlaybackThread::readyToRun()
1590{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001591 status_t status = initCheck();
1592 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001593 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001594 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001595 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001596 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001597 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598}
1599
1600void AudioFlinger::PlaybackThread::onFirstRef()
1601{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001602 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603}
1604
1605// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001606sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001607 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001608 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001610 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001611 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612 int frameCount,
1613 const sp<IMemory>& sharedBuffer,
1614 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001615 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001616 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001617 status_t *status)
1618{
1619 sp<Track> track;
1620 status_t lStatus;
1621
Glenn Kasten73d22752012-03-19 13:38:30 -07001622 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1623
1624 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001625 if (flags & IAudioFlinger::TRACK_FAST) {
1626 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001627 // not timed
1628 (!isTimed) &&
1629 // either of these use cases:
1630 (
1631 // use case 1: shared buffer with any frame count
1632 (
1633 (sharedBuffer != 0)
1634 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001635 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001636 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001637 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001638 ((frameCount == 0) ||
1639 (frameCount >= (int) mFrameCount)) // FIXME int cast is due to wrong parameter type
Glenn Kasten73d22752012-03-19 13:38:30 -07001640 )
1641 ) &&
1642 // PCM data
1643 audio_is_linear_pcm(format) &&
1644 // mono or stereo
1645 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1646 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001647#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001648 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001649 (sampleRate == mSampleRate) &&
1650#endif
1651 // normal mixer has an associated fast mixer
1652 hasFastMixer() &&
1653 // there are sufficient fast track slots available
1654 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001655 // FIXME test that MixerThread for this fast track has a capable output HAL
1656 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001657 ) {
1658 ALOGI("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
1659 frameCount, mFrameCount);
1660 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1661 if (frameCount == 0) {
1662 frameCount = mFrameCount;
1663 }
1664 } else {
1665 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001666 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1667 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1668 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1669 audio_is_linear_pcm(format),
1670 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001671 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001672 // For compatibility with AudioTrack calculation, buffer depth is forced
1673 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1674 // This is probably too conservative, but legacy application code may depend on it.
1675 // If you change this calculation, also review the start threshold which is related.
1676 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1677 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1678 if (minBufCount < 2) {
1679 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001680 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001681 int minFrameCount = mNormalFrameCount * minBufCount;
1682 if (frameCount < minFrameCount) {
1683 frameCount = minFrameCount;
1684 }
1685 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001686 }
1687
Mathias Agopian65ab4712010-07-14 17:59:35 -07001688 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001689 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1690 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001691 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001692 "for output %p with format %d",
1693 sampleRate, format, channelMask, mOutput, mFormat);
1694 lStatus = BAD_VALUE;
1695 goto Exit;
1696 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001697 }
1698 } else {
1699 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1700 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001701 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001702 lStatus = BAD_VALUE;
1703 goto Exit;
1704 }
1705 }
1706
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001707 lStatus = initCheck();
1708 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001709 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001710 goto Exit;
1711 }
1712
1713 { // scope for mLock
1714 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001715
1716 // all tracks in same audio session must share the same routing strategy otherwise
1717 // conflicts will happen when tracks are moved from one output to another by audio policy
1718 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001719 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001720 for (size_t i = 0; i < mTracks.size(); ++i) {
1721 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001722 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001723 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001724 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001725 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001726 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001727 lStatus = BAD_VALUE;
1728 goto Exit;
1729 }
1730 }
1731 }
1732
John Grossman4ff14ba2012-02-08 16:37:41 -08001733 if (!isTimed) {
1734 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001735 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001736 } else {
1737 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1738 channelMask, frameCount, sharedBuffer, sessionId);
1739 }
1740 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001741 lStatus = NO_MEMORY;
1742 goto Exit;
1743 }
1744 mTracks.add(track);
1745
1746 sp<EffectChain> chain = getEffectChain_l(sessionId);
1747 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001748 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001749 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001750 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001751 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001752 }
1753 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001754
1755#ifdef HAVE_REQUEST_PRIORITY
1756 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1757 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1758 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1759 // so ask activity manager to do this on our behalf
1760 int err = requestPriority(callingPid, tid, 1);
1761 if (err != 0) {
1762 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1763 1, callingPid, tid, err);
1764 }
1765 }
1766#endif
1767
Mathias Agopian65ab4712010-07-14 17:59:35 -07001768 lStatus = NO_ERROR;
1769
1770Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001771 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001772 *status = lStatus;
1773 }
1774 return track;
1775}
1776
1777uint32_t AudioFlinger::PlaybackThread::latency() const
1778{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001779 Mutex::Autolock _l(mLock);
1780 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001781 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001782 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001783 return 0;
1784 }
1785}
1786
Glenn Kasten6637baa2012-01-09 09:40:36 -08001787void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001788{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001789 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001790 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001791}
1792
Glenn Kasten6637baa2012-01-09 09:40:36 -08001793void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001794{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001795 Mutex::Autolock _l(mLock);
1796 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001797}
1798
Glenn Kasten6637baa2012-01-09 09:40:36 -08001799void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001800{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001801 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001802 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001803}
1804
Glenn Kasten6637baa2012-01-09 09:40:36 -08001805void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001806{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001807 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001808 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001809}
1810
Glenn Kastenfff6d712012-01-12 16:38:12 -08001811float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001812{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001813 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001814 return mStreamTypes[stream].volume;
1815}
1816
Mathias Agopian65ab4712010-07-14 17:59:35 -07001817// addTrack_l() must be called with ThreadBase::mLock held
1818status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1819{
1820 status_t status = ALREADY_EXISTS;
1821
1822 // set retry count for buffer fill
1823 track->mRetryCount = kMaxTrackStartupRetries;
1824 if (mActiveTracks.indexOf(track) < 0) {
1825 // the track is newly added, make sure it fills up all its
1826 // buffers before playing. This is to ensure the client will
1827 // effectively get the latency it requested.
1828 track->mFillingUpStatus = Track::FS_FILLING;
1829 track->mResetDone = false;
1830 mActiveTracks.add(track);
1831 if (track->mainBuffer() != mMixBuffer) {
1832 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1833 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001834 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001835 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001836 }
1837 }
1838
1839 status = NO_ERROR;
1840 }
1841
Steve Block3856b092011-10-20 11:56:00 +01001842 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843 mWaitWorkCV.broadcast();
1844
1845 return status;
1846}
1847
1848// destroyTrack_l() must be called with ThreadBase::mLock held
1849void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1850{
1851 track->mState = TrackBase::TERMINATED;
1852 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001853 removeTrack_l(track);
1854 }
1855}
1856
1857void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1858{
1859 mTracks.remove(track);
1860 deleteTrackName_l(track->name());
1861 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1862 if (chain != 0) {
1863 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864 }
1865}
1866
1867String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1868{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001869 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001870 char *s;
1871
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001872 Mutex::Autolock _l(mLock);
1873 if (initCheck() != NO_ERROR) {
1874 return out_s8;
1875 }
1876
Dima Zavin799a70e2011-04-18 16:57:27 -07001877 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001878 out_s8 = String8(s);
1879 free(s);
1880 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001881}
1882
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001883// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001884void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1885 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001886 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001887
Steve Block3856b092011-10-20 11:56:00 +01001888 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001889
1890 switch (event) {
1891 case AudioSystem::OUTPUT_OPENED:
1892 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001893 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001894 desc.samplingRate = mSampleRate;
1895 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001896 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001897 desc.latency = latency();
1898 param2 = &desc;
1899 break;
1900
1901 case AudioSystem::STREAM_CONFIG_CHANGED:
1902 param2 = &param;
1903 case AudioSystem::OUTPUT_CLOSED:
1904 default:
1905 break;
1906 }
1907 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1908}
1909
1910void AudioFlinger::PlaybackThread::readOutputParameters()
1911{
Dima Zavin799a70e2011-04-18 16:57:27 -07001912 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001913 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1914 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001915 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001916 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001917 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001918 if (mFrameCount & 15) {
1919 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1920 mFrameCount);
1921 }
1922
1923 // Calculate size of normal mix buffer
1924 if (mType == MIXER) {
1925 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
1926 mNormalFrameCount = ((minNormalFrameCount + mFrameCount - 1) / mFrameCount) * mFrameCount;
1927 if (mNormalFrameCount & 15) {
1928 ALOGW("Normal mix buffer size is %u frames but AudioMixer requires multiples of 16 "
1929 "frames", mNormalFrameCount);
1930 }
1931 } else {
1932 mNormalFrameCount = mFrameCount;
1933 }
1934 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001935
1936 // FIXME - Current mixer implementation only supports stereo output: Always
1937 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001938 delete[] mMixBuffer;
Glenn Kasten58912562012-04-03 10:45:00 -07001939 mMixBuffer = new int16_t[mNormalFrameCount * 2];
1940 memset(mMixBuffer, 0, mNormalFrameCount * 2 * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001941
Eric Laurentde070132010-07-13 04:45:46 -07001942 // force reconfiguration of effect chains and engines to take new buffer size and audio
1943 // parameters into account
1944 // Note that mLock is not held when readOutputParameters() is called from the constructor
1945 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1946 // matter.
1947 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1948 Vector< sp<EffectChain> > effectChains = mEffectChains;
1949 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001950 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001951 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001952}
1953
1954status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1955{
Glenn Kastena0d68332012-01-27 16:47:15 -08001956 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001957 return BAD_VALUE;
1958 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001959 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001960 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001961 return INVALID_OPERATION;
1962 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001963 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001964
Dima Zavin799a70e2011-04-18 16:57:27 -07001965 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001966}
1967
Eric Laurent39e94f82010-07-28 01:32:47 -07001968uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001969{
1970 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001971 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001973 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001974 }
1975
1976 for (size_t i = 0; i < mTracks.size(); ++i) {
1977 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001978 if (sessionId == track->sessionId() &&
1979 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001980 result |= TRACK_SESSION;
1981 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001982 }
1983 }
1984
Eric Laurent39e94f82010-07-28 01:32:47 -07001985 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001986}
1987
Eric Laurentde070132010-07-13 04:45:46 -07001988uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1989{
Dima Zavinfce7a472011-04-19 22:30:36 -07001990 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001991 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001992 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1993 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001994 }
1995 for (size_t i = 0; i < mTracks.size(); i++) {
1996 sp<Track> track = mTracks[i];
1997 if (sessionId == track->sessionId() &&
1998 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001999 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002000 }
2001 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002002 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002003}
2004
Mathias Agopian65ab4712010-07-14 17:59:35 -07002005
Glenn Kastenaed850d2012-01-26 09:46:34 -08002006AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002007{
2008 Mutex::Autolock _l(mLock);
2009 return mOutput;
2010}
2011
2012AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2013{
2014 Mutex::Autolock _l(mLock);
2015 AudioStreamOut *output = mOutput;
2016 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002017 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2018 // must push a NULL and wait for ack
2019 mOutputSink.clear();
2020 mPipeSink.clear();
2021 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002022 return output;
2023}
2024
2025// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002026audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002027{
2028 if (mOutput == NULL) {
2029 return NULL;
2030 }
2031 return &mOutput->stream->common;
2032}
2033
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002034uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002035{
2036 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
2037 // decoding and transfer time. So sleeping for half of the latency would likely cause
2038 // underruns
2039 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002040 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002041 } else {
2042 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
2043 }
2044}
2045
Eric Laurenta011e352012-03-29 15:51:43 -07002046status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2047{
2048 if (!isValidSyncEvent(event)) {
2049 return BAD_VALUE;
2050 }
2051
2052 Mutex::Autolock _l(mLock);
2053
2054 for (size_t i = 0; i < mTracks.size(); ++i) {
2055 sp<Track> track = mTracks[i];
2056 if (event->triggerSession() == track->sessionId()) {
2057 track->setSyncEvent(event);
2058 return NO_ERROR;
2059 }
2060 }
2061
2062 return NAME_NOT_FOUND;
2063}
2064
2065bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2066{
2067 switch (event->type()) {
2068 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2069 return true;
2070 default:
2071 break;
2072 }
2073 return false;
2074}
2075
Mathias Agopian65ab4712010-07-14 17:59:35 -07002076// ----------------------------------------------------------------------------
2077
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002078AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002079 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002080 : PlaybackThread(audioFlinger, output, id, device, type),
2081 // mAudioMixer below
2082#ifdef SOAKER
2083 mSoaker(NULL),
2084#endif
2085 // mFastMixer below
2086 mFastMixerFutex(0)
2087 // mOutputSink below
2088 // mPipeSink below
2089 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002090{
Glenn Kasten58912562012-04-03 10:45:00 -07002091 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2092 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2093 "mFrameCount=%d, mNormalFrameCount=%d",
2094 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2095 mNormalFrameCount);
2096 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2097
Mathias Agopian65ab4712010-07-14 17:59:35 -07002098 // FIXME - Current mixer implementation only supports stereo output
2099 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002100 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002101 }
Glenn Kasten58912562012-04-03 10:45:00 -07002102
2103 // create an NBAIO sink for the HAL output stream, and negotiate
2104 mOutputSink = new AudioStreamOutSink(output->stream);
2105 size_t numCounterOffers = 0;
2106 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2107 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2108 ALOG_ASSERT(index == 0);
2109
2110 // initialize fast mixer if needed
2111 if (mFrameCount < mNormalFrameCount) {
2112
2113 // create a MonoPipe to connect our submix to FastMixer
2114 NBAIO_Format format = mOutputSink->format();
2115 // frame count will be rounded up to a power of 2, so this formula should work well
2116 MonoPipe *monoPipe = new MonoPipe((mNormalFrameCount * 3) / 2, format,
2117 true /*writeCanBlock*/);
2118 const NBAIO_Format offers[1] = {format};
2119 size_t numCounterOffers = 0;
2120 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2121 ALOG_ASSERT(index == 0);
2122 mPipeSink = monoPipe;
2123
2124#ifdef SOAKER
2125 // create a soaker as workaround for governor issues
2126 mSoaker = new Soaker();
2127 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE
2128 mSoaker->run("Soaker", PRIORITY_LOWEST);
2129#endif
2130
2131 // create fast mixer and configure it initially with just one fast track for our submix
2132 mFastMixer = new FastMixer();
2133 FastMixerStateQueue *sq = mFastMixer->sq();
2134 FastMixerState *state = sq->begin();
2135 FastTrack *fastTrack = &state->mFastTracks[0];
2136 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2137 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2138 fastTrack->mVolumeProvider = NULL;
2139 fastTrack->mGeneration++;
2140 state->mFastTracksGen++;
2141 state->mTrackMask = 1;
2142 // fast mixer will use the HAL output sink
2143 state->mOutputSink = mOutputSink.get();
2144 state->mOutputSinkGen++;
2145 state->mFrameCount = mFrameCount;
2146 state->mCommand = FastMixerState::COLD_IDLE;
2147 // already done in constructor initialization list
2148 //mFastMixerFutex = 0;
2149 state->mColdFutexAddr = &mFastMixerFutex;
2150 state->mColdGen++;
2151 state->mDumpState = &mFastMixerDumpState;
2152 sq->end();
2153 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2154
2155 // start the fast mixer
2156 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2157#ifdef HAVE_REQUEST_PRIORITY
2158 pid_t tid = mFastMixer->getTid();
2159 int err = requestPriority(getpid_cached, tid, 2);
2160 if (err != 0) {
2161 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2162 2, getpid_cached, tid, err);
2163 }
2164#endif
2165
2166 } else {
2167 mFastMixer = NULL;
2168 }
2169 mNormalSink = mOutputSink;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002170}
2171
2172AudioFlinger::MixerThread::~MixerThread()
2173{
Glenn Kasten58912562012-04-03 10:45:00 -07002174 if (mFastMixer != NULL) {
2175 FastMixerStateQueue *sq = mFastMixer->sq();
2176 FastMixerState *state = sq->begin();
2177 if (state->mCommand == FastMixerState::COLD_IDLE) {
2178 int32_t old = android_atomic_inc(&mFastMixerFutex);
2179 if (old == -1) {
2180 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2181 }
2182 }
2183 state->mCommand = FastMixerState::EXIT;
2184 sq->end();
2185 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2186 mFastMixer->join();
2187 // Though the fast mixer thread has exited, it's state queue is still valid.
2188 // We'll use that extract the final state which contains one remaining fast track
2189 // corresponding to our sub-mix.
2190 state = sq->begin();
2191 ALOG_ASSERT(state->mTrackMask == 1);
2192 FastTrack *fastTrack = &state->mFastTracks[0];
2193 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2194 delete fastTrack->mBufferProvider;
2195 sq->end(false /*didModify*/);
2196 delete mFastMixer;
2197#ifdef SOAKER
2198 if (mSoaker != NULL) {
2199 mSoaker->requestExitAndWait();
2200 }
2201 delete mSoaker;
2202#endif
2203 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002204 delete mAudioMixer;
2205}
2206
Glenn Kasten83efdd02012-02-24 07:21:32 -08002207class CpuStats {
2208public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002209 CpuStats();
2210 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002211#ifdef DEBUG_CPU_USAGE
2212private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002213 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2214 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2215
2216 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2217
2218 int mCpuNum; // thread's current CPU number
2219 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002220#endif
2221};
2222
Glenn Kasten190a46f2012-03-06 11:27:10 -08002223CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002224#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002225 : mCpuNum(-1), mCpukHz(-1)
2226#endif
2227{
2228}
2229
2230void CpuStats::sample(const String8 &title) {
2231#ifdef DEBUG_CPU_USAGE
2232 // get current thread's delta CPU time in wall clock ns
2233 double wcNs;
2234 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2235
2236 // record sample for wall clock statistics
2237 if (valid) {
2238 mWcStats.sample(wcNs);
2239 }
2240
2241 // get the current CPU number
2242 int cpuNum = sched_getcpu();
2243
2244 // get the current CPU frequency in kHz
2245 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2246
2247 // check if either CPU number or frequency changed
2248 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2249 mCpuNum = cpuNum;
2250 mCpukHz = cpukHz;
2251 // ignore sample for purposes of cycles
2252 valid = false;
2253 }
2254
2255 // if no change in CPU number or frequency, then record sample for cycle statistics
2256 if (valid && mCpukHz > 0) {
2257 double cycles = wcNs * cpukHz * 0.000001;
2258 mHzStats.sample(cycles);
2259 }
2260
2261 unsigned n = mWcStats.n();
2262 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002263 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002264 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002265 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2266 double perLoop = elapsed / (double) n;
2267 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002268 double perLoop1k = perLoop * 0.001;
2269 double mean = mWcStats.mean();
2270 double stddev = mWcStats.stddev();
2271 double minimum = mWcStats.minimum();
2272 double maximum = mWcStats.maximum();
2273 double meanCycles = mHzStats.mean();
2274 double stddevCycles = mHzStats.stddev();
2275 double minCycles = mHzStats.minimum();
2276 double maxCycles = mHzStats.maximum();
2277 mCpuUsage.resetElapsed();
2278 mWcStats.reset();
2279 mHzStats.reset();
2280 ALOGD("CPU usage for %s over past %.1f secs\n"
2281 " (%u mixer loops at %.1f mean ms per loop):\n"
2282 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2283 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2284 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2285 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002286 elapsed * .000000001, n, perLoop * .000001,
2287 mean * .001,
2288 stddev * .001,
2289 minimum * .001,
2290 maximum * .001,
2291 mean / perLoop100,
2292 stddev / perLoop100,
2293 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002294 maximum / perLoop100,
2295 meanCycles / perLoop1k,
2296 stddevCycles / perLoop1k,
2297 minCycles / perLoop1k,
2298 maxCycles / perLoop1k);
2299
Glenn Kasten83efdd02012-02-24 07:21:32 -08002300 }
2301 }
2302#endif
2303};
2304
Glenn Kasten37d825e2012-02-24 07:21:48 -08002305void AudioFlinger::PlaybackThread::checkSilentMode_l()
2306{
2307 if (!mMasterMute) {
2308 char value[PROPERTY_VALUE_MAX];
2309 if (property_get("ro.audio.silent", value, "0") > 0) {
2310 char *endptr;
2311 unsigned long ul = strtoul(value, &endptr, 0);
2312 if (*endptr == '\0' && ul != 0) {
2313 ALOGD("Silence is golden");
2314 // The setprop command will not allow a property to be changed after
2315 // the first time it is set, so we don't have to worry about un-muting.
2316 setMasterMute_l(true);
2317 }
2318 }
2319 }
2320}
2321
Glenn Kasten000f0e32012-03-01 17:10:56 -08002322bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002323{
2324 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002325
Glenn Kasten000f0e32012-03-01 17:10:56 -08002326 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002327
2328 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002329 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002330if (mType == MIXER) {
2331 longStandbyExit = false;
2332}
Glenn Kasten688a6402012-02-29 07:57:06 -08002333
Glenn Kasten000f0e32012-03-01 17:10:56 -08002334 // DUPLICATING
2335 // FIXME could this be made local to while loop?
2336 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002337
Glenn Kasten66fcab92012-02-24 14:59:21 -08002338 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002339 sleepTime = idleSleepTime;
2340
2341if (mType == MIXER) {
2342 sleepTimeShift = 0;
2343}
2344
Glenn Kasten83efdd02012-02-24 07:21:32 -08002345 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002346 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002347
Eric Laurentfeb0db62011-07-22 09:04:31 -07002348 acquireWakeLock();
2349
Mathias Agopian65ab4712010-07-14 17:59:35 -07002350 while (!exitPending())
2351 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002352 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002353
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002354 Vector< sp<EffectChain> > effectChains;
2355
Mathias Agopian65ab4712010-07-14 17:59:35 -07002356 processConfigEvents();
2357
Mathias Agopian65ab4712010-07-14 17:59:35 -07002358 { // scope for mLock
2359
2360 Mutex::Autolock _l(mLock);
2361
2362 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002363 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002364 }
2365
Glenn Kastenfa26a852012-03-06 11:28:04 -08002366 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002367
Mathias Agopian65ab4712010-07-14 17:59:35 -07002368 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002369 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002370 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002371 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002372
2373 threadLoop_standby();
2374
Mathias Agopian65ab4712010-07-14 17:59:35 -07002375 mStandby = true;
2376 mBytesWritten = 0;
2377 }
2378
Glenn Kasten3e074702012-02-28 18:40:35 -08002379 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002380 // we're about to wait, flush the binder command buffer
2381 IPCThreadState::self()->flushCommands();
2382
Glenn Kastenfa26a852012-03-06 11:28:04 -08002383 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002384
Mathias Agopian65ab4712010-07-14 17:59:35 -07002385 if (exitPending()) break;
2386
Eric Laurentfeb0db62011-07-22 09:04:31 -07002387 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002388 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002389 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002390 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002391 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002392 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002393
Eric Laurentda747442012-04-25 18:53:13 -07002394 mMixerStatus = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002395
Glenn Kasten37d825e2012-02-24 07:21:48 -08002396 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002397
Glenn Kasten000f0e32012-03-01 17:10:56 -08002398 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002399 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002400 if (mType == MIXER) {
2401 sleepTimeShift = 0;
2402 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002403
Mathias Agopian65ab4712010-07-14 17:59:35 -07002404 continue;
2405 }
2406 }
2407
Eric Laurentda747442012-04-25 18:53:13 -07002408 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002409
2410 // prevent any changes in effect chain list and in each effect chain
2411 // during mixing and effect process as the audio buffers could be deleted
2412 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002413 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002414 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002415
Glenn Kastenfec279f2012-03-08 07:47:15 -08002416 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002417 threadLoop_mix();
2418 } else {
2419 threadLoop_sleepTime();
2420 }
2421
2422 if (mSuspended > 0) {
2423 sleepTime = suspendSleepTimeUs();
2424 }
2425
2426 // only process effects if we're going to write
2427 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002428 for (size_t i = 0; i < effectChains.size(); i ++) {
2429 effectChains[i]->process_l();
2430 }
2431 }
2432
2433 // enable changes in effect chain
2434 unlockEffectChains(effectChains);
2435
2436 // sleepTime == 0 means we must write to audio hardware
2437 if (sleepTime == 0) {
2438
2439 threadLoop_write();
2440
2441if (mType == MIXER) {
2442 // write blocked detection
2443 nsecs_t now = systemTime();
2444 nsecs_t delta = now - mLastWriteTime;
2445 if (!mStandby && delta > maxPeriod) {
2446 mNumDelayedWrites++;
2447 if ((now - lastWarning) > kWarningThrottleNs) {
2448 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2449 ns2ms(delta), mNumDelayedWrites, this);
2450 lastWarning = now;
2451 }
2452 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2453 // a different threshold. Or completely removed for what it is worth anyway...
2454 if (mStandby) {
2455 longStandbyExit = true;
2456 }
2457 }
2458}
2459
2460 mStandby = false;
2461 } else {
2462 usleep(sleepTime);
2463 }
2464
Glenn Kasten58912562012-04-03 10:45:00 -07002465 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002466 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002467 // same lock. This will also mutate and push a new fast mixer state.
2468 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002469 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002470
Glenn Kastenfa26a852012-03-06 11:28:04 -08002471 // FIXME I don't understand the need for this here;
2472 // it was in the original code but maybe the
2473 // assignment in saveOutputTracks() makes this unnecessary?
2474 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002475
2476 // Effect chains will be actually deleted here if they were removed from
2477 // mEffectChains list during mixing or effects processing
2478 effectChains.clear();
2479
2480 // FIXME Note that the above .clear() is no longer necessary since effectChains
2481 // is now local to this block, but will keep it for now (at least until merge done).
2482 }
2483
2484if (mType == MIXER || mType == DIRECT) {
2485 // put output stream into standby mode
2486 if (!mStandby) {
2487 mOutput->stream->common.standby(&mOutput->stream->common);
2488 }
2489}
2490if (mType == DUPLICATING) {
2491 // for DuplicatingThread, standby mode is handled by the outputTracks
2492}
2493
2494 releaseWakeLock();
2495
2496 ALOGV("Thread %p type %d exiting", this, mType);
2497 return false;
2498}
2499
Glenn Kasten58912562012-04-03 10:45:00 -07002500// FIXME This method needs a better name.
2501// It pushes a new fast mixer state and returns (via tracksToRemove) a set of tracks to remove.
2502void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2503{
2504 // were any of the removed tracks also fast tracks?
2505 unsigned removedMask = 0;
2506 for (size_t i = 0; i < tracksToRemove.size(); ++i) {
2507 if (tracksToRemove[i]->isFastTrack()) {
2508 int j = tracksToRemove[i]->mFastIndex;
2509 ALOG_ASSERT(0 < j && j < FastMixerState::kMaxFastTracks);
2510 removedMask |= 1 << j;
2511 }
2512 }
2513 Track* newArray[FastMixerState::kMaxFastTracks];
2514 unsigned newMask;
2515 {
2516 AutoMutex _l(mLock);
2517 mFastTrackAvailMask |= removedMask;
2518 newMask = mFastTrackNewMask;
2519 if (newMask) {
2520 mFastTrackNewMask = 0;
2521 memcpy(newArray, mFastTrackNewArray, sizeof(mFastTrackNewArray));
2522#if !LOG_NDEBUG
2523 memset(mFastTrackNewArray, 0, sizeof(mFastTrackNewArray));
2524#endif
2525 }
2526 }
2527 unsigned changedMask = newMask | removedMask;
2528 // are there any newly added or removed fast tracks?
2529 if (changedMask) {
2530
2531 // This assert would be incorrect because it's theoretically possible (though unlikely)
2532 // for a track to be created and then removed within the same normal mix cycle:
2533 // ALOG_ASSERT(!(newMask & removedMask));
2534 // The converse, of removing a track and then creating a new track at the identical slot
2535 // within the same normal mix cycle, is impossible because the slot isn't marked available.
2536
2537 // prepare a new state to push
2538 FastMixerStateQueue *sq = mFastMixer->sq();
2539 FastMixerState *state = sq->begin();
2540 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2541 while (changedMask) {
2542 int j = __builtin_ctz(changedMask);
2543 ALOG_ASSERT(0 < j && j < FastMixerState::kMaxFastTracks);
2544 changedMask &= ~(1 << j);
2545 FastTrack *fastTrack = &state->mFastTracks[j];
2546 // must first do new tracks, then removed tracks, in case same track in both
2547 if (newMask & (1 << j)) {
2548 ALOG_ASSERT(!(state->mTrackMask & (1 << j)));
2549 ALOG_ASSERT(fastTrack->mBufferProvider == NULL &&
2550 fastTrack->mVolumeProvider == NULL);
2551 Track *track = newArray[j];
2552 AudioBufferProvider *abp = track;
2553 VolumeProvider *vp = track;
2554 fastTrack->mBufferProvider = abp;
2555 fastTrack->mVolumeProvider = vp;
2556 fastTrack->mSampleRate = track->mSampleRate;
2557 fastTrack->mChannelMask = track->mChannelMask;
2558 state->mTrackMask |= 1 << j;
2559 }
2560 if (removedMask & (1 << j)) {
2561 ALOG_ASSERT(state->mTrackMask & (1 << j));
2562 ALOG_ASSERT(fastTrack->mBufferProvider != NULL &&
2563 fastTrack->mVolumeProvider != NULL);
2564 fastTrack->mBufferProvider = NULL;
2565 fastTrack->mVolumeProvider = NULL;
2566 fastTrack->mSampleRate = mSampleRate;
2567 fastTrack->mChannelMask = AUDIO_CHANNEL_OUT_STEREO;
2568 state->mTrackMask &= ~(1 << j);
2569 }
2570 fastTrack->mGeneration++;
2571 }
2572 state->mFastTracksGen++;
2573 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
2574 if (state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
2575 state->mCommand = FastMixerState::COLD_IDLE;
2576 state->mColdFutexAddr = &mFastMixerFutex;
2577 state->mColdGen++;
2578 mFastMixerFutex = 0;
2579 mNormalSink = mOutputSink;
2580 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2581 }
2582 sq->end();
2583 // If any fast tracks were removed, we must wait for acknowledgement
2584 // because we're about to decrement the last sp<> on those tracks.
2585 // Similarly if we put it into cold idle, need to wait for acknowledgement
2586 // so that it stops doing I/O.
2587 if (removedMask) {
2588 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2589 }
2590 sq->push(block);
2591 }
2592 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2593}
2594
2595void AudioFlinger::MixerThread::threadLoop_write()
2596{
2597 // FIXME we should only do one push per cycle; confirm this is true
2598 // Start the fast mixer if it's not already running
2599 if (mFastMixer != NULL) {
2600 FastMixerStateQueue *sq = mFastMixer->sq();
2601 FastMixerState *state = sq->begin();
2602 if (state->mCommand != FastMixerState::MIX_WRITE && state->mTrackMask > 1) {
2603 if (state->mCommand == FastMixerState::COLD_IDLE) {
2604 int32_t old = android_atomic_inc(&mFastMixerFutex);
2605 if (old == -1) {
2606 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2607 }
2608 }
2609 state->mCommand = FastMixerState::MIX_WRITE;
2610 sq->end();
2611 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2612 mNormalSink = mPipeSink;
2613 } else {
2614 sq->end(false /*didModify*/);
2615 }
2616 }
2617 PlaybackThread::threadLoop_write();
2618}
2619
Glenn Kasten000f0e32012-03-01 17:10:56 -08002620// shared by MIXER and DIRECT, overridden by DUPLICATING
2621void AudioFlinger::PlaybackThread::threadLoop_write()
2622{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002623 // FIXME rewrite to reduce number of system calls
2624 mLastWriteTime = systemTime();
2625 mInWrite = true;
Glenn Kasten58912562012-04-03 10:45:00 -07002626 int bytesWritten;
2627
2628 // If an NBAIO sink is present, use it to write the normal mixer's submix
2629 if (mNormalSink != 0) {
2630#define mBitShift 2 // FIXME
2631 size_t count = mixBufferSize >> mBitShift;
2632 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
2633 if (framesWritten > 0) {
2634 bytesWritten = framesWritten << mBitShift;
2635 } else {
2636 bytesWritten = framesWritten;
2637 }
2638
2639 // otherwise use the HAL / AudioStreamOut directly
2640 } else {
2641 // FIXME legacy, remove
2642 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2643 }
2644
2645 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002646 mNumWrites++;
2647 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002648}
2649
Glenn Kasten58912562012-04-03 10:45:00 -07002650void AudioFlinger::MixerThread::threadLoop_standby()
2651{
2652 // Idle the fast mixer if it's currently running
2653 if (mFastMixer != NULL) {
2654 FastMixerStateQueue *sq = mFastMixer->sq();
2655 FastMixerState *state = sq->begin();
2656 if (!(state->mCommand & FastMixerState::IDLE)) {
2657 state->mCommand = FastMixerState::COLD_IDLE;
2658 state->mColdFutexAddr = &mFastMixerFutex;
2659 state->mColdGen++;
2660 mFastMixerFutex = 0;
2661 sq->end();
2662 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2663 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
2664 mNormalSink = mOutputSink;
2665 } else {
2666 sq->end(false /*didModify*/);
2667 }
2668 }
2669 PlaybackThread::threadLoop_standby();
2670}
2671
Glenn Kasten000f0e32012-03-01 17:10:56 -08002672// shared by MIXER and DIRECT, overridden by DUPLICATING
2673void AudioFlinger::PlaybackThread::threadLoop_standby()
2674{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002675 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2676 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002677}
2678
2679void AudioFlinger::MixerThread::threadLoop_mix()
2680{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002681 // obtain the presentation timestamp of the next output buffer
2682 int64_t pts;
2683 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002684
Glenn Kasten952eeb22012-03-06 11:30:57 -08002685 if (NULL != mOutput->stream->get_next_write_timestamp) {
2686 status = mOutput->stream->get_next_write_timestamp(
2687 mOutput->stream, &pts);
2688 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002689
Glenn Kasten952eeb22012-03-06 11:30:57 -08002690 if (status != NO_ERROR) {
2691 pts = AudioBufferProvider::kInvalidPTS;
2692 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002693
Glenn Kasten952eeb22012-03-06 11:30:57 -08002694 // mix buffers...
2695 mAudioMixer->process(pts);
2696 // increase sleep time progressively when application underrun condition clears.
2697 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2698 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2699 // such that we would underrun the audio HAL.
2700 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2701 sleepTimeShift--;
2702 }
2703 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002704 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002705 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002706}
2707
2708void AudioFlinger::MixerThread::threadLoop_sleepTime()
2709{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002710 // If no tracks are ready, sleep once for the duration of an output
2711 // buffer size, then write 0s to the output
2712 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002713 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002714 sleepTime = activeSleepTime >> sleepTimeShift;
2715 if (sleepTime < kMinThreadSleepTimeUs) {
2716 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002717 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002718 // reduce sleep time in case of consecutive application underruns to avoid
2719 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2720 // duration we would end up writing less data than needed by the audio HAL if
2721 // the condition persists.
2722 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2723 sleepTimeShift++;
2724 }
2725 } else {
2726 sleepTime = idleSleepTime;
2727 }
2728 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002729 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002730 memset (mMixBuffer, 0, mixBufferSize);
2731 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002732 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002733 }
2734 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002735}
2736
2737// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002738AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002739 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002740{
2741
Glenn Kasten29c23c32012-01-26 13:37:52 -08002742 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002743 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002744 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002745 size_t mixedTracks = 0;
2746 size_t tracksWithEffect = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07002747 size_t fastTracks = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002748
2749 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002750 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002751
Eric Laurent571d49c2010-08-11 05:20:11 -07002752 if (masterMute) {
2753 masterVolume = 0;
2754 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002755 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002756 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002757 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002758 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002759 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002760 masterVolume = (float)((v + (1 << 23)) >> 24);
2761 chain.clear();
2762 }
2763
2764 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002765 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002766 if (t == 0) continue;
2767
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002768 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002769 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002770
2771 if (track->isFastTrack()) {
2772 // cache the combined master volume and stream type volume for fast mixer;
2773 // this lacks any synchronization or barrier so VolumeProvider may read a stale value
2774 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
2775 ++fastTracks;
2776 if (track->isTerminated()) {
2777 tracksToRemove->add(track);
2778 }
2779 continue;
2780 }
2781
2782 { // local variable scope to avoid goto warning
2783
Mathias Agopian65ab4712010-07-14 17:59:35 -07002784 audio_track_cblk_t* cblk = track->cblk();
2785
2786 // The first time a track is added we wait
2787 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002788 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002789 // make sure that we have enough frames to mix one full buffer.
2790 // enforce this condition only once to enable draining the buffer in case the client
2791 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07002792 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002793 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002794 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002795 if (!track->isStopped() && !track->isPausing() &&
Eric Laurentda747442012-04-25 18:53:13 -07002796 (mMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002797 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07002798 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07002799 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002800 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07002801 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08002802 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07002803 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08002804 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2805 // the minimum track buffer size is normally twice the number of frames necessary
2806 // to fill one buffer and the resampler should not leave more than one buffer worth
2807 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002808 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002809 }
2810 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002811 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002812 !track->isPaused() && !track->isTerminated())
2813 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002814 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002815
2816 mixedTracks++;
2817
2818 // track->mainBuffer() != mMixBuffer means there is an effect chain
2819 // connected to the track
2820 chain.clear();
2821 if (track->mainBuffer() != mMixBuffer) {
2822 chain = getEffectChain_l(track->sessionId());
2823 // Delegate volume control to effect in track effect chain if needed
2824 if (chain != 0) {
2825 tracksWithEffect++;
2826 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002827 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002828 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002829 }
2830 }
2831
2832
2833 int param = AudioMixer::VOLUME;
2834 if (track->mFillingUpStatus == Track::FS_FILLED) {
2835 // no ramp for the first volume setting
2836 track->mFillingUpStatus = Track::FS_ACTIVE;
2837 if (track->mState == TrackBase::RESUMING) {
2838 track->mState = TrackBase::ACTIVE;
2839 param = AudioMixer::RAMP_VOLUME;
2840 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002841 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002842 } else if (cblk->server != 0) {
2843 // If the track is stopped before the first frame was mixed,
2844 // do not apply ramp
2845 param = AudioMixer::RAMP_VOLUME;
2846 }
2847
2848 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002849 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002850 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002851 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002852 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002853 if (track->isPausing()) {
2854 track->setPaused();
2855 }
2856 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002857
Mathias Agopian65ab4712010-07-14 17:59:35 -07002858 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002859 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002860 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002861 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002862 vl = vlr & 0xFFFF;
2863 vr = vlr >> 16;
2864 // track volumes come from shared memory, so can't be trusted and must be clamped
2865 if (vl > MAX_GAIN_INT) {
2866 ALOGV("Track left volume out of range: %04X", vl);
2867 vl = MAX_GAIN_INT;
2868 }
2869 if (vr > MAX_GAIN_INT) {
2870 ALOGV("Track right volume out of range: %04X", vr);
2871 vr = MAX_GAIN_INT;
2872 }
2873 // now apply the master volume and stream type volume
2874 vl = (uint32_t)(v * vl) << 12;
2875 vr = (uint32_t)(v * vr) << 12;
2876 // assuming master volume and stream type volume each go up to 1.0,
2877 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002878
Glenn Kasten05632a52012-01-03 14:22:33 -08002879 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2880 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002881 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002882 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002883 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002884 }
2885 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002886 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002887 // Delegate volume control to effect in track effect chain if needed
2888 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2889 // Do not ramp volume if volume is controlled by effect
2890 param = AudioMixer::VOLUME;
2891 track->mHasVolumeController = true;
2892 } else {
2893 // force no volume ramp when volume controller was just disabled or removed
2894 // from effect chain to avoid volume spike
2895 if (track->mHasVolumeController) {
2896 param = AudioMixer::VOLUME;
2897 }
2898 track->mHasVolumeController = false;
2899 }
2900
2901 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002902 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002903 vl = (vl + (1 << 11)) >> 12;
2904 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2905 vr = (vr + (1 << 11)) >> 12;
2906 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002907
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002908 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 -07002909
Mathias Agopian65ab4712010-07-14 17:59:35 -07002910 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002911 mAudioMixer->setBufferProvider(name, track);
2912 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002913
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002914 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2915 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2916 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002917 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002918 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002919 AudioMixer::TRACK,
2920 AudioMixer::FORMAT, (void *)track->format());
2921 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002922 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002924 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002925 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002926 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002927 AudioMixer::RESAMPLE,
2928 AudioMixer::SAMPLE_RATE,
2929 (void *)(cblk->sampleRate));
2930 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002931 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002932 AudioMixer::TRACK,
2933 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2934 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002935 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002936 AudioMixer::TRACK,
2937 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2938
2939 // reset retry count
2940 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002941
Eric Laurent27741442012-01-17 19:20:12 -08002942 // If one track is ready, set the mixer ready if:
2943 // - the mixer was not ready during previous round OR
2944 // - no other track is not ready
Eric Laurentda747442012-04-25 18:53:13 -07002945 if (mMixerStatus != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08002946 mixerStatus != MIXER_TRACKS_ENABLED) {
2947 mixerStatus = MIXER_TRACKS_READY;
2948 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002949 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002950 //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 -07002951 if (track->isStopped()) {
2952 track->reset();
2953 }
2954 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2955 // We have consumed all the buffers of this track.
2956 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07002957 // TODO: use actual buffer filling status instead of latency when available from
2958 // audio HAL
2959 size_t audioHALFrames =
2960 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2961 size_t framesWritten =
2962 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2963 if (track->presentationComplete(framesWritten, audioHALFrames)) {
2964 tracksToRemove->add(track);
2965 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002966 } else {
2967 // No buffers for this track. Give it a few chances to
2968 // fill a buffer, then remove it from active list.
2969 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002970 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002971 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002972 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002973 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002974 // If one track is not ready, mark the mixer also not ready if:
2975 // - the mixer was ready during previous round OR
2976 // - no other track is ready
Eric Laurentda747442012-04-25 18:53:13 -07002977 } else if (mMixerStatus == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08002978 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002979 mixerStatus = MIXER_TRACKS_ENABLED;
2980 }
2981 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002982 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002983 }
Glenn Kasten58912562012-04-03 10:45:00 -07002984
2985 } // local variable scope to avoid goto warning
2986track_is_ready: ;
2987
Mathias Agopian65ab4712010-07-14 17:59:35 -07002988 }
2989
Glenn Kasten58912562012-04-03 10:45:00 -07002990 // FIXME Here is where we would push the new FastMixer state if necessary
2991
Mathias Agopian65ab4712010-07-14 17:59:35 -07002992 // remove all the tracks that need to be...
2993 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002994 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002995 for (size_t i=0 ; i<count ; i++) {
2996 const sp<Track>& track = tracksToRemove->itemAt(i);
2997 mActiveTracks.remove(track);
2998 if (track->mainBuffer() != mMixBuffer) {
2999 chain = getEffectChain_l(track->sessionId());
3000 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003001 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003002 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003003 }
3004 }
3005 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003006 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003007 }
3008 }
3009 }
3010
3011 // mix buffer must be cleared if all tracks are connected to an
3012 // effect chain as in this case the mixer will not write to
3013 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003014 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3015 // FIXME as a performance optimization, should remember previous zero status
3016 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003017 }
3018
Glenn Kasten58912562012-04-03 10:45:00 -07003019 // if any fast tracks, then status is ready
3020 if (fastTracks > 0) {
3021 mixerStatus = MIXER_TRACKS_READY;
3022 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003023 return mixerStatus;
3024}
3025
Glenn Kasten66fcab92012-02-24 14:59:21 -08003026/*
3027The derived values that are cached:
3028 - mixBufferSize from frame count * frame size
3029 - activeSleepTime from activeSleepTimeUs()
3030 - idleSleepTime from idleSleepTimeUs()
3031 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3032 - maxPeriod from frame count and sample rate (MIXER only)
3033
3034The parameters that affect these derived values are:
3035 - frame count
3036 - frame size
3037 - sample rate
3038 - device type: A2DP or not
3039 - device latency
3040 - format: PCM or not
3041 - active sleep time
3042 - idle sleep time
3043*/
3044
3045void AudioFlinger::PlaybackThread::cacheParameters_l()
3046{
Glenn Kasten58912562012-04-03 10:45:00 -07003047 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003048 activeSleepTime = activeSleepTimeUs();
3049 idleSleepTime = idleSleepTimeUs();
3050}
3051
Glenn Kastenfff6d712012-01-12 16:38:12 -08003052void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003053{
Steve Block3856b092011-10-20 11:56:00 +01003054 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003055 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003056 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003057
Mathias Agopian65ab4712010-07-14 17:59:35 -07003058 size_t size = mTracks.size();
3059 for (size_t i = 0; i < size; i++) {
3060 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003061 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003062 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003063 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003064 }
3065 }
3066}
3067
Mathias Agopian65ab4712010-07-14 17:59:35 -07003068// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003069int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003070{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003071 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003072}
3073
3074// deleteTrackName_l() must be called with ThreadBase::mLock held
3075void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3076{
Steve Block3856b092011-10-20 11:56:00 +01003077 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003078 mAudioMixer->deleteTrackName(name);
3079}
3080
3081// checkForNewParameters_l() must be called with ThreadBase::mLock held
3082bool AudioFlinger::MixerThread::checkForNewParameters_l()
3083{
Glenn Kasten58912562012-04-03 10:45:00 -07003084 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3085 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003086 bool reconfig = false;
3087
3088 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003089
3090 if (mFastMixer != NULL) {
3091 FastMixerStateQueue *sq = mFastMixer->sq();
3092 FastMixerState *state = sq->begin();
3093 if (!(state->mCommand & FastMixerState::IDLE)) {
3094 previousCommand = state->mCommand;
3095 state->mCommand = FastMixerState::HOT_IDLE;
3096 sq->end();
3097 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3098 } else {
3099 sq->end(false /*didModify*/);
3100 }
3101 }
3102
Mathias Agopian65ab4712010-07-14 17:59:35 -07003103 status_t status = NO_ERROR;
3104 String8 keyValuePair = mNewParameters[0];
3105 AudioParameter param = AudioParameter(keyValuePair);
3106 int value;
3107
3108 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3109 reconfig = true;
3110 }
3111 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003112 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003113 status = BAD_VALUE;
3114 } else {
3115 reconfig = true;
3116 }
3117 }
3118 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003119 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003120 status = BAD_VALUE;
3121 } else {
3122 reconfig = true;
3123 }
3124 }
3125 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3126 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003127 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003128 // if frame count is changed after track creation
3129 if (!mTracks.isEmpty()) {
3130 status = INVALID_OPERATION;
3131 } else {
3132 reconfig = true;
3133 }
3134 }
3135 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003136#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003137 // when changing the audio output device, call addBatteryData to notify
3138 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003139 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003140 uint32_t params = 0;
3141 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003142 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003143 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3144 }
3145
3146 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003147 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003148 // check if any other device (except speaker) is on
3149 if (value & deviceWithoutSpeaker ) {
3150 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3151 }
3152
3153 if (params != 0) {
3154 addBatteryData(params);
3155 }
3156 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003157#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003158
Mathias Agopian65ab4712010-07-14 17:59:35 -07003159 // forward device change to effects that have requested to be
3160 // aware of attached audio device.
3161 mDevice = (uint32_t)value;
3162 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003163 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003164 }
3165 }
3166
3167 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003168 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003169 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003170 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003171 mOutput->stream->common.standby(&mOutput->stream->common);
3172 mStandby = true;
3173 mBytesWritten = 0;
3174 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003175 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003176 }
3177 if (status == NO_ERROR && reconfig) {
3178 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003179 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3180 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003181 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003182 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003183 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003184 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003185 if (name < 0) break;
3186 mTracks[i]->mName = name;
3187 // limit track sample rate to 2 x new output sample rate
3188 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3189 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3190 }
3191 }
3192 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3193 }
3194 }
3195
3196 mNewParameters.removeAt(0);
3197
3198 mParamStatus = status;
3199 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003200 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3201 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003202 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003203 }
Glenn Kasten58912562012-04-03 10:45:00 -07003204
3205 if (!(previousCommand & FastMixerState::IDLE)) {
3206 ALOG_ASSERT(mFastMixer != NULL);
3207 FastMixerStateQueue *sq = mFastMixer->sq();
3208 FastMixerState *state = sq->begin();
3209 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3210 state->mCommand = previousCommand;
3211 sq->end();
3212 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3213 }
3214
Mathias Agopian65ab4712010-07-14 17:59:35 -07003215 return reconfig;
3216}
3217
3218status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3219{
3220 const size_t SIZE = 256;
3221 char buffer[SIZE];
3222 String8 result;
3223
3224 PlaybackThread::dumpInternals(fd, args);
3225
3226 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3227 result.append(buffer);
3228 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003229
3230 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3231 FastMixerDumpState copy = mFastMixerDumpState;
3232 copy.dump(fd);
3233
Mathias Agopian65ab4712010-07-14 17:59:35 -07003234 return NO_ERROR;
3235}
3236
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003237uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003238{
Glenn Kasten58912562012-04-03 10:45:00 -07003239 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003240}
3241
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003242uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003243{
Glenn Kasten58912562012-04-03 10:45:00 -07003244 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003245}
3246
Glenn Kasten66fcab92012-02-24 14:59:21 -08003247void AudioFlinger::MixerThread::cacheParameters_l()
3248{
3249 PlaybackThread::cacheParameters_l();
3250
3251 // FIXME: Relaxed timing because of a certain device that can't meet latency
3252 // Should be reduced to 2x after the vendor fixes the driver issue
3253 // increase threshold again due to low power audio mode. The way this warning
3254 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003255 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003256}
3257
Mathias Agopian65ab4712010-07-14 17:59:35 -07003258// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003259AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3260 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003261 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003262 // mLeftVolFloat, mRightVolFloat
3263 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07003264{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003265}
3266
3267AudioFlinger::DirectOutputThread::~DirectOutputThread()
3268{
3269}
3270
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003271AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3272 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003273)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003274{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003275 sp<Track> trackToRemove;
3276
Glenn Kastenfec279f2012-03-08 07:47:15 -08003277 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003278
Glenn Kasten952eeb22012-03-06 11:30:57 -08003279 // find out which tracks need to be processed
3280 if (mActiveTracks.size() != 0) {
3281 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003282 // The track died recently
3283 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003284
Glenn Kasten952eeb22012-03-06 11:30:57 -08003285 Track* const track = t.get();
3286 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003287
Glenn Kasten952eeb22012-03-06 11:30:57 -08003288 // The first time a track is added we wait
3289 // for all its buffers to be filled before processing it
3290 if (cblk->framesReady() && track->isReady() &&
3291 !track->isPaused() && !track->isTerminated())
3292 {
3293 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003294
Glenn Kasten952eeb22012-03-06 11:30:57 -08003295 if (track->mFillingUpStatus == Track::FS_FILLED) {
3296 track->mFillingUpStatus = Track::FS_ACTIVE;
3297 mLeftVolFloat = mRightVolFloat = 0;
3298 mLeftVolShort = mRightVolShort = 0;
3299 if (track->mState == TrackBase::RESUMING) {
3300 track->mState = TrackBase::ACTIVE;
3301 rampVolume = true;
3302 }
3303 } else if (cblk->server != 0) {
3304 // If the track is stopped before the first frame was mixed,
3305 // do not apply ramp
3306 rampVolume = true;
3307 }
3308 // compute volume for this track
3309 float left, right;
3310 if (track->isMuted() || mMasterMute || track->isPausing() ||
3311 mStreamTypes[track->streamType()].mute) {
3312 left = right = 0;
3313 if (track->isPausing()) {
3314 track->setPaused();
3315 }
3316 } else {
3317 float typeVolume = mStreamTypes[track->streamType()].volume;
3318 float v = mMasterVolume * typeVolume;
3319 uint32_t vlr = cblk->getVolumeLR();
3320 float v_clamped = v * (vlr & 0xFFFF);
3321 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3322 left = v_clamped/MAX_GAIN;
3323 v_clamped = v * (vlr >> 16);
3324 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3325 right = v_clamped/MAX_GAIN;
3326 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003327
Glenn Kasten952eeb22012-03-06 11:30:57 -08003328 if (left != mLeftVolFloat || right != mRightVolFloat) {
3329 mLeftVolFloat = left;
3330 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003331
Glenn Kasten952eeb22012-03-06 11:30:57 -08003332 // If audio HAL implements volume control,
3333 // force software volume to nominal value
3334 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
3335 left = 1.0f;
3336 right = 1.0f;
3337 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003338
Glenn Kasten952eeb22012-03-06 11:30:57 -08003339 // Convert volumes from float to 8.24
3340 uint32_t vl = (uint32_t)(left * (1 << 24));
3341 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003342
Glenn Kasten952eeb22012-03-06 11:30:57 -08003343 // Delegate volume control to effect in track effect chain if needed
3344 // only one effect chain can be present on DirectOutputThread, so if
3345 // there is one, the track is connected to it
3346 if (!mEffectChains.isEmpty()) {
3347 // Do not ramp volume if volume is controlled by effect
3348 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003349 rampVolume = false;
3350 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003351 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003352
Glenn Kasten952eeb22012-03-06 11:30:57 -08003353 // Convert volumes from 8.24 to 4.12 format
3354 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
3355 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3356 leftVol = (uint16_t)v_clamped;
3357 v_clamped = (vr + (1 << 11)) >> 12;
3358 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3359 rightVol = (uint16_t)v_clamped;
3360 } else {
3361 leftVol = mLeftVolShort;
3362 rightVol = mRightVolShort;
3363 rampVolume = false;
3364 }
3365
3366 // reset retry count
3367 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003368 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003369 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003370 } else {
3371 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
3372 if (track->isStopped()) {
3373 track->reset();
3374 }
3375 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
3376 // We have consumed all the buffers of this track.
3377 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003378 // TODO: implement behavior for compressed audio
3379 size_t audioHALFrames =
3380 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3381 size_t framesWritten =
3382 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3383 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3384 trackToRemove = track;
3385 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003386 } else {
3387 // No buffers for this track. Give it a few chances to
3388 // fill a buffer, then remove it from active list.
3389 if (--(track->mRetryCount) <= 0) {
3390 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3391 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003392 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003393 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003394 }
3395 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003396 }
3397 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003398
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003399 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003400 // remove all the tracks that need to be...
3401 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003402 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003403 mActiveTracks.remove(trackToRemove);
3404 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003405 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003406 trackToRemove->sessionId());
3407 mEffectChains[0]->decActiveTrackCnt();
3408 }
3409 if (trackToRemove->isTerminated()) {
3410 removeTrack_l(trackToRemove);
3411 }
3412 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003413
Glenn Kastenfec279f2012-03-08 07:47:15 -08003414 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003415}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003416
Glenn Kasten000f0e32012-03-01 17:10:56 -08003417void AudioFlinger::DirectOutputThread::threadLoop_mix()
3418{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003419 AudioBufferProvider::Buffer buffer;
3420 size_t frameCount = mFrameCount;
3421 int8_t *curBuf = (int8_t *)mMixBuffer;
3422 // output audio to hardware
3423 while (frameCount) {
3424 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003425 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003426 if (CC_UNLIKELY(buffer.raw == NULL)) {
3427 memset(curBuf, 0, frameCount * mFrameSize);
3428 break;
3429 }
3430 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3431 frameCount -= buffer.frameCount;
3432 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003433 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003434 }
3435 sleepTime = 0;
3436 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003437 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003438
3439 // apply volume
3440
3441 // Do not apply volume on compressed audio
3442 if (!audio_is_linear_pcm(mFormat)) {
3443 return;
3444 }
3445
3446 // convert to signed 16 bit before volume calculation
3447 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3448 size_t count = mFrameCount * mChannelCount;
3449 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
3450 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003451 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003452 *dst-- = (int16_t)(*src--^0x80) << 8;
3453 }
3454 }
3455
3456 frameCount = mFrameCount;
3457 int16_t *out = mMixBuffer;
3458 if (rampVolume) {
3459 if (mChannelCount == 1) {
3460 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3461 int32_t vlInc = d / (int32_t)frameCount;
3462 int32_t vl = ((int32_t)mLeftVolShort << 16);
3463 do {
3464 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3465 out++;
3466 vl += vlInc;
3467 } while (--frameCount);
3468
3469 } else {
3470 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3471 int32_t vlInc = d / (int32_t)frameCount;
3472 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3473 int32_t vrInc = d / (int32_t)frameCount;
3474 int32_t vl = ((int32_t)mLeftVolShort << 16);
3475 int32_t vr = ((int32_t)mRightVolShort << 16);
3476 do {
3477 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3478 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3479 out += 2;
3480 vl += vlInc;
3481 vr += vrInc;
3482 } while (--frameCount);
3483 }
3484 } else {
3485 if (mChannelCount == 1) {
3486 do {
3487 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3488 out++;
3489 } while (--frameCount);
3490 } else {
3491 do {
3492 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3493 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3494 out += 2;
3495 } while (--frameCount);
3496 }
3497 }
3498
3499 // convert back to unsigned 8 bit after volume calculation
3500 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3501 size_t count = mFrameCount * mChannelCount;
3502 int16_t *src = mMixBuffer;
3503 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003504 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003505 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3506 }
3507 }
3508
3509 mLeftVolShort = leftVol;
3510 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003511}
3512
3513void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3514{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003515 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003516 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003517 sleepTime = activeSleepTime;
3518 } else {
3519 sleepTime = idleSleepTime;
3520 }
3521 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003522 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003523 sleepTime = 0;
3524 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003525}
3526
3527// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003528int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003529{
3530 return 0;
3531}
3532
3533// deleteTrackName_l() must be called with ThreadBase::mLock held
3534void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3535{
3536}
3537
3538// checkForNewParameters_l() must be called with ThreadBase::mLock held
3539bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3540{
3541 bool reconfig = false;
3542
3543 while (!mNewParameters.isEmpty()) {
3544 status_t status = NO_ERROR;
3545 String8 keyValuePair = mNewParameters[0];
3546 AudioParameter param = AudioParameter(keyValuePair);
3547 int value;
3548
3549 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3550 // do not accept frame count changes if tracks are open as the track buffer
3551 // size depends on frame count and correct behavior would not be garantied
3552 // if frame count is changed after track creation
3553 if (!mTracks.isEmpty()) {
3554 status = INVALID_OPERATION;
3555 } else {
3556 reconfig = true;
3557 }
3558 }
3559 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003560 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003561 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003562 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003563 mOutput->stream->common.standby(&mOutput->stream->common);
3564 mStandby = true;
3565 mBytesWritten = 0;
3566 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003567 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003568 }
3569 if (status == NO_ERROR && reconfig) {
3570 readOutputParameters();
3571 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3572 }
3573 }
3574
3575 mNewParameters.removeAt(0);
3576
3577 mParamStatus = status;
3578 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003579 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3580 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003581 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003582 }
3583 return reconfig;
3584}
3585
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003586uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003587{
3588 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003589 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003590 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591 } else {
3592 time = 10000;
3593 }
3594 return time;
3595}
3596
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003597uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003598{
3599 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003600 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003601 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003602 } else {
3603 time = 10000;
3604 }
3605 return time;
3606}
3607
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003608uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003609{
3610 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003611 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003612 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3613 } else {
3614 time = 10000;
3615 }
3616 return time;
3617}
3618
Glenn Kasten66fcab92012-02-24 14:59:21 -08003619void AudioFlinger::DirectOutputThread::cacheParameters_l()
3620{
3621 PlaybackThread::cacheParameters_l();
3622
3623 // use shorter standby delay as on normal output to release
3624 // hardware resources as soon as possible
3625 standbyDelay = microseconds(activeSleepTime*2);
3626}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003627
Mathias Agopian65ab4712010-07-14 17:59:35 -07003628// ----------------------------------------------------------------------------
3629
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003630AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003631 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003632 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3633 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003634{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003635 addOutputTrack(mainThread);
3636}
3637
3638AudioFlinger::DuplicatingThread::~DuplicatingThread()
3639{
3640 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3641 mOutputTracks[i]->destroy();
3642 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003643}
3644
Glenn Kasten000f0e32012-03-01 17:10:56 -08003645void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003646{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003647 // mix buffers...
3648 if (outputsReady(outputTracks)) {
3649 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3650 } else {
3651 memset(mMixBuffer, 0, mixBufferSize);
3652 }
3653 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003654 writeFrames = mNormalFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003655}
3656
3657void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3658{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003659 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003660 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003661 sleepTime = activeSleepTime;
3662 } else {
3663 sleepTime = idleSleepTime;
3664 }
3665 } else if (mBytesWritten != 0) {
3666 // flush remaining overflow buffers in output tracks
3667 for (size_t i = 0; i < outputTracks.size(); i++) {
3668 if (outputTracks[i]->isActive()) {
3669 sleepTime = 0;
3670 writeFrames = 0;
3671 memset(mMixBuffer, 0, mixBufferSize);
3672 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003673 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003674 }
3675 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003676}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003677
Glenn Kasten000f0e32012-03-01 17:10:56 -08003678void AudioFlinger::DuplicatingThread::threadLoop_write()
3679{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003680 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003681 for (size_t i = 0; i < outputTracks.size(); i++) {
3682 outputTracks[i]->write(mMixBuffer, writeFrames);
3683 }
3684 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003685}
Glenn Kasten688a6402012-02-29 07:57:06 -08003686
Glenn Kasten000f0e32012-03-01 17:10:56 -08003687void AudioFlinger::DuplicatingThread::threadLoop_standby()
3688{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003689 // DuplicatingThread implements standby by stopping all tracks
3690 for (size_t i = 0; i < outputTracks.size(); i++) {
3691 outputTracks[i]->stop();
3692 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003693}
3694
Glenn Kastenfa26a852012-03-06 11:28:04 -08003695void AudioFlinger::DuplicatingThread::saveOutputTracks()
3696{
3697 outputTracks = mOutputTracks;
3698}
3699
3700void AudioFlinger::DuplicatingThread::clearOutputTracks()
3701{
3702 outputTracks.clear();
3703}
3704
Mathias Agopian65ab4712010-07-14 17:59:35 -07003705void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3706{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003707 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003708 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003709 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003710 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003711 this,
3712 mSampleRate,
3713 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003714 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003715 frameCount);
3716 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003717 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003718 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003719 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003720 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003721 }
3722}
3723
3724void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3725{
3726 Mutex::Autolock _l(mLock);
3727 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003728 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003729 mOutputTracks[i]->destroy();
3730 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003731 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003732 return;
3733 }
3734 }
Steve Block3856b092011-10-20 11:56:00 +01003735 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003736}
3737
Glenn Kasten438b0362012-03-06 11:24:48 -08003738// caller must hold mLock
3739void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003740{
3741 mWaitTimeMs = UINT_MAX;
3742 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3743 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003744 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003745 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3746 if (waitTimeMs < mWaitTimeMs) {
3747 mWaitTimeMs = waitTimeMs;
3748 }
3749 }
3750 }
3751}
3752
3753
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003754bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003755{
3756 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003757 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003758 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003759 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003760 return false;
3761 }
3762 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3763 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003764 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003765 return false;
3766 }
3767 }
3768 return true;
3769}
3770
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003771uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003772{
3773 return (mWaitTimeMs * 1000) / 2;
3774}
3775
Glenn Kasten66fcab92012-02-24 14:59:21 -08003776void AudioFlinger::DuplicatingThread::cacheParameters_l()
3777{
3778 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3779 updateWaitTime_l();
3780
3781 MixerThread::cacheParameters_l();
3782}
3783
Mathias Agopian65ab4712010-07-14 17:59:35 -07003784// ----------------------------------------------------------------------------
3785
3786// TrackBase constructor must be called with AudioFlinger::mLock held
3787AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003788 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003789 const sp<Client>& client,
3790 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003791 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003792 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003793 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003794 const sp<IMemory>& sharedBuffer,
3795 int sessionId)
3796 : RefBase(),
3797 mThread(thread),
3798 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003799 mCblk(NULL),
3800 // mBuffer
3801 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003802 mFrameCount(0),
3803 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07003804 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003805 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003806 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003807 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003808 // mChannelCount
3809 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003810{
Steve Block3856b092011-10-20 11:56:00 +01003811 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003812
Steve Blockb8a80522011-12-20 16:23:08 +00003813 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003814 size_t size = sizeof(audio_track_cblk_t);
3815 uint8_t channelCount = popcount(channelMask);
3816 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3817 if (sharedBuffer == 0) {
3818 size += bufferSize;
3819 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003820
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003821 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003822 mCblkMemory = client->heap()->allocate(size);
3823 if (mCblkMemory != 0) {
3824 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003825 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003826 new(mCblk) audio_track_cblk_t();
3827 // clear all buffers
3828 mCblk->frameCount = frameCount;
3829 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003830// uncomment the following lines to quickly test 32-bit wraparound
3831// mCblk->user = 0xffff0000;
3832// mCblk->server = 0xffff0000;
3833// mCblk->userBase = 0xffff0000;
3834// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003835 mChannelCount = channelCount;
3836 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003837 if (sharedBuffer == 0) {
3838 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3839 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3840 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003841 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003842 mCblk->flags = CBLK_UNDERRUN_ON;
3843 } else {
3844 mBuffer = sharedBuffer->pointer();
3845 }
3846 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3847 }
3848 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003849 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003850 client->heap()->dump("AudioTrack");
3851 return;
3852 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003853 } else {
3854 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07003855 // construct the shared structure in-place.
3856 new(mCblk) audio_track_cblk_t();
3857 // clear all buffers
3858 mCblk->frameCount = frameCount;
3859 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003860// uncomment the following lines to quickly test 32-bit wraparound
3861// mCblk->user = 0xffff0000;
3862// mCblk->server = 0xffff0000;
3863// mCblk->userBase = 0xffff0000;
3864// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003865 mChannelCount = channelCount;
3866 mChannelMask = channelMask;
3867 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3868 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3869 // Force underrun condition to avoid false underrun callback until first data is
3870 // written to buffer (other flags are cleared)
3871 mCblk->flags = CBLK_UNDERRUN_ON;
3872 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003873 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003874}
3875
3876AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3877{
Glenn Kastena0d68332012-01-27 16:47:15 -08003878 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003879 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003880 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003881 } else {
3882 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003883 }
3884 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003885 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003886 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003887 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003888 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003889 // If the client's reference count drops to zero, the associated destructor
3890 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3891 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003892 mClient.clear();
3893 }
3894}
3895
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003896// AudioBufferProvider interface
3897// getNextBuffer() = 0;
3898// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003899void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3900{
Glenn Kastene0feee32011-12-13 11:53:26 -08003901 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003902 mFrameCount = buffer->frameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003903 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003904 buffer->frameCount = 0;
3905}
3906
3907bool AudioFlinger::ThreadBase::TrackBase::step() {
3908 bool result;
3909 audio_track_cblk_t* cblk = this->cblk();
3910
3911 result = cblk->stepServer(mFrameCount);
3912 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003913 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003914 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003915 }
3916 return result;
3917}
3918
3919void AudioFlinger::ThreadBase::TrackBase::reset() {
3920 audio_track_cblk_t* cblk = this->cblk();
3921
3922 cblk->user = 0;
3923 cblk->server = 0;
3924 cblk->userBase = 0;
3925 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003926 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01003927 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003928}
3929
Mathias Agopian65ab4712010-07-14 17:59:35 -07003930int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3931 return (int)mCblk->sampleRate;
3932}
3933
Mathias Agopian65ab4712010-07-14 17:59:35 -07003934void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3935 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003936 size_t frameSize = cblk->frameSize;
3937 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3938 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003939
3940 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07003941 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
3942 "TrackBase::getBuffer buffer out of range:\n"
3943 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
3944 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003945 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07003946 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003947
3948 return bufferStart;
3949}
3950
Eric Laurenta011e352012-03-29 15:51:43 -07003951status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
3952{
3953 mSyncEvents.add(event);
3954 return NO_ERROR;
3955}
3956
Mathias Agopian65ab4712010-07-14 17:59:35 -07003957// ----------------------------------------------------------------------------
3958
3959// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3960AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003961 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003962 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003963 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003964 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003965 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003966 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003967 int frameCount,
3968 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07003969 int sessionId,
3970 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003971 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07003972 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07003973 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07003974 // mRetryCount initialized later when needed
3975 mSharedBuffer(sharedBuffer),
3976 mStreamType(streamType),
3977 mName(-1), // see note below
3978 mMainBuffer(thread->mixBuffer()),
3979 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07003980 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07003981 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07003982 mFlags(flags),
3983 mFastIndex(-1),
3984 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003985{
3986 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003987 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3988 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003989 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten58912562012-04-03 10:45:00 -07003990 if (flags & IAudioFlinger::TRACK_FAST) {
3991 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
3992 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
3993 int i = __builtin_ctz(thread->mFastTrackAvailMask);
3994 ALOG_ASSERT(0 < i && i < FastMixerState::kMaxFastTracks);
3995 mFastIndex = i;
3996 thread->mFastTrackAvailMask &= ~(1 << i);
3997 // Although we've allocated an index, we can't mutate or push a new fast track state
3998 // here, because that data structure can only be changed within the normal mixer
3999 // threadLoop(). So instead, make a note to mutate and push later.
4000 thread->mFastTrackNewArray[i] = this;
4001 thread->mFastTrackNewMask |= 1 << i;
4002 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004003 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07004004 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kastenf9959012012-03-19 11:14:37 -07004005 if (mName < 0) {
4006 ALOGE("no more track names available");
4007 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004008 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004009 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004010}
4011
4012AudioFlinger::PlaybackThread::Track::~Track()
4013{
Steve Block3856b092011-10-20 11:56:00 +01004014 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004015 sp<ThreadBase> thread = mThread.promote();
4016 if (thread != 0) {
4017 Mutex::Autolock _l(thread->mLock);
4018 mState = TERMINATED;
4019 }
4020}
4021
4022void AudioFlinger::PlaybackThread::Track::destroy()
4023{
4024 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4025 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004026 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004027 // we must acquire a strong reference on this Track before locking mLock
4028 // here so that the destructor is called only when exiting this function.
4029 // On the other hand, as long as Track::destroy() is only called by
4030 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4031 // this Track with its member mTrack.
4032 sp<Track> keep(this);
4033 { // scope for mLock
4034 sp<ThreadBase> thread = mThread.promote();
4035 if (thread != 0) {
4036 if (!isOutputTrack()) {
4037 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004038 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004039
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004040#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004041 // to track the speaker usage
4042 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004043#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004044 }
4045 AudioSystem::releaseOutput(thread->id());
4046 }
4047 Mutex::Autolock _l(thread->mLock);
4048 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4049 playbackThread->destroyTrack_l(this);
4050 }
4051 }
4052}
4053
4054void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4055{
Glenn Kasten83d86532012-01-17 14:39:34 -08004056 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004057 if (isFastTrack()) {
4058 strcpy(buffer, " fast");
4059 } else {
4060 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4061 }
4062 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 -08004063 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004064 mStreamType,
4065 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004066 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004067 mSessionId,
4068 mFrameCount,
4069 mState,
4070 mMute,
4071 mFillingUpStatus,
4072 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004073 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4074 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004075 mCblk->server,
4076 mCblk->user,
4077 (int)mMainBuffer,
4078 (int)mAuxBuffer);
4079}
4080
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004081// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004082status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004083 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004084{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004085 audio_track_cblk_t* cblk = this->cblk();
4086 uint32_t framesReady;
4087 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004088
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004089 // Check if last stepServer failed, try to step now
4090 if (mStepServerFailed) {
4091 if (!step()) goto getNextBuffer_exit;
4092 ALOGV("stepServer recovered");
4093 mStepServerFailed = false;
4094 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004095
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004096 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004097
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004098 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004099 uint32_t s = cblk->server;
4100 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4101
4102 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4103 if (framesReq > framesReady) {
4104 framesReq = framesReady;
4105 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004106 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004107 framesReq = bufferEnd - s;
4108 }
4109
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004110 buffer->raw = getBuffer(s, framesReq);
4111 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004112
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004113 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004114 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004115 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004116
4117getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004118 buffer->raw = NULL;
4119 buffer->frameCount = 0;
4120 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4121 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004122}
4123
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004124uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004125 return mCblk->framesReady();
4126}
4127
Mathias Agopian65ab4712010-07-14 17:59:35 -07004128bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004129 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004130
John Grossman4ff14ba2012-02-08 16:37:41 -08004131 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004132 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4133 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004134 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004135 return true;
4136 }
4137 return false;
4138}
4139
Glenn Kasten3acbd052012-02-28 10:39:56 -08004140status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004141 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004142{
4143 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004144 ALOGV("start(%d), calling pid %d session %d",
4145 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004146
Mathias Agopian65ab4712010-07-14 17:59:35 -07004147 sp<ThreadBase> thread = mThread.promote();
4148 if (thread != 0) {
4149 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004150 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004151 // here the track could be either new, or restarted
4152 // in both cases "unstop" the track
4153 if (mState == PAUSED) {
4154 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004155 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004156 } else {
4157 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004158 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004159 }
4160
4161 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4162 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004163 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004164 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004165
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004166#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004167 // to track the speaker usage
4168 if (status == NO_ERROR) {
4169 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4170 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004171#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004172 }
4173 if (status == NO_ERROR) {
4174 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4175 playbackThread->addTrack_l(this);
4176 } else {
4177 mState = state;
4178 }
4179 } else {
4180 status = BAD_VALUE;
4181 }
4182 return status;
4183}
4184
4185void AudioFlinger::PlaybackThread::Track::stop()
4186{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004187 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004188 sp<ThreadBase> thread = mThread.promote();
4189 if (thread != 0) {
4190 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004191 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004192 if (mState > STOPPED) {
4193 mState = STOPPED;
4194 // If the track is not active (PAUSED and buffers full), flush buffers
4195 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4196 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4197 reset();
4198 }
Steve Block3856b092011-10-20 11:56:00 +01004199 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200 }
4201 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4202 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004203 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004204 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004205
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004206#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004207 // to track the speaker usage
4208 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004209#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004210 }
4211 }
4212}
4213
4214void AudioFlinger::PlaybackThread::Track::pause()
4215{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004216 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004217 sp<ThreadBase> thread = mThread.promote();
4218 if (thread != 0) {
4219 Mutex::Autolock _l(thread->mLock);
4220 if (mState == ACTIVE || mState == RESUMING) {
4221 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004222 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004223 if (!isOutputTrack()) {
4224 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004225 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004226 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004227
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004228#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004229 // to track the speaker usage
4230 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004231#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004232 }
4233 }
4234 }
4235}
4236
4237void AudioFlinger::PlaybackThread::Track::flush()
4238{
Steve Block3856b092011-10-20 11:56:00 +01004239 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004240 sp<ThreadBase> thread = mThread.promote();
4241 if (thread != 0) {
4242 Mutex::Autolock _l(thread->mLock);
4243 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
4244 return;
4245 }
4246 // No point remaining in PAUSED state after a flush => go to
4247 // STOPPED state
4248 mState = STOPPED;
4249
Eric Laurent38ccae22011-03-28 18:37:07 -07004250 // do not reset the track if it is still in the process of being stopped or paused.
4251 // this will be done by prepareTracks_l() when the track is stopped.
4252 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4253 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4254 reset();
4255 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004256 }
4257}
4258
4259void AudioFlinger::PlaybackThread::Track::reset()
4260{
4261 // Do not reset twice to avoid discarding data written just after a flush and before
4262 // the audioflinger thread detects the track is stopped.
4263 if (!mResetDone) {
4264 TrackBase::reset();
4265 // Force underrun condition to avoid false underrun callback until first data is
4266 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004267 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4268 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004269 mFillingUpStatus = FS_FILLING;
4270 mResetDone = true;
Eric Laurenta011e352012-03-29 15:51:43 -07004271 mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004272 }
4273}
4274
4275void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4276{
4277 mMute = muted;
4278}
4279
Mathias Agopian65ab4712010-07-14 17:59:35 -07004280status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4281{
4282 status_t status = DEAD_OBJECT;
4283 sp<ThreadBase> thread = mThread.promote();
4284 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004285 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4286 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004287 }
4288 return status;
4289}
4290
4291void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4292{
4293 mAuxEffectId = EffectId;
4294 mAuxBuffer = buffer;
4295}
4296
Eric Laurenta011e352012-03-29 15:51:43 -07004297bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4298 size_t audioHalFrames)
4299{
4300 // a track is considered presented when the total number of frames written to audio HAL
4301 // corresponds to the number of frames written when presentationComplete() is called for the
4302 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4303 if (mPresentationCompleteFrames == 0) {
4304 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4305 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4306 mPresentationCompleteFrames, audioHalFrames);
4307 }
4308 if (framesWritten >= mPresentationCompleteFrames) {
4309 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4310 mSessionId, framesWritten);
4311 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
4312 mPresentationCompleteFrames = 0;
4313 return true;
4314 }
4315 return false;
4316}
4317
4318void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4319{
4320 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4321 if (mSyncEvents[i]->type() == type) {
4322 mSyncEvents[i]->trigger();
4323 mSyncEvents.removeAt(i);
4324 i--;
4325 }
4326 }
4327}
4328
Glenn Kasten58912562012-04-03 10:45:00 -07004329// implement VolumeBufferProvider interface
4330
4331uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4332{
4333 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4334 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4335 uint32_t vlr = mCblk->getVolumeLR();
4336 uint32_t vl = vlr & 0xFFFF;
4337 uint32_t vr = vlr >> 16;
4338 // track volumes come from shared memory, so can't be trusted and must be clamped
4339 if (vl > MAX_GAIN_INT) {
4340 vl = MAX_GAIN_INT;
4341 }
4342 if (vr > MAX_GAIN_INT) {
4343 vr = MAX_GAIN_INT;
4344 }
4345 // now apply the cached master volume and stream type volume;
4346 // this is trusted but lacks any synchronization or barrier so may be stale
4347 float v = mCachedVolume;
4348 vl *= v;
4349 vr *= v;
4350 // re-combine into U4.16
4351 vlr = (vr << 16) | (vl & 0xFFFF);
4352 // FIXME look at mute, pause, and stop flags
4353 return vlr;
4354}
Eric Laurenta011e352012-03-29 15:51:43 -07004355
John Grossman4ff14ba2012-02-08 16:37:41 -08004356// timed audio tracks
4357
4358sp<AudioFlinger::PlaybackThread::TimedTrack>
4359AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004360 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004361 const sp<Client>& client,
4362 audio_stream_type_t streamType,
4363 uint32_t sampleRate,
4364 audio_format_t format,
4365 uint32_t channelMask,
4366 int frameCount,
4367 const sp<IMemory>& sharedBuffer,
4368 int sessionId) {
4369 if (!client->reserveTimedTrack())
4370 return NULL;
4371
Glenn Kastena0356762012-03-19 10:38:51 -07004372 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004373 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4374 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004375}
4376
4377AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004378 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004379 const sp<Client>& client,
4380 audio_stream_type_t streamType,
4381 uint32_t sampleRate,
4382 audio_format_t format,
4383 uint32_t channelMask,
4384 int frameCount,
4385 const sp<IMemory>& sharedBuffer,
4386 int sessionId)
4387 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004388 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004389 mQueueHeadInFlight(false),
4390 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004391 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004392 mTimedSilenceBuffer(NULL),
4393 mTimedSilenceBufferSize(0),
4394 mTimedAudioOutputOnTime(false),
4395 mMediaTimeTransformValid(false)
4396{
4397 LocalClock lc;
4398 mLocalTimeFreq = lc.getLocalFreq();
4399
4400 mLocalTimeToSampleTransform.a_zero = 0;
4401 mLocalTimeToSampleTransform.b_zero = 0;
4402 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4403 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4404 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4405 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004406
4407 mMediaTimeToSampleTransform.a_zero = 0;
4408 mMediaTimeToSampleTransform.b_zero = 0;
4409 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4410 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4411 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4412 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004413}
4414
4415AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4416 mClient->releaseTimedTrack();
4417 delete [] mTimedSilenceBuffer;
4418}
4419
4420status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4421 size_t size, sp<IMemory>* buffer) {
4422
4423 Mutex::Autolock _l(mTimedBufferQueueLock);
4424
4425 trimTimedBufferQueue_l();
4426
4427 // lazily initialize the shared memory heap for timed buffers
4428 if (mTimedMemoryDealer == NULL) {
4429 const int kTimedBufferHeapSize = 512 << 10;
4430
4431 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4432 "AudioFlingerTimed");
4433 if (mTimedMemoryDealer == NULL)
4434 return NO_MEMORY;
4435 }
4436
4437 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4438 if (newBuffer == NULL) {
4439 newBuffer = mTimedMemoryDealer->allocate(size);
4440 if (newBuffer == NULL)
4441 return NO_MEMORY;
4442 }
4443
4444 *buffer = newBuffer;
4445 return NO_ERROR;
4446}
4447
4448// caller must hold mTimedBufferQueueLock
4449void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4450 int64_t mediaTimeNow;
4451 {
4452 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4453 if (!mMediaTimeTransformValid)
4454 return;
4455
4456 int64_t targetTimeNow;
4457 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4458 ? mCCHelper.getCommonTime(&targetTimeNow)
4459 : mCCHelper.getLocalTime(&targetTimeNow);
4460
4461 if (OK != res)
4462 return;
4463
4464 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4465 &mediaTimeNow)) {
4466 return;
4467 }
4468 }
4469
John Grossman1c345192012-03-27 14:00:17 -07004470 size_t trimEnd;
4471 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004472 int64_t bufEnd;
4473
John Grossmanc95cfbb2012-04-12 11:53:11 -07004474 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4475 // We have a next buffer. Just use its PTS as the PTS of the frame
4476 // following the last frame in this buffer. If the stream is sparse
4477 // (ie, there are deliberate gaps left in the stream which should be
4478 // filled with silence by the TimedAudioTrack), then this can result
4479 // in one extra buffer being left un-trimmed when it could have
4480 // been. In general, this is not typical, and we would rather
4481 // optimized away the TS calculation below for the more common case
4482 // where PTSes are contiguous.
4483 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4484 } else {
4485 // We have no next buffer. Compute the PTS of the frame following
4486 // the last frame in this buffer by computing the duration of of
4487 // this frame in media time units and adding it to the PTS of the
4488 // buffer.
4489 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4490 / mCblk->frameSize;
4491
4492 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4493 &bufEnd)) {
4494 ALOGE("Failed to convert frame count of %lld to media time"
4495 " duration" " (scale factor %d/%u) in %s",
4496 frameCount,
4497 mMediaTimeToSampleTransform.a_to_b_numer,
4498 mMediaTimeToSampleTransform.a_to_b_denom,
4499 __PRETTY_FUNCTION__);
4500 break;
4501 }
4502 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004503 }
John Grossman9fbdee12012-03-26 17:51:46 -07004504
4505 if (bufEnd > mediaTimeNow)
4506 break;
4507
4508 // Is the buffer we want to use in the middle of a mix operation right
4509 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4510 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004511 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004512 mTrimQueueHeadOnRelease = true;
4513 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004514 }
4515
John Grossman9fbdee12012-03-26 17:51:46 -07004516 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004517 if (trimStart < trimEnd) {
4518 // Update the bookkeeping for framesReady()
4519 for (size_t i = trimStart; i < trimEnd; ++i) {
4520 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4521 }
4522
4523 // Now actually remove the buffers from the queue.
4524 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004525 }
4526}
4527
John Grossman1c345192012-03-27 14:00:17 -07004528void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4529 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004530 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4531 "%s called (reason \"%s\"), but timed buffer queue has no"
4532 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004533
4534 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4535 mTimedBufferQueue.removeAt(0);
4536}
4537
4538void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4539 const TimedBuffer& buf,
4540 const char* logTag) {
4541 uint32_t bufBytes = buf.buffer()->size();
4542 uint32_t consumedAlready = buf.position();
4543
Eric Laurentb388e532012-04-14 13:32:48 -07004544 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004545 "Bad bookkeeping while updating frames pending. Timed buffer is"
4546 " only %u bytes long, but claims to have consumed %u"
4547 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004548 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004549
4550 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004551 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4552 "Bad bookkeeping while updating frames pending. Should have at"
4553 " least %u queued frames, but we think we have only %u. (update"
4554 " reason: \"%s\")",
4555 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004556
4557 mFramesPendingInQueue -= bufFrames;
4558}
4559
John Grossman4ff14ba2012-02-08 16:37:41 -08004560status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4561 const sp<IMemory>& buffer, int64_t pts) {
4562
4563 {
4564 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4565 if (!mMediaTimeTransformValid)
4566 return INVALID_OPERATION;
4567 }
4568
4569 Mutex::Autolock _l(mTimedBufferQueueLock);
4570
John Grossman1c345192012-03-27 14:00:17 -07004571 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4572 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004573 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4574
4575 return NO_ERROR;
4576}
4577
4578status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4579 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4580
John Grossman1c345192012-03-27 14:00:17 -07004581 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4582 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4583 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004584
4585 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4586 target == TimedAudioTrack::COMMON_TIME)) {
4587 return BAD_VALUE;
4588 }
4589
4590 Mutex::Autolock lock(mMediaTimeTransformLock);
4591 mMediaTimeTransform = xform;
4592 mMediaTimeTransformTarget = target;
4593 mMediaTimeTransformValid = true;
4594
4595 return NO_ERROR;
4596}
4597
4598#define min(a, b) ((a) < (b) ? (a) : (b))
4599
4600// implementation of getNextBuffer for tracks whose buffers have timestamps
4601status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4602 AudioBufferProvider::Buffer* buffer, int64_t pts)
4603{
4604 if (pts == AudioBufferProvider::kInvalidPTS) {
4605 buffer->raw = 0;
4606 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07004607 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004608 return INVALID_OPERATION;
4609 }
4610
John Grossman4ff14ba2012-02-08 16:37:41 -08004611 Mutex::Autolock _l(mTimedBufferQueueLock);
4612
John Grossman9fbdee12012-03-26 17:51:46 -07004613 ALOG_ASSERT(!mQueueHeadInFlight,
4614 "getNextBuffer called without releaseBuffer!");
4615
John Grossman4ff14ba2012-02-08 16:37:41 -08004616 while (true) {
4617
4618 // if we have no timed buffers, then fail
4619 if (mTimedBufferQueue.isEmpty()) {
4620 buffer->raw = 0;
4621 buffer->frameCount = 0;
4622 return NOT_ENOUGH_DATA;
4623 }
4624
4625 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4626
4627 // calculate the PTS of the head of the timed buffer queue expressed in
4628 // local time
4629 int64_t headLocalPTS;
4630 {
4631 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4632
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004633 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004634
4635 if (mMediaTimeTransform.a_to_b_denom == 0) {
4636 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07004637 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004638 return NO_ERROR;
4639 }
4640
4641 int64_t transformedPTS;
4642 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4643 &transformedPTS)) {
4644 // the transform failed. this shouldn't happen, but if it does
4645 // then just drop this buffer
4646 ALOGW("timedGetNextBuffer transform failed");
4647 buffer->raw = 0;
4648 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07004649 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08004650 return NO_ERROR;
4651 }
4652
4653 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4654 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4655 &headLocalPTS)) {
4656 buffer->raw = 0;
4657 buffer->frameCount = 0;
4658 return INVALID_OPERATION;
4659 }
4660 } else {
4661 headLocalPTS = transformedPTS;
4662 }
4663 }
4664
4665 // adjust the head buffer's PTS to reflect the portion of the head buffer
4666 // that has already been consumed
4667 int64_t effectivePTS = headLocalPTS +
4668 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4669
4670 // Calculate the delta in samples between the head of the input buffer
4671 // queue and the start of the next output buffer that will be written.
4672 // If the transformation fails because of over or underflow, it means
4673 // that the sample's position in the output stream is so far out of
4674 // whack that it should just be dropped.
4675 int64_t sampleDelta;
4676 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4677 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004678 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
4679 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08004680 continue;
4681 }
4682 if (!mLocalTimeToSampleTransform.doForwardTransform(
4683 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07004684 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004685 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08004686 continue;
4687 }
4688
John Grossman1c345192012-03-27 14:00:17 -07004689 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
4690 " sampleDelta=[%d.%08x]",
4691 head.pts(), head.position(), pts,
4692 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
4693 + (sampleDelta >> 32)),
4694 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08004695
4696 // if the delta between the ideal placement for the next input sample and
4697 // the current output position is within this threshold, then we will
4698 // concatenate the next input samples to the previous output
4699 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07004700 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08004701
4702 // if this is the first buffer of audio that we're emitting from this track
4703 // then it should be almost exactly on time.
4704 const int64_t kSampleStartupThreshold = 1LL << 32;
4705
4706 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07004707 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004708 // the next input is close enough to being on time, so concatenate it
4709 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07004710 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004711
John Grossman1c345192012-03-27 14:00:17 -07004712 ALOGVV("*** on time: head.pos=%d frameCount=%u",
4713 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08004714 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07004715 }
4716
4717 // Looks like our output is not on time. Reset our on timed status.
4718 // Next time we mix samples from our input queue, then should be within
4719 // the StartupThreshold.
4720 mTimedAudioOutputOnTime = false;
4721 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004722 // the gap between the current output position and the proper start of
4723 // the next input sample is too big, so fill it with silence
4724 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4725
John Grossman9fbdee12012-03-26 17:51:46 -07004726 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004727 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4728 return NO_ERROR;
4729 } else {
4730 // the next input sample is late
4731 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4732 size_t onTimeSamplePosition =
4733 head.position() + lateFrames * mCblk->frameSize;
4734
4735 if (onTimeSamplePosition > head.buffer()->size()) {
4736 // all the remaining samples in the head are too late, so
4737 // drop it and move on
4738 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004739 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08004740 continue;
4741 } else {
4742 // skip over the late samples
4743 head.setPosition(onTimeSamplePosition);
4744
4745 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07004746 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004747
4748 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4749 return NO_ERROR;
4750 }
4751 }
4752 }
4753}
4754
4755// Yield samples from the timed buffer queue head up to the given output
4756// buffer's capacity.
4757//
4758// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004759void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004760 AudioBufferProvider::Buffer* buffer) {
4761
4762 const TimedBuffer& head = mTimedBufferQueue[0];
4763
4764 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4765 head.position());
4766
4767 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4768 mCblk->frameSize);
4769 size_t framesRequested = buffer->frameCount;
4770 buffer->frameCount = min(framesLeftInHead, framesRequested);
4771
John Grossman9fbdee12012-03-26 17:51:46 -07004772 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08004773 mTimedAudioOutputOnTime = true;
4774}
4775
4776// Yield samples of silence up to the given output buffer's capacity
4777//
4778// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004779void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004780 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4781
4782 // lazily allocate a buffer filled with silence
4783 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4784 delete [] mTimedSilenceBuffer;
4785 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4786 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4787 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4788 }
4789
4790 buffer->raw = mTimedSilenceBuffer;
4791 size_t framesRequested = buffer->frameCount;
4792 buffer->frameCount = min(numFrames, framesRequested);
4793
4794 mTimedAudioOutputOnTime = false;
4795}
4796
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004797// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004798void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4799 AudioBufferProvider::Buffer* buffer) {
4800
4801 Mutex::Autolock _l(mTimedBufferQueueLock);
4802
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004803 // If the buffer which was just released is part of the buffer at the head
4804 // of the queue, be sure to update the amt of the buffer which has been
4805 // consumed. If the buffer being returned is not part of the head of the
4806 // queue, its either because the buffer is part of the silence buffer, or
4807 // because the head of the timed queue was trimmed after the mixer called
4808 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07004809 if (buffer->raw == mTimedSilenceBuffer) {
4810 ALOG_ASSERT(!mQueueHeadInFlight,
4811 "Queue head in flight during release of silence buffer!");
4812 goto done;
4813 }
4814
4815 ALOG_ASSERT(mQueueHeadInFlight,
4816 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
4817 " head in flight.");
4818
4819 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004820 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004821
4822 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07004823 void* end = reinterpret_cast<void*>(
4824 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
4825 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004826
John Grossman9fbdee12012-03-26 17:51:46 -07004827 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
4828 "released buffer not within the head of the timed buffer"
4829 " queue; qHead = [%p, %p], released buffer = %p",
4830 start, end, buffer->raw);
4831
4832 head.setPosition(head.position() +
4833 (buffer->frameCount * mCblk->frameSize));
4834 mQueueHeadInFlight = false;
4835
John Grossman1c345192012-03-27 14:00:17 -07004836 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
4837 "Bad bookkeeping during releaseBuffer! Should have at"
4838 " least %u queued frames, but we think we have only %u",
4839 buffer->frameCount, mFramesPendingInQueue);
4840
4841 mFramesPendingInQueue -= buffer->frameCount;
4842
John Grossman9fbdee12012-03-26 17:51:46 -07004843 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
4844 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07004845 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07004846 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004847 }
John Grossman9fbdee12012-03-26 17:51:46 -07004848 } else {
4849 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
4850 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08004851 }
4852
John Grossman9fbdee12012-03-26 17:51:46 -07004853done:
John Grossman4ff14ba2012-02-08 16:37:41 -08004854 buffer->raw = 0;
4855 buffer->frameCount = 0;
4856}
4857
4858uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4859 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07004860 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08004861}
4862
4863AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4864 : mPTS(0), mPosition(0) {}
4865
4866AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4867 const sp<IMemory>& buffer, int64_t pts)
4868 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4869
Mathias Agopian65ab4712010-07-14 17:59:35 -07004870// ----------------------------------------------------------------------------
4871
4872// RecordTrack constructor must be called with AudioFlinger::mLock held
4873AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004874 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004875 const sp<Client>& client,
4876 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004877 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004878 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004879 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004880 int sessionId)
4881 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004882 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004883 mOverflow(false)
4884{
4885 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004886 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
4887 if (format == AUDIO_FORMAT_PCM_16_BIT) {
4888 mCblk->frameSize = mChannelCount * sizeof(int16_t);
4889 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
4890 mCblk->frameSize = mChannelCount * sizeof(int8_t);
4891 } else {
4892 mCblk->frameSize = sizeof(int8_t);
4893 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004894 }
4895}
4896
4897AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4898{
4899 sp<ThreadBase> thread = mThread.promote();
4900 if (thread != 0) {
4901 AudioSystem::releaseInput(thread->id());
4902 }
4903}
4904
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004905// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004906status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004907{
4908 audio_track_cblk_t* cblk = this->cblk();
4909 uint32_t framesAvail;
4910 uint32_t framesReq = buffer->frameCount;
4911
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004912 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004913 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004914 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01004915 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004916 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004917 }
4918
4919 framesAvail = cblk->framesAvailable_l();
4920
Glenn Kastenf6b16782011-12-15 09:51:17 -08004921 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004922 uint32_t s = cblk->server;
4923 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4924
4925 if (framesReq > framesAvail) {
4926 framesReq = framesAvail;
4927 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004928 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004929 framesReq = bufferEnd - s;
4930 }
4931
4932 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08004933 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004934
4935 buffer->frameCount = framesReq;
4936 return NO_ERROR;
4937 }
4938
4939getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08004940 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004941 buffer->frameCount = 0;
4942 return NOT_ENOUGH_DATA;
4943}
4944
Glenn Kasten3acbd052012-02-28 10:39:56 -08004945status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004946 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004947{
4948 sp<ThreadBase> thread = mThread.promote();
4949 if (thread != 0) {
4950 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08004951 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004952 } else {
4953 return BAD_VALUE;
4954 }
4955}
4956
4957void AudioFlinger::RecordThread::RecordTrack::stop()
4958{
4959 sp<ThreadBase> thread = mThread.promote();
4960 if (thread != 0) {
4961 RecordThread *recordThread = (RecordThread *)thread.get();
4962 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004963 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08004964 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07004965 // read from buffer
4966 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004967 }
4968}
4969
4970void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4971{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004972 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004973 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004974 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004975 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004976 mSessionId,
4977 mFrameCount,
4978 mState,
4979 mCblk->sampleRate,
4980 mCblk->server,
4981 mCblk->user);
4982}
4983
4984
4985// ----------------------------------------------------------------------------
4986
4987AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004988 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004989 DuplicatingThread *sourceThread,
4990 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004991 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004992 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004993 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07004994 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
4995 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004996 mActive(false), mSourceThread(sourceThread)
4997{
4998
Mathias Agopian65ab4712010-07-14 17:59:35 -07004999 if (mCblk != NULL) {
5000 mCblk->flags |= CBLK_DIRECTION_OUT;
5001 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005002 mOutBuffer.frameCount = 0;
5003 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005004 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005005 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5006 mCblk, mBuffer, mCblk->buffers,
5007 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005008 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005009 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005010 }
5011}
5012
5013AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5014{
5015 clearBufferQueue();
5016}
5017
Glenn Kasten3acbd052012-02-28 10:39:56 -08005018status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005019 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005020{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005021 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005022 if (status != NO_ERROR) {
5023 return status;
5024 }
5025
5026 mActive = true;
5027 mRetryCount = 127;
5028 return status;
5029}
5030
5031void AudioFlinger::PlaybackThread::OutputTrack::stop()
5032{
5033 Track::stop();
5034 clearBufferQueue();
5035 mOutBuffer.frameCount = 0;
5036 mActive = false;
5037}
5038
5039bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5040{
5041 Buffer *pInBuffer;
5042 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005043 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005044 bool outputBufferFull = false;
5045 inBuffer.frameCount = frames;
5046 inBuffer.i16 = data;
5047
5048 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5049
5050 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005051 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005052 sp<ThreadBase> thread = mThread.promote();
5053 if (thread != 0) {
5054 MixerThread *mixerThread = (MixerThread *)thread.get();
5055 if (mCblk->frameCount > frames){
5056 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5057 uint32_t startFrames = (mCblk->frameCount - frames);
5058 pInBuffer = new Buffer;
5059 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5060 pInBuffer->frameCount = startFrames;
5061 pInBuffer->i16 = pInBuffer->mBuffer;
5062 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5063 mBufferQueue.add(pInBuffer);
5064 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005065 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005066 }
5067 }
5068 }
5069 }
5070
5071 while (waitTimeLeftMs) {
5072 // First write pending buffers, then new data
5073 if (mBufferQueue.size()) {
5074 pInBuffer = mBufferQueue.itemAt(0);
5075 } else {
5076 pInBuffer = &inBuffer;
5077 }
5078
5079 if (pInBuffer->frameCount == 0) {
5080 break;
5081 }
5082
5083 if (mOutBuffer.frameCount == 0) {
5084 mOutBuffer.frameCount = pInBuffer->frameCount;
5085 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005086 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005087 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005088 outputBufferFull = true;
5089 break;
5090 }
5091 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5092 if (waitTimeLeftMs >= waitTimeMs) {
5093 waitTimeLeftMs -= waitTimeMs;
5094 } else {
5095 waitTimeLeftMs = 0;
5096 }
5097 }
5098
5099 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5100 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5101 mCblk->stepUser(outFrames);
5102 pInBuffer->frameCount -= outFrames;
5103 pInBuffer->i16 += outFrames * channelCount;
5104 mOutBuffer.frameCount -= outFrames;
5105 mOutBuffer.i16 += outFrames * channelCount;
5106
5107 if (pInBuffer->frameCount == 0) {
5108 if (mBufferQueue.size()) {
5109 mBufferQueue.removeAt(0);
5110 delete [] pInBuffer->mBuffer;
5111 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005112 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005113 } else {
5114 break;
5115 }
5116 }
5117 }
5118
5119 // If we could not write all frames, allocate a buffer and queue it for next time.
5120 if (inBuffer.frameCount) {
5121 sp<ThreadBase> thread = mThread.promote();
5122 if (thread != 0 && !thread->standby()) {
5123 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5124 pInBuffer = new Buffer;
5125 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5126 pInBuffer->frameCount = inBuffer.frameCount;
5127 pInBuffer->i16 = pInBuffer->mBuffer;
5128 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5129 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005130 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005131 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005132 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005133 }
5134 }
5135 }
5136
5137 // Calling write() with a 0 length buffer, means that no more data will be written:
5138 // If no more buffers are pending, fill output track buffer to make sure it is started
5139 // by output mixer.
5140 if (frames == 0 && mBufferQueue.size() == 0) {
5141 if (mCblk->user < mCblk->frameCount) {
5142 frames = mCblk->frameCount - mCblk->user;
5143 pInBuffer = new Buffer;
5144 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5145 pInBuffer->frameCount = frames;
5146 pInBuffer->i16 = pInBuffer->mBuffer;
5147 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5148 mBufferQueue.add(pInBuffer);
5149 } else if (mActive) {
5150 stop();
5151 }
5152 }
5153
5154 return outputBufferFull;
5155}
5156
5157status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5158{
5159 int active;
5160 status_t result;
5161 audio_track_cblk_t* cblk = mCblk;
5162 uint32_t framesReq = buffer->frameCount;
5163
Steve Block3856b092011-10-20 11:56:00 +01005164// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005165 buffer->frameCount = 0;
5166
5167 uint32_t framesAvail = cblk->framesAvailable();
5168
5169
5170 if (framesAvail == 0) {
5171 Mutex::Autolock _l(cblk->lock);
5172 goto start_loop_here;
5173 while (framesAvail == 0) {
5174 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005175 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005176 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005177 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005178 }
5179 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5180 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005181 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005182 }
5183 // read the server count again
5184 start_loop_here:
5185 framesAvail = cblk->framesAvailable_l();
5186 }
5187 }
5188
5189// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005190// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005191// }
5192
5193 if (framesReq > framesAvail) {
5194 framesReq = framesAvail;
5195 }
5196
5197 uint32_t u = cblk->user;
5198 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5199
Marco Nelissena1472d92012-03-30 14:36:54 -07005200 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005201 framesReq = bufferEnd - u;
5202 }
5203
5204 buffer->frameCount = framesReq;
5205 buffer->raw = (void *)cblk->buffer(u);
5206 return NO_ERROR;
5207}
5208
5209
5210void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5211{
5212 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005213
5214 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005215 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005216 delete [] pBuffer->mBuffer;
5217 delete pBuffer;
5218 }
5219 mBufferQueue.clear();
5220}
5221
5222// ----------------------------------------------------------------------------
5223
5224AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5225 : RefBase(),
5226 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005227 // 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 -07005228 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005229 mPid(pid),
5230 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005231{
5232 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5233}
5234
5235// Client destructor must be called with AudioFlinger::mLock held
5236AudioFlinger::Client::~Client()
5237{
5238 mAudioFlinger->removeClient_l(mPid);
5239}
5240
Glenn Kasten435dbe62012-01-30 10:15:48 -08005241sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005242{
5243 return mMemoryDealer;
5244}
5245
John Grossman4ff14ba2012-02-08 16:37:41 -08005246// Reserve one of the limited slots for a timed audio track associated
5247// with this client
5248bool AudioFlinger::Client::reserveTimedTrack()
5249{
5250 const int kMaxTimedTracksPerClient = 4;
5251
5252 Mutex::Autolock _l(mTimedTrackLock);
5253
5254 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5255 ALOGW("can not create timed track - pid %d has exceeded the limit",
5256 mPid);
5257 return false;
5258 }
5259
5260 mTimedTrackCount++;
5261 return true;
5262}
5263
5264// Release a slot for a timed audio track
5265void AudioFlinger::Client::releaseTimedTrack()
5266{
5267 Mutex::Autolock _l(mTimedTrackLock);
5268 mTimedTrackCount--;
5269}
5270
Mathias Agopian65ab4712010-07-14 17:59:35 -07005271// ----------------------------------------------------------------------------
5272
5273AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5274 const sp<IAudioFlingerClient>& client,
5275 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005276 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005277{
5278}
5279
5280AudioFlinger::NotificationClient::~NotificationClient()
5281{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005282}
5283
5284void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5285{
5286 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005287 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005288}
5289
5290// ----------------------------------------------------------------------------
5291
5292AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5293 : BnAudioTrack(),
5294 mTrack(track)
5295{
5296}
5297
5298AudioFlinger::TrackHandle::~TrackHandle() {
5299 // just stop the track on deletion, associated resources
5300 // will be freed from the main thread once all pending buffers have
5301 // been played. Unless it's not in the active track list, in which
5302 // case we free everything now...
5303 mTrack->destroy();
5304}
5305
Glenn Kasten90716c52012-01-26 13:40:12 -08005306sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5307 return mTrack->getCblk();
5308}
5309
Glenn Kasten3acbd052012-02-28 10:39:56 -08005310status_t AudioFlinger::TrackHandle::start() {
5311 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005312}
5313
5314void AudioFlinger::TrackHandle::stop() {
5315 mTrack->stop();
5316}
5317
5318void AudioFlinger::TrackHandle::flush() {
5319 mTrack->flush();
5320}
5321
5322void AudioFlinger::TrackHandle::mute(bool e) {
5323 mTrack->mute(e);
5324}
5325
5326void AudioFlinger::TrackHandle::pause() {
5327 mTrack->pause();
5328}
5329
Mathias Agopian65ab4712010-07-14 17:59:35 -07005330status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5331{
5332 return mTrack->attachAuxEffect(EffectId);
5333}
5334
John Grossman4ff14ba2012-02-08 16:37:41 -08005335status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5336 sp<IMemory>* buffer) {
5337 if (!mTrack->isTimedTrack())
5338 return INVALID_OPERATION;
5339
5340 PlaybackThread::TimedTrack* tt =
5341 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5342 return tt->allocateTimedBuffer(size, buffer);
5343}
5344
5345status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5346 int64_t pts) {
5347 if (!mTrack->isTimedTrack())
5348 return INVALID_OPERATION;
5349
5350 PlaybackThread::TimedTrack* tt =
5351 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5352 return tt->queueTimedBuffer(buffer, pts);
5353}
5354
5355status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5356 const LinearTransform& xform, int target) {
5357
5358 if (!mTrack->isTimedTrack())
5359 return INVALID_OPERATION;
5360
5361 PlaybackThread::TimedTrack* tt =
5362 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5363 return tt->setMediaTimeTransform(
5364 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5365}
5366
Mathias Agopian65ab4712010-07-14 17:59:35 -07005367status_t AudioFlinger::TrackHandle::onTransact(
5368 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5369{
5370 return BnAudioTrack::onTransact(code, data, reply, flags);
5371}
5372
5373// ----------------------------------------------------------------------------
5374
5375sp<IAudioRecord> AudioFlinger::openRecord(
5376 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005377 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005378 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005379 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005380 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005381 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005382 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005383 int *sessionId,
5384 status_t *status)
5385{
5386 sp<RecordThread::RecordTrack> recordTrack;
5387 sp<RecordHandle> recordHandle;
5388 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005389 status_t lStatus;
5390 RecordThread *thread;
5391 size_t inFrameCount;
5392 int lSessionId;
5393
5394 // check calling permissions
5395 if (!recordingAllowed()) {
5396 lStatus = PERMISSION_DENIED;
5397 goto Exit;
5398 }
5399
5400 // add client to list
5401 { // scope for mLock
5402 Mutex::Autolock _l(mLock);
5403 thread = checkRecordThread_l(input);
5404 if (thread == NULL) {
5405 lStatus = BAD_VALUE;
5406 goto Exit;
5407 }
5408
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005409 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005410
5411 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005412 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005413 lSessionId = *sessionId;
5414 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005415 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005416 if (sessionId != NULL) {
5417 *sessionId = lSessionId;
5418 }
5419 }
5420 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005421 recordTrack = thread->createRecordTrack_l(client,
5422 sampleRate,
5423 format,
5424 channelMask,
5425 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005426 lSessionId,
5427 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005428 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005429 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005430 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5431 // destructor is called by the TrackBase destructor with mLock held
5432 client.clear();
5433 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005434 goto Exit;
5435 }
5436
5437 // return to handle to client
5438 recordHandle = new RecordHandle(recordTrack);
5439 lStatus = NO_ERROR;
5440
5441Exit:
5442 if (status) {
5443 *status = lStatus;
5444 }
5445 return recordHandle;
5446}
5447
5448// ----------------------------------------------------------------------------
5449
5450AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5451 : BnAudioRecord(),
5452 mRecordTrack(recordTrack)
5453{
5454}
5455
5456AudioFlinger::RecordHandle::~RecordHandle() {
5457 stop();
5458}
5459
Glenn Kasten90716c52012-01-26 13:40:12 -08005460sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5461 return mRecordTrack->getCblk();
5462}
5463
Glenn Kasten3acbd052012-02-28 10:39:56 -08005464status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005465 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005466 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005467}
5468
5469void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005470 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005471 mRecordTrack->stop();
5472}
5473
Mathias Agopian65ab4712010-07-14 17:59:35 -07005474status_t AudioFlinger::RecordHandle::onTransact(
5475 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5476{
5477 return BnAudioRecord::onTransact(code, data, reply, flags);
5478}
5479
5480// ----------------------------------------------------------------------------
5481
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005482AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5483 AudioStreamIn *input,
5484 uint32_t sampleRate,
5485 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005486 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005487 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005488 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005489 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5490 // mRsmpInIndex and mInputBytes set by readInputParameters()
5491 mReqChannelCount(popcount(channels)),
5492 mReqSampleRate(sampleRate)
5493 // mBytesRead is only meaningful while active, and so is cleared in start()
5494 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005495{
Glenn Kasten480b4682012-02-28 12:30:08 -08005496 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005497
Mathias Agopian65ab4712010-07-14 17:59:35 -07005498 readInputParameters();
5499}
5500
5501
5502AudioFlinger::RecordThread::~RecordThread()
5503{
5504 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005505 delete mResampler;
5506 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005507}
5508
5509void AudioFlinger::RecordThread::onFirstRef()
5510{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005511 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005512}
5513
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005514status_t AudioFlinger::RecordThread::readyToRun()
5515{
5516 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005517 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005518 return status;
5519}
5520
Mathias Agopian65ab4712010-07-14 17:59:35 -07005521bool AudioFlinger::RecordThread::threadLoop()
5522{
5523 AudioBufferProvider::Buffer buffer;
5524 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005525 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005526
Eric Laurent44d98482010-09-30 16:12:31 -07005527 nsecs_t lastWarning = 0;
5528
Eric Laurentfeb0db62011-07-22 09:04:31 -07005529 acquireWakeLock();
5530
Mathias Agopian65ab4712010-07-14 17:59:35 -07005531 // start recording
5532 while (!exitPending()) {
5533
5534 processConfigEvents();
5535
5536 { // scope for mLock
5537 Mutex::Autolock _l(mLock);
5538 checkForNewParameters_l();
5539 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5540 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005541 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005542 mStandby = true;
5543 }
5544
5545 if (exitPending()) break;
5546
Eric Laurentfeb0db62011-07-22 09:04:31 -07005547 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005548 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005549 // go to sleep
5550 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005551 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005552 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005553 continue;
5554 }
5555 if (mActiveTrack != 0) {
5556 if (mActiveTrack->mState == TrackBase::PAUSING) {
5557 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005558 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005559 mStandby = true;
5560 }
5561 mActiveTrack.clear();
5562 mStartStopCond.broadcast();
5563 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5564 if (mReqChannelCount != mActiveTrack->channelCount()) {
5565 mActiveTrack.clear();
5566 mStartStopCond.broadcast();
5567 } else if (mBytesRead != 0) {
5568 // record start succeeds only if first read from audio input
5569 // succeeds
5570 if (mBytesRead > 0) {
5571 mActiveTrack->mState = TrackBase::ACTIVE;
5572 } else {
5573 mActiveTrack.clear();
5574 }
5575 mStartStopCond.broadcast();
5576 }
5577 mStandby = false;
5578 }
5579 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005580 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005581 }
5582
5583 if (mActiveTrack != 0) {
5584 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5585 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005586 unlockEffectChains(effectChains);
5587 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005588 continue;
5589 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005590 for (size_t i = 0; i < effectChains.size(); i ++) {
5591 effectChains[i]->process_l();
5592 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005593
Mathias Agopian65ab4712010-07-14 17:59:35 -07005594 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005595 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005596 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08005597 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005598 // no resampling
5599 while (framesOut) {
5600 size_t framesIn = mFrameCount - mRsmpInIndex;
5601 if (framesIn) {
5602 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5603 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5604 if (framesIn > framesOut)
5605 framesIn = framesOut;
5606 mRsmpInIndex += framesIn;
5607 framesOut -= framesIn;
5608 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07005609 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005610 memcpy(dst, src, framesIn * mFrameSize);
5611 } else {
5612 int16_t *src16 = (int16_t *)src;
5613 int16_t *dst16 = (int16_t *)dst;
5614 if (mChannelCount == 1) {
5615 while (framesIn--) {
5616 *dst16++ = *src16;
5617 *dst16++ = *src16++;
5618 }
5619 } else {
5620 while (framesIn--) {
5621 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5622 src16 += 2;
5623 }
5624 }
5625 }
5626 }
5627 if (framesOut && mFrameCount == mRsmpInIndex) {
5628 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005629 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005630 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005631 framesOut = 0;
5632 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005633 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005634 mRsmpInIndex = 0;
5635 }
5636 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005637 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005638 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5639 // Force input into standby so that it tries to
5640 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005641 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005642 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005643 }
5644 mRsmpInIndex = mFrameCount;
5645 framesOut = 0;
5646 buffer.frameCount = 0;
5647 }
5648 }
5649 }
5650 } else {
5651 // resampling
5652
5653 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5654 // alter output frame count as if we were expecting stereo samples
5655 if (mChannelCount == 1 && mReqChannelCount == 1) {
5656 framesOut >>= 1;
5657 }
5658 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5659 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5660 // are 32 bit aligned which should be always true.
5661 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005662 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005663 // the resampler always outputs stereo samples: do post stereo to mono conversion
5664 int16_t *src = (int16_t *)mRsmpOutBuffer;
5665 int16_t *dst = buffer.i16;
5666 while (framesOut--) {
5667 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5668 src += 2;
5669 }
5670 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005671 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005672 }
5673
5674 }
Eric Laurenta011e352012-03-29 15:51:43 -07005675 if (mFramestoDrop == 0) {
5676 mActiveTrack->releaseBuffer(&buffer);
5677 } else {
5678 if (mFramestoDrop > 0) {
5679 mFramestoDrop -= buffer.frameCount;
5680 if (mFramestoDrop < 0) {
5681 mFramestoDrop = 0;
5682 }
5683 }
5684 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005685 mActiveTrack->overflow();
5686 }
5687 // client isn't retrieving buffers fast enough
5688 else {
Eric Laurent44d98482010-09-30 16:12:31 -07005689 if (!mActiveTrack->setOverflow()) {
5690 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08005691 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005692 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07005693 lastWarning = now;
5694 }
5695 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005696 // Release the processor for a while before asking for a new buffer.
5697 // This will give the application more chance to read from the buffer and
5698 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005699 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005700 }
5701 }
Eric Laurentec437d82011-07-26 20:54:46 -07005702 // enable changes in effect chain
5703 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005704 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005705 }
5706
5707 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005708 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005709 }
5710 mActiveTrack.clear();
5711
5712 mStartStopCond.broadcast();
5713
Eric Laurentfeb0db62011-07-22 09:04:31 -07005714 releaseWakeLock();
5715
Steve Block3856b092011-10-20 11:56:00 +01005716 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005717 return false;
5718}
5719
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005720
5721sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5722 const sp<AudioFlinger::Client>& client,
5723 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005724 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005725 int channelMask,
5726 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005727 int sessionId,
5728 status_t *status)
5729{
5730 sp<RecordTrack> track;
5731 status_t lStatus;
5732
5733 lStatus = initCheck();
5734 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005735 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005736 goto Exit;
5737 }
5738
5739 { // scope for mLock
5740 Mutex::Autolock _l(mLock);
5741
5742 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005743 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005744
Glenn Kasten7378ca52012-01-20 13:44:40 -08005745 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005746 lStatus = NO_MEMORY;
5747 goto Exit;
5748 }
5749
5750 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005751 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5752 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005753 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005754 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5755 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005756 }
5757 lStatus = NO_ERROR;
5758
5759Exit:
5760 if (status) {
5761 *status = lStatus;
5762 }
5763 return track;
5764}
5765
Eric Laurenta011e352012-03-29 15:51:43 -07005766status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08005767 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005768 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005769{
Glenn Kasten58912562012-04-03 10:45:00 -07005770 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005771 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005772 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07005773
5774 if (event == AudioSystem::SYNC_EVENT_NONE) {
5775 mSyncStartEvent.clear();
5776 mFramestoDrop = 0;
5777 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
5778 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
5779 triggerSession,
5780 recordTrack->sessionId(),
5781 syncStartEventCallback,
5782 this);
5783 mFramestoDrop = -1;
5784 }
5785
Mathias Agopian65ab4712010-07-14 17:59:35 -07005786 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005787 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005788 if (mActiveTrack != 0) {
5789 if (recordTrack != mActiveTrack.get()) {
5790 status = -EBUSY;
5791 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5792 mActiveTrack->mState = TrackBase::ACTIVE;
5793 }
5794 return status;
5795 }
5796
5797 recordTrack->mState = TrackBase::IDLE;
5798 mActiveTrack = recordTrack;
5799 mLock.unlock();
5800 status_t status = AudioSystem::startInput(mId);
5801 mLock.lock();
5802 if (status != NO_ERROR) {
5803 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07005804 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005805 return status;
5806 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005807 mRsmpInIndex = mFrameCount;
5808 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005809 if (mResampler != NULL) {
5810 mResampler->reset();
5811 }
5812 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005813 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005814 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005815 mWaitWorkCV.signal();
5816 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005817 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005818 mActiveTrack.clear();
5819 status = INVALID_OPERATION;
5820 goto startError;
5821 }
5822 mStartStopCond.wait(mLock);
5823 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005824 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005825 status = BAD_VALUE;
5826 goto startError;
5827 }
Steve Block3856b092011-10-20 11:56:00 +01005828 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005829 return status;
5830 }
5831startError:
5832 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07005833 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005834 return status;
5835}
5836
Eric Laurenta011e352012-03-29 15:51:43 -07005837void AudioFlinger::RecordThread::clearSyncStartEvent()
5838{
5839 if (mSyncStartEvent != 0) {
5840 mSyncStartEvent->cancel();
5841 }
5842 mSyncStartEvent.clear();
5843}
5844
5845void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
5846{
5847 sp<SyncEvent> strongEvent = event.promote();
5848
5849 if (strongEvent != 0) {
5850 RecordThread *me = (RecordThread *)strongEvent->cookie();
5851 me->handleSyncStartEvent(strongEvent);
5852 }
5853}
5854
5855void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
5856{
5857 ALOGV("handleSyncStartEvent() mActiveTrack %p session %d event->listenerSession() %d",
5858 mActiveTrack.get(),
5859 mActiveTrack.get() ? mActiveTrack->sessionId() : 0,
5860 event->listenerSession());
5861
5862 if (mActiveTrack != 0 &&
5863 event == mSyncStartEvent) {
5864 // TODO: use actual buffer filling status instead of 2 buffers when info is available
5865 // from audio HAL
5866 mFramestoDrop = mFrameCount * 2;
5867 mSyncStartEvent.clear();
5868 }
5869}
5870
Mathias Agopian65ab4712010-07-14 17:59:35 -07005871void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01005872 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005873 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005874 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005875 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005876 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5877 mActiveTrack->mState = TrackBase::PAUSING;
5878 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005879 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005880 return;
5881 }
5882 mStartStopCond.wait(mLock);
5883 // if we have been restarted, recordTrack == mActiveTrack.get() here
5884 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5885 mLock.unlock();
5886 AudioSystem::stopInput(mId);
5887 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01005888 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005889 }
5890 }
5891 }
5892}
5893
Eric Laurenta011e352012-03-29 15:51:43 -07005894bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
5895{
5896 return false;
5897}
5898
5899status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
5900{
5901 if (!isValidSyncEvent(event)) {
5902 return BAD_VALUE;
5903 }
5904
5905 Mutex::Autolock _l(mLock);
5906
5907 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
5908 mTrack->setSyncEvent(event);
5909 return NO_ERROR;
5910 }
5911 return NAME_NOT_FOUND;
5912}
5913
Mathias Agopian65ab4712010-07-14 17:59:35 -07005914status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5915{
5916 const size_t SIZE = 256;
5917 char buffer[SIZE];
5918 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005919
5920 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5921 result.append(buffer);
5922
5923 if (mActiveTrack != 0) {
5924 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005925 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005926 mActiveTrack->dump(buffer, SIZE);
5927 result.append(buffer);
5928
5929 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5930 result.append(buffer);
5931 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5932 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08005933 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005934 result.append(buffer);
5935 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5936 result.append(buffer);
5937 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5938 result.append(buffer);
5939
5940
5941 } else {
5942 result.append("No record client\n");
5943 }
5944 write(fd, result.string(), result.size());
5945
5946 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005947 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005948
5949 return NO_ERROR;
5950}
5951
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005952// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005953status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005954{
5955 size_t framesReq = buffer->frameCount;
5956 size_t framesReady = mFrameCount - mRsmpInIndex;
5957 int channelCount;
5958
5959 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005960 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005961 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005962 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005963 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5964 // Force input into standby so that it tries to
5965 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005966 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005967 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005968 }
Glenn Kastene0feee32011-12-13 11:53:26 -08005969 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005970 buffer->frameCount = 0;
5971 return NOT_ENOUGH_DATA;
5972 }
5973 mRsmpInIndex = 0;
5974 framesReady = mFrameCount;
5975 }
5976
5977 if (framesReq > framesReady) {
5978 framesReq = framesReady;
5979 }
5980
5981 if (mChannelCount == 1 && mReqChannelCount == 2) {
5982 channelCount = 1;
5983 } else {
5984 channelCount = 2;
5985 }
5986 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5987 buffer->frameCount = framesReq;
5988 return NO_ERROR;
5989}
5990
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005991// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07005992void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5993{
5994 mRsmpInIndex += buffer->frameCount;
5995 buffer->frameCount = 0;
5996}
5997
5998bool AudioFlinger::RecordThread::checkForNewParameters_l()
5999{
6000 bool reconfig = false;
6001
6002 while (!mNewParameters.isEmpty()) {
6003 status_t status = NO_ERROR;
6004 String8 keyValuePair = mNewParameters[0];
6005 AudioParameter param = AudioParameter(keyValuePair);
6006 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006007 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006008 int reqSamplingRate = mReqSampleRate;
6009 int reqChannelCount = mReqChannelCount;
6010
6011 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6012 reqSamplingRate = value;
6013 reconfig = true;
6014 }
6015 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006016 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006017 reconfig = true;
6018 }
6019 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006020 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006021 reconfig = true;
6022 }
6023 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6024 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006025 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006026 // if frame count is changed after track creation
6027 if (mActiveTrack != 0) {
6028 status = INVALID_OPERATION;
6029 } else {
6030 reconfig = true;
6031 }
6032 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006033 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6034 // forward device change to effects that have requested to be
6035 // aware of attached audio device.
6036 for (size_t i = 0; i < mEffectChains.size(); i++) {
6037 mEffectChains[i]->setDevice_l(value);
6038 }
6039 // store input device and output device but do not forward output device to audio HAL.
6040 // Note that status is ignored by the caller for output device
6041 // (see AudioFlinger::setParameters()
6042 if (value & AUDIO_DEVICE_OUT_ALL) {
6043 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6044 status = BAD_VALUE;
6045 } else {
6046 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006047 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6048 if (mTrack != NULL) {
6049 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006050 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006051 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6052 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6053 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006054 }
6055 mDevice |= (uint32_t)value;
6056 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006057 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006058 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006059 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006060 mInput->stream->common.standby(&mInput->stream->common);
6061 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6062 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006063 }
6064 if (reconfig) {
6065 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006066 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006067 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006068 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006069 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6070 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006071 status = NO_ERROR;
6072 }
6073 if (status == NO_ERROR) {
6074 readInputParameters();
6075 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6076 }
6077 }
6078 }
6079
6080 mNewParameters.removeAt(0);
6081
6082 mParamStatus = status;
6083 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006084 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6085 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006086 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006087 }
6088 return reconfig;
6089}
6090
6091String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6092{
Dima Zavinfce7a472011-04-19 22:30:36 -07006093 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006094 String8 out_s8 = String8();
6095
6096 Mutex::Autolock _l(mLock);
6097 if (initCheck() != NO_ERROR) {
6098 return out_s8;
6099 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006100
Dima Zavin799a70e2011-04-18 16:57:27 -07006101 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006102 out_s8 = String8(s);
6103 free(s);
6104 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006105}
6106
6107void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6108 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006109 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006110
6111 switch (event) {
6112 case AudioSystem::INPUT_OPENED:
6113 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006114 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006115 desc.samplingRate = mSampleRate;
6116 desc.format = mFormat;
6117 desc.frameCount = mFrameCount;
6118 desc.latency = 0;
6119 param2 = &desc;
6120 break;
6121
6122 case AudioSystem::INPUT_CLOSED:
6123 default:
6124 break;
6125 }
6126 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6127}
6128
6129void AudioFlinger::RecordThread::readInputParameters()
6130{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006131 delete mRsmpInBuffer;
6132 // mRsmpInBuffer is always assigned a new[] below
6133 delete mRsmpOutBuffer;
6134 mRsmpOutBuffer = NULL;
6135 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006136 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006137
Dima Zavin799a70e2011-04-18 16:57:27 -07006138 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006139 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6140 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006141 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006142 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006143 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006144 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006145 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006146 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6147
Glenn Kasten53d76db2012-03-08 12:32:47 -08006148 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006149 {
6150 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006151 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6152 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006153 if (mChannelCount == 1 && mReqChannelCount == 2) {
6154 channelCount = 1;
6155 } else {
6156 channelCount = 2;
6157 }
6158 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6159 mResampler->setSampleRate(mSampleRate);
6160 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6161 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6162
6163 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6164 if (mChannelCount == 1 && mReqChannelCount == 1) {
6165 mFrameCount >>= 1;
6166 }
6167
6168 }
6169 mRsmpInIndex = mFrameCount;
6170}
6171
6172unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6173{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006174 Mutex::Autolock _l(mLock);
6175 if (initCheck() != NO_ERROR) {
6176 return 0;
6177 }
6178
Dima Zavin799a70e2011-04-18 16:57:27 -07006179 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006180}
6181
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006182uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6183{
6184 Mutex::Autolock _l(mLock);
6185 uint32_t result = 0;
6186 if (getEffectChain_l(sessionId) != 0) {
6187 result = EFFECT_SESSION;
6188 }
6189
6190 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6191 result |= TRACK_SESSION;
6192 }
6193
6194 return result;
6195}
6196
Eric Laurent59bd0da2011-08-01 09:52:20 -07006197AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6198{
6199 Mutex::Autolock _l(mLock);
6200 return mTrack;
6201}
6202
Glenn Kastenaed850d2012-01-26 09:46:34 -08006203AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006204{
6205 Mutex::Autolock _l(mLock);
6206 return mInput;
6207}
6208
6209AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6210{
6211 Mutex::Autolock _l(mLock);
6212 AudioStreamIn *input = mInput;
6213 mInput = NULL;
6214 return input;
6215}
6216
6217// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006218audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006219{
6220 if (mInput == NULL) {
6221 return NULL;
6222 }
6223 return &mInput->stream->common;
6224}
6225
6226
Mathias Agopian65ab4712010-07-14 17:59:35 -07006227// ----------------------------------------------------------------------------
6228
Eric Laurenta4c5a552012-03-29 10:12:40 -07006229audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6230{
6231 if (!settingsAllowed()) {
6232 return 0;
6233 }
6234 Mutex::Autolock _l(mLock);
6235 return loadHwModule_l(name);
6236}
6237
6238// loadHwModule_l() must be called with AudioFlinger::mLock held
6239audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6240{
6241 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6242 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6243 ALOGW("loadHwModule() module %s already loaded", name);
6244 return mAudioHwDevs.keyAt(i);
6245 }
6246 }
6247
Eric Laurenta4c5a552012-03-29 10:12:40 -07006248 audio_hw_device_t *dev;
6249
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006250 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006251 if (rc) {
6252 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6253 return 0;
6254 }
6255
6256 mHardwareStatus = AUDIO_HW_INIT;
6257 rc = dev->init_check(dev);
6258 mHardwareStatus = AUDIO_HW_IDLE;
6259 if (rc) {
6260 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6261 return 0;
6262 }
6263
6264 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6265 (NULL != dev->set_master_volume)) {
6266 AutoMutex lock(mHardwareLock);
6267 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6268 dev->set_master_volume(dev, mMasterVolume);
6269 mHardwareStatus = AUDIO_HW_IDLE;
6270 }
6271
6272 audio_module_handle_t handle = nextUniqueId();
6273 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6274
6275 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006276 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006277
6278 return handle;
6279
6280}
6281
6282audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6283 audio_devices_t *pDevices,
6284 uint32_t *pSamplingRate,
6285 audio_format_t *pFormat,
6286 audio_channel_mask_t *pChannelMask,
6287 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006288 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006289{
6290 status_t status;
6291 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006292 struct audio_config config = {
6293 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6294 channel_mask: pChannelMask ? *pChannelMask : 0,
6295 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6296 };
6297 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006298 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006299
Eric Laurenta4c5a552012-03-29 10:12:40 -07006300 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6301 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006302 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006303 config.sample_rate,
6304 config.format,
6305 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006306 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006307
6308 if (pDevices == NULL || *pDevices == 0) {
6309 return 0;
6310 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006311
Mathias Agopian65ab4712010-07-14 17:59:35 -07006312 Mutex::Autolock _l(mLock);
6313
Eric Laurenta4c5a552012-03-29 10:12:40 -07006314 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006315 if (outHwDev == NULL)
6316 return 0;
6317
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006318 audio_io_handle_t id = nextUniqueId();
6319
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006320 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006321
6322 status = outHwDev->open_output_stream(outHwDev,
6323 id,
6324 *pDevices,
6325 (audio_output_flags_t)flags,
6326 &config,
6327 &outStream);
6328
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006329 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006330 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006331 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006332 config.sample_rate,
6333 config.format,
6334 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006335 status);
6336
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006337 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006338 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006339
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006340 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006341 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6342 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006343 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006344 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006345 } else {
6346 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006347 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006348 }
6349 mPlaybackThreads.add(id, thread);
6350
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006351 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6352 if (pFormat != NULL) *pFormat = config.format;
6353 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006354 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006355
6356 // notify client processes of the new output creation
6357 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006358
6359 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006360 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006361 ALOGI("Using module %d has the primary audio interface", module);
6362 mPrimaryHardwareDev = outHwDev;
6363
6364 AutoMutex lock(mHardwareLock);
6365 mHardwareStatus = AUDIO_HW_SET_MODE;
6366 outHwDev->set_mode(outHwDev, mMode);
6367
6368 // Determine the level of master volume support the primary audio HAL has,
6369 // and set the initial master volume at the same time.
6370 float initialVolume = 1.0;
6371 mMasterVolumeSupportLvl = MVS_NONE;
6372
6373 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6374 if ((NULL != outHwDev->get_master_volume) &&
6375 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6376 mMasterVolumeSupportLvl = MVS_FULL;
6377 } else {
6378 mMasterVolumeSupportLvl = MVS_SETONLY;
6379 initialVolume = 1.0;
6380 }
6381
6382 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6383 if ((NULL == outHwDev->set_master_volume) ||
6384 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6385 mMasterVolumeSupportLvl = MVS_NONE;
6386 }
6387 // now that we have a primary device, initialize master volume on other devices
6388 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6389 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6390
6391 if ((dev != mPrimaryHardwareDev) &&
6392 (NULL != dev->set_master_volume)) {
6393 dev->set_master_volume(dev, initialVolume);
6394 }
6395 }
6396 mHardwareStatus = AUDIO_HW_IDLE;
6397 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6398 ? initialVolume
6399 : 1.0;
6400 mMasterVolume = initialVolume;
6401 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006402 return id;
6403 }
6404
6405 return 0;
6406}
6407
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006408audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6409 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006410{
6411 Mutex::Autolock _l(mLock);
6412 MixerThread *thread1 = checkMixerThread_l(output1);
6413 MixerThread *thread2 = checkMixerThread_l(output2);
6414
6415 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006416 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006417 return 0;
6418 }
6419
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006420 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006421 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6422 thread->addOutputTrack(thread2);
6423 mPlaybackThreads.add(id, thread);
6424 // notify client processes of the new output creation
6425 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6426 return id;
6427}
6428
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006429status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006430{
6431 // keep strong reference on the playback thread so that
6432 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006433 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006434 {
6435 Mutex::Autolock _l(mLock);
6436 thread = checkPlaybackThread_l(output);
6437 if (thread == NULL) {
6438 return BAD_VALUE;
6439 }
6440
Steve Block3856b092011-10-20 11:56:00 +01006441 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006442
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006443 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006444 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006445 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006446 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6447 dupThread->removeOutputTrack((MixerThread *)thread.get());
6448 }
6449 }
6450 }
Glenn Kastena1117922012-01-26 10:53:32 -08006451 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006452 mPlaybackThreads.removeItem(output);
6453 }
6454 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006455 // The thread entity (active unit of execution) is no longer running here,
6456 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006457
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006458 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006459 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006460 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006461 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006462 out->hwDev->close_output_stream(out->hwDev, out->stream);
6463 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006464 }
6465 return NO_ERROR;
6466}
6467
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006468status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006469{
6470 Mutex::Autolock _l(mLock);
6471 PlaybackThread *thread = checkPlaybackThread_l(output);
6472
6473 if (thread == NULL) {
6474 return BAD_VALUE;
6475 }
6476
Steve Block3856b092011-10-20 11:56:00 +01006477 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006478 thread->suspend();
6479
6480 return NO_ERROR;
6481}
6482
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006483status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006484{
6485 Mutex::Autolock _l(mLock);
6486 PlaybackThread *thread = checkPlaybackThread_l(output);
6487
6488 if (thread == NULL) {
6489 return BAD_VALUE;
6490 }
6491
Steve Block3856b092011-10-20 11:56:00 +01006492 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006493
6494 thread->restore();
6495
6496 return NO_ERROR;
6497}
6498
Eric Laurenta4c5a552012-03-29 10:12:40 -07006499audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6500 audio_devices_t *pDevices,
6501 uint32_t *pSamplingRate,
6502 audio_format_t *pFormat,
6503 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006504{
6505 status_t status;
6506 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006507 struct audio_config config = {
6508 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6509 channel_mask: pChannelMask ? *pChannelMask : 0,
6510 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6511 };
6512 uint32_t reqSamplingRate = config.sample_rate;
6513 audio_format_t reqFormat = config.format;
6514 audio_channel_mask_t reqChannels = config.channel_mask;
6515 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006516 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006517
6518 if (pDevices == NULL || *pDevices == 0) {
6519 return 0;
6520 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006521
Mathias Agopian65ab4712010-07-14 17:59:35 -07006522 Mutex::Autolock _l(mLock);
6523
Eric Laurenta4c5a552012-03-29 10:12:40 -07006524 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006525 if (inHwDev == NULL)
6526 return 0;
6527
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006528 audio_io_handle_t id = nextUniqueId();
6529
6530 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006531 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006532 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006533 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006534 config.sample_rate,
6535 config.format,
6536 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006537 status);
6538
6539 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6540 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6541 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006542 if (status == BAD_VALUE &&
6543 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6544 (config.sample_rate <= 2 * reqSamplingRate) &&
6545 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006546 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006547 inStream = NULL;
6548 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006549 }
6550
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006551 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006552 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6553
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006554 // Start record thread
6555 // RecorThread require both input and output device indication to forward to audio
6556 // pre processing modules
6557 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6558 thread = new RecordThread(this,
6559 input,
6560 reqSamplingRate,
6561 reqChannels,
6562 id,
6563 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006564 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006565 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006566 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006567 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006568 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006569
Dima Zavin799a70e2011-04-18 16:57:27 -07006570 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006571
6572 // notify client processes of the new input creation
6573 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6574 return id;
6575 }
6576
6577 return 0;
6578}
6579
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006580status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006581{
6582 // keep strong reference on the record thread so that
6583 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006584 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006585 {
6586 Mutex::Autolock _l(mLock);
6587 thread = checkRecordThread_l(input);
6588 if (thread == NULL) {
6589 return BAD_VALUE;
6590 }
6591
Steve Block3856b092011-10-20 11:56:00 +01006592 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08006593 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006594 mRecordThreads.removeItem(input);
6595 }
6596 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006597 // The thread entity (active unit of execution) is no longer running here,
6598 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006599
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006600 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006601 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006602 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006603 in->hwDev->close_input_stream(in->hwDev, in->stream);
6604 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006605
6606 return NO_ERROR;
6607}
6608
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006609status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006610{
6611 Mutex::Autolock _l(mLock);
6612 MixerThread *dstThread = checkMixerThread_l(output);
6613 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006614 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006615 return BAD_VALUE;
6616 }
6617
Steve Block3856b092011-10-20 11:56:00 +01006618 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006619 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
6620
6621 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6622 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08006623 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006624 MixerThread *srcThread = (MixerThread *)thread;
6625 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006626 }
Eric Laurentde070132010-07-13 04:45:46 -07006627 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006628
6629 return NO_ERROR;
6630}
6631
6632
6633int AudioFlinger::newAudioSessionId()
6634{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006635 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006636}
6637
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006638void AudioFlinger::acquireAudioSessionId(int audioSession)
6639{
6640 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006641 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006642 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006643 size_t num = mAudioSessionRefs.size();
6644 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006645 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006646 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6647 ref->mCnt++;
6648 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006649 return;
6650 }
6651 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006652 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6653 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006654}
6655
6656void AudioFlinger::releaseAudioSessionId(int audioSession)
6657{
6658 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006659 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006660 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006661 size_t num = mAudioSessionRefs.size();
6662 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006663 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006664 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6665 ref->mCnt--;
6666 ALOGV(" decremented refcount to %d", ref->mCnt);
6667 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006668 mAudioSessionRefs.removeAt(i);
6669 delete ref;
6670 purgeStaleEffects_l();
6671 }
6672 return;
6673 }
6674 }
Steve Block5ff1dd52012-01-05 23:22:43 +00006675 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006676}
6677
6678void AudioFlinger::purgeStaleEffects_l() {
6679
Steve Block3856b092011-10-20 11:56:00 +01006680 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006681
6682 Vector< sp<EffectChain> > chains;
6683
6684 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6685 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6686 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6687 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07006688 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6689 chains.push(ec);
6690 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006691 }
6692 }
6693 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6694 sp<RecordThread> t = mRecordThreads.valueAt(i);
6695 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6696 sp<EffectChain> ec = t->mEffectChains[j];
6697 chains.push(ec);
6698 }
6699 }
6700
6701 for (size_t i = 0; i < chains.size(); i++) {
6702 sp<EffectChain> ec = chains[i];
6703 int sessionid = ec->sessionId();
6704 sp<ThreadBase> t = ec->mThread.promote();
6705 if (t == 0) {
6706 continue;
6707 }
6708 size_t numsessionrefs = mAudioSessionRefs.size();
6709 bool found = false;
6710 for (size_t k = 0; k < numsessionrefs; k++) {
6711 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006712 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01006713 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006714 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006715 found = true;
6716 break;
6717 }
6718 }
6719 if (!found) {
6720 // remove all effects from the chain
6721 while (ec->mEffects.size()) {
6722 sp<EffectModule> effect = ec->mEffects[0];
6723 effect->unPin();
6724 Mutex::Autolock _l (t->mLock);
6725 t->removeEffect_l(effect);
6726 for (size_t j = 0; j < effect->mHandles.size(); j++) {
6727 sp<EffectHandle> handle = effect->mHandles[j].promote();
6728 if (handle != 0) {
6729 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07006730 if (handle->mHasControl && handle->mEnabled) {
6731 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
6732 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006733 }
6734 }
6735 AudioSystem::unregisterEffect(effect->id());
6736 }
6737 }
6738 }
6739 return;
6740}
6741
Mathias Agopian65ab4712010-07-14 17:59:35 -07006742// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006743AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006744{
Glenn Kastena1117922012-01-26 10:53:32 -08006745 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006746}
6747
6748// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006749AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006750{
6751 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08006752 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006753}
6754
6755// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006756AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006757{
Glenn Kastena1117922012-01-26 10:53:32 -08006758 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006759}
6760
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006761uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07006762{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006763 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006764}
6765
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006766AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006767{
6768 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6769 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006770 AudioStreamOut *output = thread->getOutput();
6771 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006772 return thread;
6773 }
6774 }
6775 return NULL;
6776}
6777
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006778uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006779{
6780 PlaybackThread *thread = primaryPlaybackThread_l();
6781
6782 if (thread == NULL) {
6783 return 0;
6784 }
6785
6786 return thread->device();
6787}
6788
Eric Laurenta011e352012-03-29 15:51:43 -07006789sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
6790 int triggerSession,
6791 int listenerSession,
6792 sync_event_callback_t callBack,
6793 void *cookie)
6794{
6795 Mutex::Autolock _l(mLock);
6796
6797 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
6798 status_t playStatus = NAME_NOT_FOUND;
6799 status_t recStatus = NAME_NOT_FOUND;
6800 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6801 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
6802 if (playStatus == NO_ERROR) {
6803 return event;
6804 }
6805 }
6806 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6807 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
6808 if (recStatus == NO_ERROR) {
6809 return event;
6810 }
6811 }
6812 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
6813 mPendingSyncEvents.add(event);
6814 } else {
6815 ALOGV("createSyncEvent() invalid event %d", event->type());
6816 event.clear();
6817 }
6818 return event;
6819}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006820
Mathias Agopian65ab4712010-07-14 17:59:35 -07006821// ----------------------------------------------------------------------------
6822// Effect management
6823// ----------------------------------------------------------------------------
6824
6825
Glenn Kastenf587ba52012-01-26 16:25:10 -08006826status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006827{
6828 Mutex::Autolock _l(mLock);
6829 return EffectQueryNumberEffects(numEffects);
6830}
6831
Glenn Kastenf587ba52012-01-26 16:25:10 -08006832status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006833{
6834 Mutex::Autolock _l(mLock);
6835 return EffectQueryEffect(index, descriptor);
6836}
6837
Glenn Kasten5e92a782012-01-30 07:40:52 -08006838status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08006839 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006840{
6841 Mutex::Autolock _l(mLock);
6842 return EffectGetDescriptor(pUuid, descriptor);
6843}
6844
6845
Mathias Agopian65ab4712010-07-14 17:59:35 -07006846sp<IEffect> AudioFlinger::createEffect(pid_t pid,
6847 effect_descriptor_t *pDesc,
6848 const sp<IEffectClient>& effectClient,
6849 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006850 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006851 int sessionId,
6852 status_t *status,
6853 int *id,
6854 int *enabled)
6855{
6856 status_t lStatus = NO_ERROR;
6857 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006858 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006859
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006860 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006861 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006862
6863 if (pDesc == NULL) {
6864 lStatus = BAD_VALUE;
6865 goto Exit;
6866 }
6867
Eric Laurent84e9a102010-09-23 16:10:16 -07006868 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006869 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006870 lStatus = PERMISSION_DENIED;
6871 goto Exit;
6872 }
6873
Dima Zavinfce7a472011-04-19 22:30:36 -07006874 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07006875 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08006876 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006877 lStatus = PERMISSION_DENIED;
6878 goto Exit;
6879 }
6880
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006881 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006882 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006883 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07006884 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07006885 lStatus = BAD_VALUE;
6886 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07006887 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006888 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006889 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07006890 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006891 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07006892 }
6893 }
6894
Mathias Agopian65ab4712010-07-14 17:59:35 -07006895 {
6896 Mutex::Autolock _l(mLock);
6897
Mathias Agopian65ab4712010-07-14 17:59:35 -07006898
6899 if (!EffectIsNullUuid(&pDesc->uuid)) {
6900 // if uuid is specified, request effect descriptor
6901 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
6902 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006903 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006904 goto Exit;
6905 }
6906 } else {
6907 // if uuid is not specified, look for an available implementation
6908 // of the required type in effect factory
6909 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006910 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006911 lStatus = BAD_VALUE;
6912 goto Exit;
6913 }
6914 uint32_t numEffects = 0;
6915 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006916 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07006917 bool found = false;
6918
6919 lStatus = EffectQueryNumberEffects(&numEffects);
6920 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006921 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006922 goto Exit;
6923 }
6924 for (uint32_t i = 0; i < numEffects; i++) {
6925 lStatus = EffectQueryEffect(i, &desc);
6926 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006927 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006928 continue;
6929 }
6930 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
6931 // If matching type found save effect descriptor. If the session is
6932 // 0 and the effect is not auxiliary, continue enumeration in case
6933 // an auxiliary version of this effect type is available
6934 found = true;
6935 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07006936 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006937 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6938 break;
6939 }
6940 }
6941 }
6942 if (!found) {
6943 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00006944 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006945 goto Exit;
6946 }
6947 // For same effect type, chose auxiliary version over insert version if
6948 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07006949 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006950 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
6951 memcpy(&desc, &d, sizeof(effect_descriptor_t));
6952 }
6953 }
6954
6955 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07006956 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07006957 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6958 lStatus = INVALID_OPERATION;
6959 goto Exit;
6960 }
6961
Eric Laurent59255e42011-07-27 19:49:51 -07006962 // check recording permission for visualizer
6963 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
6964 !recordingAllowed()) {
6965 lStatus = PERMISSION_DENIED;
6966 goto Exit;
6967 }
6968
Mathias Agopian65ab4712010-07-14 17:59:35 -07006969 // return effect descriptor
6970 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6971
6972 // If output is not specified try to find a matching audio session ID in one of the
6973 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07006974 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6975 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006976 // Note: io is never 0 when creating an effect on an input
6977 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006978 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07006979 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6980 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006981 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006982 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006983 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006984 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006985 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006986 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6987 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6988 io = mRecordThreads.keyAt(i);
6989 break;
6990 }
6991 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006992 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006993 // If no output thread contains the requested session ID, default to
6994 // first output. The effect chain will be moved to the correct output
6995 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006996 if (io == 0 && mPlaybackThreads.size()) {
6997 io = mPlaybackThreads.keyAt(0);
6998 }
Steve Block3856b092011-10-20 11:56:00 +01006999 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007000 }
7001 ThreadBase *thread = checkRecordThread_l(io);
7002 if (thread == NULL) {
7003 thread = checkPlaybackThread_l(io);
7004 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007005 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007006 lStatus = BAD_VALUE;
7007 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007008 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007009 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007010
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007011 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007012
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007013 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007014 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7015 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007016 if (handle != 0 && id != NULL) {
7017 *id = handle->id();
7018 }
7019 }
7020
7021Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007022 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007023 *status = lStatus;
7024 }
7025 return handle;
7026}
7027
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007028status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7029 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007030{
Steve Block3856b092011-10-20 11:56:00 +01007031 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007032 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007033 Mutex::Autolock _l(mLock);
7034 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007035 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007036 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007037 }
Eric Laurentde070132010-07-13 04:45:46 -07007038 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7039 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007040 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007041 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007042 }
Eric Laurentde070132010-07-13 04:45:46 -07007043 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7044 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007045 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007046 return BAD_VALUE;
7047 }
7048
7049 Mutex::Autolock _dl(dstThread->mLock);
7050 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007051 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007052
Mathias Agopian65ab4712010-07-14 17:59:35 -07007053 return NO_ERROR;
7054}
7055
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007056// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007057status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007058 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007059 AudioFlinger::PlaybackThread *dstThread,
7060 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007061{
Steve Block3856b092011-10-20 11:56:00 +01007062 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007063 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007064
Eric Laurent59255e42011-07-27 19:49:51 -07007065 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007066 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007067 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007068 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007069 return INVALID_OPERATION;
7070 }
7071
Eric Laurent39e94f82010-07-28 01:32:47 -07007072 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007073 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007074 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007075 // removed.
7076 srcThread->removeEffectChain_l(chain);
7077
7078 // transfer all effects one by one so that new effect chain is created on new thread with
7079 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007080 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007081 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007082 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007083 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7084 while (effect != 0) {
7085 srcThread->removeEffect_l(effect);
7086 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007087 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7088 if (effect->state() == EffectModule::ACTIVE ||
7089 effect->state() == EffectModule::STOPPING) {
7090 effect->start();
7091 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007092 // if the move request is not received from audio policy manager, the effect must be
7093 // re-registered with the new strategy and output
7094 if (dstChain == 0) {
7095 dstChain = effect->chain().promote();
7096 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007097 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007098 srcThread->addEffect_l(effect);
7099 return NO_INIT;
7100 }
7101 strategy = dstChain->strategy();
7102 }
7103 if (reRegister) {
7104 AudioSystem::unregisterEffect(effect->id());
7105 AudioSystem::registerEffect(&effect->desc(),
7106 dstOutput,
7107 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007108 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007109 effect->id());
7110 }
Eric Laurentde070132010-07-13 04:45:46 -07007111 effect = chain->getEffectFromId_l(0);
7112 }
7113
7114 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007115}
7116
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007117
Mathias Agopian65ab4712010-07-14 17:59:35 -07007118// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007119sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007120 const sp<AudioFlinger::Client>& client,
7121 const sp<IEffectClient>& effectClient,
7122 int32_t priority,
7123 int sessionId,
7124 effect_descriptor_t *desc,
7125 int *enabled,
7126 status_t *status
7127 )
7128{
7129 sp<EffectModule> effect;
7130 sp<EffectHandle> handle;
7131 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007132 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007133 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007134 bool effectCreated = false;
7135 bool effectRegistered = false;
7136
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007137 lStatus = initCheck();
7138 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007139 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007140 goto Exit;
7141 }
7142
7143 // Do not allow effects with session ID 0 on direct output or duplicating threads
7144 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007145 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007146 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007147 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007148 lStatus = BAD_VALUE;
7149 goto Exit;
7150 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007151 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007152 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007153 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007154 desc->name, desc->flags, mType);
7155 lStatus = BAD_VALUE;
7156 goto Exit;
7157 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007158
Steve Block3856b092011-10-20 11:56:00 +01007159 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007160
7161 { // scope for mLock
7162 Mutex::Autolock _l(mLock);
7163
7164 // check for existing effect chain with the requested audio session
7165 chain = getEffectChain_l(sessionId);
7166 if (chain == 0) {
7167 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007168 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007169 chain = new EffectChain(this, sessionId);
7170 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007171 chain->setStrategy(getStrategyForSession_l(sessionId));
7172 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007173 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007174 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007175 }
7176
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007177 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007178
7179 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007180 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007181 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007182 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007183 if (lStatus != NO_ERROR) {
7184 goto Exit;
7185 }
7186 effectRegistered = true;
7187 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007188 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007189 lStatus = effect->status();
7190 if (lStatus != NO_ERROR) {
7191 goto Exit;
7192 }
Eric Laurentcab11242010-07-15 12:50:15 -07007193 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007194 if (lStatus != NO_ERROR) {
7195 goto Exit;
7196 }
7197 effectCreated = true;
7198
7199 effect->setDevice(mDevice);
7200 effect->setMode(mAudioFlinger->getMode());
7201 }
7202 // create effect handle and connect it to effect module
7203 handle = new EffectHandle(effect, client, effectClient, priority);
7204 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08007205 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007206 *enabled = (int)effect->isEnabled();
7207 }
7208 }
7209
7210Exit:
7211 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007212 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007213 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007214 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007215 }
7216 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007217 AudioSystem::unregisterEffect(effect->id());
7218 }
7219 if (chainCreated) {
7220 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007221 }
7222 handle.clear();
7223 }
7224
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007225 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007226 *status = lStatus;
7227 }
7228 return handle;
7229}
7230
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007231sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7232{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007233 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007234 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007235}
7236
Eric Laurentde070132010-07-13 04:45:46 -07007237// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7238// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007239status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007240{
7241 // check for existing effect chain with the requested audio session
7242 int sessionId = effect->sessionId();
7243 sp<EffectChain> chain = getEffectChain_l(sessionId);
7244 bool chainCreated = false;
7245
7246 if (chain == 0) {
7247 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007248 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007249 chain = new EffectChain(this, sessionId);
7250 addEffectChain_l(chain);
7251 chain->setStrategy(getStrategyForSession_l(sessionId));
7252 chainCreated = true;
7253 }
Steve Block3856b092011-10-20 11:56:00 +01007254 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007255
7256 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007257 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007258 this, effect->desc().name, chain.get());
7259 return BAD_VALUE;
7260 }
7261
7262 status_t status = chain->addEffect_l(effect);
7263 if (status != NO_ERROR) {
7264 if (chainCreated) {
7265 removeEffectChain_l(chain);
7266 }
7267 return status;
7268 }
7269
7270 effect->setDevice(mDevice);
7271 effect->setMode(mAudioFlinger->getMode());
7272 return NO_ERROR;
7273}
7274
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007275void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007276
Steve Block3856b092011-10-20 11:56:00 +01007277 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007278 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007279 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7280 detachAuxEffect_l(effect->id());
7281 }
7282
7283 sp<EffectChain> chain = effect->chain().promote();
7284 if (chain != 0) {
7285 // remove effect chain if removing last effect
7286 if (chain->removeEffect_l(effect) == 0) {
7287 removeEffectChain_l(chain);
7288 }
7289 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007290 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007291 }
7292}
7293
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007294void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007295 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007296{
7297 effectChains = mEffectChains;
7298 for (size_t i = 0; i < mEffectChains.size(); i++) {
7299 mEffectChains[i]->lock();
7300 }
7301}
7302
7303void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007304 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007305{
7306 for (size_t i = 0; i < effectChains.size(); i++) {
7307 effectChains[i]->unlock();
7308 }
7309}
7310
7311sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7312{
7313 Mutex::Autolock _l(mLock);
7314 return getEffectChain_l(sessionId);
7315}
7316
7317sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7318{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007319 size_t size = mEffectChains.size();
7320 for (size_t i = 0; i < size; i++) {
7321 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007322 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007323 }
7324 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007325 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007326}
7327
Glenn Kastenf78aee72012-01-04 11:00:47 -08007328void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007329{
7330 Mutex::Autolock _l(mLock);
7331 size_t size = mEffectChains.size();
7332 for (size_t i = 0; i < size; i++) {
7333 mEffectChains[i]->setMode_l(mode);
7334 }
7335}
7336
7337void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007338 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007339 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007340
Mathias Agopian65ab4712010-07-14 17:59:35 -07007341 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007342 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007343 // delete the effect module if removing last handle on it
7344 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007345 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007346 removeEffect_l(effect);
7347 AudioSystem::unregisterEffect(effect->id());
7348 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007349 }
7350}
7351
7352status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7353{
7354 int session = chain->sessionId();
7355 int16_t *buffer = mMixBuffer;
7356 bool ownsBuffer = false;
7357
Steve Block3856b092011-10-20 11:56:00 +01007358 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007359 if (session > 0) {
7360 // Only one effect chain can be present in direct output thread and it uses
7361 // the mix buffer as input
7362 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007363 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007364 buffer = new int16_t[numSamples];
7365 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007366 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007367 ownsBuffer = true;
7368 }
7369
7370 // Attach all tracks with same session ID to this chain.
7371 for (size_t i = 0; i < mTracks.size(); ++i) {
7372 sp<Track> track = mTracks[i];
7373 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007374 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007375 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007376 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007377 }
7378 }
7379
7380 // indicate all active tracks in the chain
7381 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7382 sp<Track> track = mActiveTracks[i].promote();
7383 if (track == 0) continue;
7384 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007385 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007386 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007387 }
7388 }
7389 }
7390
7391 chain->setInBuffer(buffer, ownsBuffer);
7392 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007393 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007394 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007395 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7396 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007397 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007398 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7399 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007400 // Effect chain for other sessions are inserted at beginning of effect
7401 // chains list to be processed before output mix effects. Relative order between other
7402 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007403 size_t size = mEffectChains.size();
7404 size_t i = 0;
7405 for (i = 0; i < size; i++) {
7406 if (mEffectChains[i]->sessionId() < session) break;
7407 }
7408 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007409 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007410
7411 return NO_ERROR;
7412}
7413
7414size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7415{
7416 int session = chain->sessionId();
7417
Steve Block3856b092011-10-20 11:56:00 +01007418 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007419
7420 for (size_t i = 0; i < mEffectChains.size(); i++) {
7421 if (chain == mEffectChains[i]) {
7422 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007423 // detach all active tracks from the chain
7424 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7425 sp<Track> track = mActiveTracks[i].promote();
7426 if (track == 0) continue;
7427 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007428 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007429 chain.get(), session);
7430 chain->decActiveTrackCnt();
7431 }
7432 }
7433
Mathias Agopian65ab4712010-07-14 17:59:35 -07007434 // detach all tracks with same session ID from this chain
7435 for (size_t i = 0; i < mTracks.size(); ++i) {
7436 sp<Track> track = mTracks[i];
7437 if (session == track->sessionId()) {
7438 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007439 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007440 }
7441 }
Eric Laurentde070132010-07-13 04:45:46 -07007442 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007443 }
7444 }
7445 return mEffectChains.size();
7446}
7447
Eric Laurentde070132010-07-13 04:45:46 -07007448status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7449 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007450{
7451 Mutex::Autolock _l(mLock);
7452 return attachAuxEffect_l(track, EffectId);
7453}
7454
Eric Laurentde070132010-07-13 04:45:46 -07007455status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7456 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007457{
7458 status_t status = NO_ERROR;
7459
7460 if (EffectId == 0) {
7461 track->setAuxBuffer(0, NULL);
7462 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007463 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7464 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007465 if (effect != 0) {
7466 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7467 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7468 } else {
7469 status = INVALID_OPERATION;
7470 }
7471 } else {
7472 status = BAD_VALUE;
7473 }
7474 }
7475 return status;
7476}
7477
7478void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7479{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007480 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007481 sp<Track> track = mTracks[i];
7482 if (track->auxEffectId() == effectId) {
7483 attachAuxEffect_l(track, 0);
7484 }
7485 }
7486}
7487
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007488status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7489{
7490 // only one chain per input thread
7491 if (mEffectChains.size() != 0) {
7492 return INVALID_OPERATION;
7493 }
Steve Block3856b092011-10-20 11:56:00 +01007494 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007495
7496 chain->setInBuffer(NULL);
7497 chain->setOutBuffer(NULL);
7498
Eric Laurent59255e42011-07-27 19:49:51 -07007499 checkSuspendOnAddEffectChain_l(chain);
7500
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007501 mEffectChains.add(chain);
7502
7503 return NO_ERROR;
7504}
7505
7506size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7507{
Steve Block3856b092011-10-20 11:56:00 +01007508 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007509 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007510 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7511 chain.get(), mEffectChains.size(), this);
7512 if (mEffectChains.size() == 1) {
7513 mEffectChains.removeAt(0);
7514 }
7515 return 0;
7516}
7517
Mathias Agopian65ab4712010-07-14 17:59:35 -07007518// ----------------------------------------------------------------------------
7519// EffectModule implementation
7520// ----------------------------------------------------------------------------
7521
7522#undef LOG_TAG
7523#define LOG_TAG "AudioFlinger::EffectModule"
7524
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007525AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007526 const wp<AudioFlinger::EffectChain>& chain,
7527 effect_descriptor_t *desc,
7528 int id,
7529 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007530 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007531 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007532{
Steve Block3856b092011-10-20 11:56:00 +01007533 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007534 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007535 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007536 return;
7537 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007538
7539 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7540
7541 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007542 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007543
7544 if (mStatus != NO_ERROR) {
7545 return;
7546 }
7547 lStatus = init();
7548 if (lStatus < 0) {
7549 mStatus = lStatus;
7550 goto Error;
7551 }
7552
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007553 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
7554 mPinned = true;
7555 }
Steve Block3856b092011-10-20 11:56:00 +01007556 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007557 return;
7558Error:
7559 EffectRelease(mEffectInterface);
7560 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007561 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007562}
7563
7564AudioFlinger::EffectModule::~EffectModule()
7565{
Steve Block3856b092011-10-20 11:56:00 +01007566 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007567 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007568 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7569 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7570 sp<ThreadBase> thread = mThread.promote();
7571 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007572 audio_stream_t *stream = thread->stream();
7573 if (stream != NULL) {
7574 stream->remove_audio_effect(stream, mEffectInterface);
7575 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007576 }
7577 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007578 // release effect engine
7579 EffectRelease(mEffectInterface);
7580 }
7581}
7582
Glenn Kasten435dbe62012-01-30 10:15:48 -08007583status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007584{
7585 status_t status;
7586
7587 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007588 int priority = handle->priority();
7589 size_t size = mHandles.size();
7590 sp<EffectHandle> h;
7591 size_t i;
7592 for (i = 0; i < size; i++) {
7593 h = mHandles[i].promote();
7594 if (h == 0) continue;
7595 if (h->priority() <= priority) break;
7596 }
7597 // if inserted in first place, move effect control from previous owner to this handle
7598 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007599 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007600 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007601 enabled = h->enabled();
7602 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007603 }
Eric Laurent59255e42011-07-27 19:49:51 -07007604 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007605 status = NO_ERROR;
7606 } else {
7607 status = ALREADY_EXISTS;
7608 }
Steve Block3856b092011-10-20 11:56:00 +01007609 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007610 mHandles.insertAt(handle, i);
7611 return status;
7612}
7613
7614size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
7615{
7616 Mutex::Autolock _l(mLock);
7617 size_t size = mHandles.size();
7618 size_t i;
7619 for (i = 0; i < size; i++) {
7620 if (mHandles[i] == handle) break;
7621 }
7622 if (i == size) {
7623 return size;
7624 }
Steve Block3856b092011-10-20 11:56:00 +01007625 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07007626
7627 bool enabled = false;
7628 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08007629 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01007630 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07007631 enabled = hdl->enabled();
7632 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007633 mHandles.removeAt(i);
7634 size = mHandles.size();
7635 // if removed from first place, move effect control from this handle to next in line
7636 if (i == 0 && size != 0) {
7637 sp<EffectHandle> h = mHandles[0].promote();
7638 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007639 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007640 }
7641 }
7642
Eric Laurentec437d82011-07-26 20:54:46 -07007643 // Prevent calls to process() and other functions on effect interface from now on.
7644 // The effect engine will be released by the destructor when the last strong reference on
7645 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007646 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07007647 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07007648 }
7649
Mathias Agopian65ab4712010-07-14 17:59:35 -07007650 return size;
7651}
7652
Eric Laurent59255e42011-07-27 19:49:51 -07007653sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7654{
7655 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08007656 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007657}
7658
Glenn Kasten58123c32012-02-03 10:32:24 -08007659void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007660{
Glenn Kasten90bebef2012-01-27 15:24:38 -08007661 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007662 // keep a strong reference on this EffectModule to avoid calling the
7663 // destructor before we exit
7664 sp<EffectModule> keep(this);
7665 {
7666 sp<ThreadBase> thread = mThread.promote();
7667 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007668 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007669 }
7670 }
7671}
7672
7673void AudioFlinger::EffectModule::updateState() {
7674 Mutex::Autolock _l(mLock);
7675
7676 switch (mState) {
7677 case RESTART:
7678 reset_l();
7679 // FALL THROUGH
7680
7681 case STARTING:
7682 // clear auxiliary effect input buffer for next accumulation
7683 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7684 memset(mConfig.inputCfg.buffer.raw,
7685 0,
7686 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7687 }
7688 start_l();
7689 mState = ACTIVE;
7690 break;
7691 case STOPPING:
7692 stop_l();
7693 mDisableWaitCnt = mMaxDisableWaitCnt;
7694 mState = STOPPED;
7695 break;
7696 case STOPPED:
7697 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
7698 // turn off sequence.
7699 if (--mDisableWaitCnt == 0) {
7700 reset_l();
7701 mState = IDLE;
7702 }
7703 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007704 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07007705 break;
7706 }
7707}
7708
7709void AudioFlinger::EffectModule::process()
7710{
7711 Mutex::Autolock _l(mLock);
7712
Eric Laurentec437d82011-07-26 20:54:46 -07007713 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007714 mConfig.inputCfg.buffer.raw == NULL ||
7715 mConfig.outputCfg.buffer.raw == NULL) {
7716 return;
7717 }
7718
Eric Laurent8f45bd72010-08-31 13:50:07 -07007719 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007720 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
7721 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08007722 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007723 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07007724 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007725 }
7726
7727 // do the actual processing in the effect engine
7728 int ret = (*mEffectInterface)->process(mEffectInterface,
7729 &mConfig.inputCfg.buffer,
7730 &mConfig.outputCfg.buffer);
7731
7732 // force transition to IDLE state when engine is ready
7733 if (mState == STOPPED && ret == -ENODATA) {
7734 mDisableWaitCnt = 1;
7735 }
7736
7737 // clear auxiliary effect input buffer for next accumulation
7738 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08007739 memset(mConfig.inputCfg.buffer.raw, 0,
7740 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007741 }
7742 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08007743 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7744 // If an insert effect is idle and input buffer is different from output buffer,
7745 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07007746 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07007747 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08007748 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
7749 int16_t *in = mConfig.inputCfg.buffer.s16;
7750 int16_t *out = mConfig.outputCfg.buffer.s16;
7751 for (size_t i = 0; i < frameCnt; i++) {
7752 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007753 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007754 }
7755 }
7756}
7757
7758void AudioFlinger::EffectModule::reset_l()
7759{
7760 if (mEffectInterface == NULL) {
7761 return;
7762 }
7763 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
7764}
7765
7766status_t AudioFlinger::EffectModule::configure()
7767{
7768 uint32_t channels;
7769 if (mEffectInterface == NULL) {
7770 return NO_INIT;
7771 }
7772
7773 sp<ThreadBase> thread = mThread.promote();
7774 if (thread == 0) {
7775 return DEAD_OBJECT;
7776 }
7777
7778 // TODO: handle configuration of effects replacing track process
7779 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007780 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007781 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07007782 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007783 }
7784
7785 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007786 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007787 } else {
7788 mConfig.inputCfg.channels = channels;
7789 }
7790 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07007791 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
7792 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007793 mConfig.inputCfg.samplingRate = thread->sampleRate();
7794 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
7795 mConfig.inputCfg.bufferProvider.cookie = NULL;
7796 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
7797 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
7798 mConfig.outputCfg.bufferProvider.cookie = NULL;
7799 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
7800 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
7801 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
7802 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07007803 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07007804 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07007805 // - in other sessions:
7806 // last effect in the chain accumulates in output buffer: input buffer != output buffer
7807 // other effect: overwrites output buffer: input buffer == output buffer
7808 // Auxiliary effect:
7809 // accumulates in output buffer: input buffer != output buffer
7810 // Therefore: accumulate <=> input buffer != output buffer
7811 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7812 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
7813 } else {
7814 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
7815 }
7816 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
7817 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
7818 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
7819 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
7820
Steve Block3856b092011-10-20 11:56:00 +01007821 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07007822 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
7823
Mathias Agopian65ab4712010-07-14 17:59:35 -07007824 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007825 uint32_t size = sizeof(int);
7826 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08007827 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07007828 sizeof(effect_config_t),
7829 &mConfig,
7830 &size,
7831 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007832 if (status == 0) {
7833 status = cmdStatus;
7834 }
7835
7836 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
7837 (1000 * mConfig.outputCfg.buffer.frameCount);
7838
7839 return status;
7840}
7841
7842status_t AudioFlinger::EffectModule::init()
7843{
7844 Mutex::Autolock _l(mLock);
7845 if (mEffectInterface == NULL) {
7846 return NO_INIT;
7847 }
7848 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007849 uint32_t size = sizeof(status_t);
7850 status_t status = (*mEffectInterface)->command(mEffectInterface,
7851 EFFECT_CMD_INIT,
7852 0,
7853 NULL,
7854 &size,
7855 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007856 if (status == 0) {
7857 status = cmdStatus;
7858 }
7859 return status;
7860}
7861
Eric Laurentec35a142011-10-05 17:42:25 -07007862status_t AudioFlinger::EffectModule::start()
7863{
7864 Mutex::Autolock _l(mLock);
7865 return start_l();
7866}
7867
Mathias Agopian65ab4712010-07-14 17:59:35 -07007868status_t AudioFlinger::EffectModule::start_l()
7869{
7870 if (mEffectInterface == NULL) {
7871 return NO_INIT;
7872 }
7873 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007874 uint32_t size = sizeof(status_t);
7875 status_t status = (*mEffectInterface)->command(mEffectInterface,
7876 EFFECT_CMD_ENABLE,
7877 0,
7878 NULL,
7879 &size,
7880 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007881 if (status == 0) {
7882 status = cmdStatus;
7883 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007884 if (status == 0 &&
7885 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7886 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7887 sp<ThreadBase> thread = mThread.promote();
7888 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007889 audio_stream_t *stream = thread->stream();
7890 if (stream != NULL) {
7891 stream->add_audio_effect(stream, mEffectInterface);
7892 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007893 }
7894 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007895 return status;
7896}
7897
Eric Laurentec437d82011-07-26 20:54:46 -07007898status_t AudioFlinger::EffectModule::stop()
7899{
7900 Mutex::Autolock _l(mLock);
7901 return stop_l();
7902}
7903
Mathias Agopian65ab4712010-07-14 17:59:35 -07007904status_t AudioFlinger::EffectModule::stop_l()
7905{
7906 if (mEffectInterface == NULL) {
7907 return NO_INIT;
7908 }
7909 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007910 uint32_t size = sizeof(status_t);
7911 status_t status = (*mEffectInterface)->command(mEffectInterface,
7912 EFFECT_CMD_DISABLE,
7913 0,
7914 NULL,
7915 &size,
7916 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007917 if (status == 0) {
7918 status = cmdStatus;
7919 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007920 if (status == 0 &&
7921 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7922 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
7923 sp<ThreadBase> thread = mThread.promote();
7924 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007925 audio_stream_t *stream = thread->stream();
7926 if (stream != NULL) {
7927 stream->remove_audio_effect(stream, mEffectInterface);
7928 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007929 }
7930 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007931 return status;
7932}
7933
Eric Laurent25f43952010-07-28 05:40:18 -07007934status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
7935 uint32_t cmdSize,
7936 void *pCmdData,
7937 uint32_t *replySize,
7938 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007939{
7940 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007941// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007942
Eric Laurentec437d82011-07-26 20:54:46 -07007943 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007944 return NO_INIT;
7945 }
Eric Laurent25f43952010-07-28 05:40:18 -07007946 status_t status = (*mEffectInterface)->command(mEffectInterface,
7947 cmdCode,
7948 cmdSize,
7949 pCmdData,
7950 replySize,
7951 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007952 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007953 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007954 for (size_t i = 1; i < mHandles.size(); i++) {
7955 sp<EffectHandle> h = mHandles[i].promote();
7956 if (h != 0) {
7957 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7958 }
7959 }
7960 }
7961 return status;
7962}
7963
7964status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7965{
Eric Laurentdb7c0792011-08-10 10:37:50 -07007966
Mathias Agopian65ab4712010-07-14 17:59:35 -07007967 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007968 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007969
7970 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007971 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7972 if (enabled && status != NO_ERROR) {
7973 return status;
7974 }
7975
Mathias Agopian65ab4712010-07-14 17:59:35 -07007976 switch (mState) {
7977 // going from disabled to enabled
7978 case IDLE:
7979 mState = STARTING;
7980 break;
7981 case STOPPED:
7982 mState = RESTART;
7983 break;
7984 case STOPPING:
7985 mState = ACTIVE;
7986 break;
7987
7988 // going from enabled to disabled
7989 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007990 mState = STOPPED;
7991 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007992 case STARTING:
7993 mState = IDLE;
7994 break;
7995 case ACTIVE:
7996 mState = STOPPING;
7997 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007998 case DESTROYED:
7999 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008000 }
8001 for (size_t i = 1; i < mHandles.size(); i++) {
8002 sp<EffectHandle> h = mHandles[i].promote();
8003 if (h != 0) {
8004 h->setEnabled(enabled);
8005 }
8006 }
8007 }
8008 return NO_ERROR;
8009}
8010
Glenn Kastenc59c0042012-02-02 14:06:11 -08008011bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008012{
8013 switch (mState) {
8014 case RESTART:
8015 case STARTING:
8016 case ACTIVE:
8017 return true;
8018 case IDLE:
8019 case STOPPING:
8020 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008021 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008022 default:
8023 return false;
8024 }
8025}
8026
Glenn Kastenc59c0042012-02-02 14:06:11 -08008027bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008028{
8029 switch (mState) {
8030 case RESTART:
8031 case ACTIVE:
8032 case STOPPING:
8033 case STOPPED:
8034 return true;
8035 case IDLE:
8036 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008037 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008038 default:
8039 return false;
8040 }
8041}
8042
Mathias Agopian65ab4712010-07-14 17:59:35 -07008043status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8044{
8045 Mutex::Autolock _l(mLock);
8046 status_t status = NO_ERROR;
8047
8048 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8049 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008050 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008051 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8052 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008053 status_t cmdStatus;
8054 uint32_t volume[2];
8055 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008056 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008057 volume[0] = *left;
8058 volume[1] = *right;
8059 if (controller) {
8060 pVolume = volume;
8061 }
Eric Laurent25f43952010-07-28 05:40:18 -07008062 status = (*mEffectInterface)->command(mEffectInterface,
8063 EFFECT_CMD_SET_VOLUME,
8064 size,
8065 volume,
8066 &size,
8067 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008068 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8069 *left = volume[0];
8070 *right = volume[1];
8071 }
8072 }
8073 return status;
8074}
8075
8076status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8077{
8078 Mutex::Autolock _l(mLock);
8079 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008080 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8081 // audio pre processing modules on RecordThread can receive both output and
8082 // input device indication in the same call
8083 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8084 if (dev) {
8085 status_t cmdStatus;
8086 uint32_t size = sizeof(status_t);
8087
8088 status = (*mEffectInterface)->command(mEffectInterface,
8089 EFFECT_CMD_SET_DEVICE,
8090 sizeof(uint32_t),
8091 &dev,
8092 &size,
8093 &cmdStatus);
8094 if (status == NO_ERROR) {
8095 status = cmdStatus;
8096 }
8097 }
8098 dev = device & AUDIO_DEVICE_IN_ALL;
8099 if (dev) {
8100 status_t cmdStatus;
8101 uint32_t size = sizeof(status_t);
8102
8103 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8104 EFFECT_CMD_SET_INPUT_DEVICE,
8105 sizeof(uint32_t),
8106 &dev,
8107 &size,
8108 &cmdStatus);
8109 if (status2 == NO_ERROR) {
8110 status2 = cmdStatus;
8111 }
8112 if (status == NO_ERROR) {
8113 status = status2;
8114 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008115 }
8116 }
8117 return status;
8118}
8119
Glenn Kastenf78aee72012-01-04 11:00:47 -08008120status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008121{
8122 Mutex::Autolock _l(mLock);
8123 status_t status = NO_ERROR;
8124 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008125 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008126 uint32_t size = sizeof(status_t);
8127 status = (*mEffectInterface)->command(mEffectInterface,
8128 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008129 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008130 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008131 &size,
8132 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008133 if (status == NO_ERROR) {
8134 status = cmdStatus;
8135 }
8136 }
8137 return status;
8138}
8139
Eric Laurent59255e42011-07-27 19:49:51 -07008140void AudioFlinger::EffectModule::setSuspended(bool suspended)
8141{
8142 Mutex::Autolock _l(mLock);
8143 mSuspended = suspended;
8144}
Glenn Kastena3a85482012-01-04 11:01:11 -08008145
8146bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008147{
8148 Mutex::Autolock _l(mLock);
8149 return mSuspended;
8150}
8151
Mathias Agopian65ab4712010-07-14 17:59:35 -07008152status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8153{
8154 const size_t SIZE = 256;
8155 char buffer[SIZE];
8156 String8 result;
8157
8158 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8159 result.append(buffer);
8160
8161 bool locked = tryLock(mLock);
8162 // failed to lock - AudioFlinger is probably deadlocked
8163 if (!locked) {
8164 result.append("\t\tCould not lock Fx mutex:\n");
8165 }
8166
8167 result.append("\t\tSession Status State Engine:\n");
8168 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8169 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8170 result.append(buffer);
8171
8172 result.append("\t\tDescriptor:\n");
8173 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8174 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8175 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8176 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8177 result.append(buffer);
8178 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8179 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8180 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8181 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8182 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008183 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008184 mDescriptor.apiVersion,
8185 mDescriptor.flags);
8186 result.append(buffer);
8187 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8188 mDescriptor.name);
8189 result.append(buffer);
8190 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8191 mDescriptor.implementor);
8192 result.append(buffer);
8193
8194 result.append("\t\t- Input configuration:\n");
8195 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8196 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8197 (uint32_t)mConfig.inputCfg.buffer.raw,
8198 mConfig.inputCfg.buffer.frameCount,
8199 mConfig.inputCfg.samplingRate,
8200 mConfig.inputCfg.channels,
8201 mConfig.inputCfg.format);
8202 result.append(buffer);
8203
8204 result.append("\t\t- Output configuration:\n");
8205 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8206 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8207 (uint32_t)mConfig.outputCfg.buffer.raw,
8208 mConfig.outputCfg.buffer.frameCount,
8209 mConfig.outputCfg.samplingRate,
8210 mConfig.outputCfg.channels,
8211 mConfig.outputCfg.format);
8212 result.append(buffer);
8213
8214 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8215 result.append(buffer);
8216 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8217 for (size_t i = 0; i < mHandles.size(); ++i) {
8218 sp<EffectHandle> handle = mHandles[i].promote();
8219 if (handle != 0) {
8220 handle->dump(buffer, SIZE);
8221 result.append(buffer);
8222 }
8223 }
8224
8225 result.append("\n");
8226
8227 write(fd, result.string(), result.length());
8228
8229 if (locked) {
8230 mLock.unlock();
8231 }
8232
8233 return NO_ERROR;
8234}
8235
8236// ----------------------------------------------------------------------------
8237// EffectHandle implementation
8238// ----------------------------------------------------------------------------
8239
8240#undef LOG_TAG
8241#define LOG_TAG "AudioFlinger::EffectHandle"
8242
8243AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8244 const sp<AudioFlinger::Client>& client,
8245 const sp<IEffectClient>& effectClient,
8246 int32_t priority)
8247 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008248 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008249 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008250{
Steve Block3856b092011-10-20 11:56:00 +01008251 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008252
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008253 if (client == 0) {
8254 return;
8255 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008256 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8257 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8258 if (mCblkMemory != 0) {
8259 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8260
Glenn Kastena0d68332012-01-27 16:47:15 -08008261 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008262 new(mCblk) effect_param_cblk_t();
8263 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008264 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008265 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008266 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008267 return;
8268 }
8269}
8270
8271AudioFlinger::EffectHandle::~EffectHandle()
8272{
Steve Block3856b092011-10-20 11:56:00 +01008273 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008274 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01008275 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008276}
8277
8278status_t AudioFlinger::EffectHandle::enable()
8279{
Steve Block3856b092011-10-20 11:56:00 +01008280 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008281 if (!mHasControl) return INVALID_OPERATION;
8282 if (mEffect == 0) return DEAD_OBJECT;
8283
Eric Laurentdb7c0792011-08-10 10:37:50 -07008284 if (mEnabled) {
8285 return NO_ERROR;
8286 }
8287
Eric Laurent59255e42011-07-27 19:49:51 -07008288 mEnabled = true;
8289
8290 sp<ThreadBase> thread = mEffect->thread().promote();
8291 if (thread != 0) {
8292 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8293 }
8294
8295 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8296 if (mEffect->suspended()) {
8297 return NO_ERROR;
8298 }
8299
Eric Laurentdb7c0792011-08-10 10:37:50 -07008300 status_t status = mEffect->setEnabled(true);
8301 if (status != NO_ERROR) {
8302 if (thread != 0) {
8303 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8304 }
8305 mEnabled = false;
8306 }
8307 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008308}
8309
8310status_t AudioFlinger::EffectHandle::disable()
8311{
Steve Block3856b092011-10-20 11:56:00 +01008312 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008313 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008314 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008315
Eric Laurentdb7c0792011-08-10 10:37:50 -07008316 if (!mEnabled) {
8317 return NO_ERROR;
8318 }
Eric Laurent59255e42011-07-27 19:49:51 -07008319 mEnabled = false;
8320
8321 if (mEffect->suspended()) {
8322 return NO_ERROR;
8323 }
8324
8325 status_t status = mEffect->setEnabled(false);
8326
8327 sp<ThreadBase> thread = mEffect->thread().promote();
8328 if (thread != 0) {
8329 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8330 }
8331
8332 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008333}
8334
8335void AudioFlinger::EffectHandle::disconnect()
8336{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008337 disconnect(true);
8338}
8339
Glenn Kasten58123c32012-02-03 10:32:24 -08008340void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008341{
Glenn Kasten58123c32012-02-03 10:32:24 -08008342 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008343 if (mEffect == 0) {
8344 return;
8345 }
Glenn Kasten58123c32012-02-03 10:32:24 -08008346 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07008347
Eric Laurenta85a74a2011-10-19 11:44:54 -07008348 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008349 sp<ThreadBase> thread = mEffect->thread().promote();
8350 if (thread != 0) {
8351 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8352 }
Eric Laurent59255e42011-07-27 19:49:51 -07008353 }
8354
Mathias Agopian65ab4712010-07-14 17:59:35 -07008355 // release sp on module => module destructor can be called now
8356 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008357 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008358 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008359 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008360 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8361 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008362 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008363 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008364 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8365 mClient.clear();
8366 }
8367}
8368
Eric Laurent25f43952010-07-28 05:40:18 -07008369status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8370 uint32_t cmdSize,
8371 void *pCmdData,
8372 uint32_t *replySize,
8373 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008374{
Steve Block3856b092011-10-20 11:56:00 +01008375// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008376// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008377
8378 // only get parameter command is permitted for applications not controlling the effect
8379 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8380 return INVALID_OPERATION;
8381 }
8382 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008383 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008384
8385 // handle commands that are not forwarded transparently to effect engine
8386 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8387 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8388 // no risk to block the whole media server process or mixer threads is we are stuck here
8389 Mutex::Autolock _l(mCblk->lock);
8390 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8391 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8392 mCblk->serverIndex = 0;
8393 mCblk->clientIndex = 0;
8394 return BAD_VALUE;
8395 }
8396 status_t status = NO_ERROR;
8397 while (mCblk->serverIndex < mCblk->clientIndex) {
8398 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008399 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008400 int *p = (int *)(mBuffer + mCblk->serverIndex);
8401 int size = *p++;
8402 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008403 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008404 break;
8405 }
8406 effect_param_t *param = (effect_param_t *)p;
8407 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008408 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008409 mCblk->serverIndex += size;
8410 continue;
8411 }
Eric Laurent25f43952010-07-28 05:40:18 -07008412 uint32_t psize = sizeof(effect_param_t) +
8413 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8414 param->vsize;
8415 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8416 psize,
8417 p,
8418 &rsize,
8419 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008420 // stop at first error encountered
8421 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008422 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008423 *(int *)pReplyData = reply;
8424 break;
8425 } else if (reply != NO_ERROR) {
8426 *(int *)pReplyData = reply;
8427 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008428 }
8429 mCblk->serverIndex += size;
8430 }
8431 mCblk->serverIndex = 0;
8432 mCblk->clientIndex = 0;
8433 return status;
8434 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008435 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008436 return enable();
8437 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008438 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008439 return disable();
8440 }
8441
8442 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8443}
8444
Eric Laurent59255e42011-07-27 19:49:51 -07008445void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008446{
Steve Block3856b092011-10-20 11:56:00 +01008447 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008448
8449 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008450 mEnabled = enabled;
8451
Mathias Agopian65ab4712010-07-14 17:59:35 -07008452 if (signal && mEffectClient != 0) {
8453 mEffectClient->controlStatusChanged(hasControl);
8454 }
8455}
8456
Eric Laurent25f43952010-07-28 05:40:18 -07008457void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8458 uint32_t cmdSize,
8459 void *pCmdData,
8460 uint32_t replySize,
8461 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008462{
8463 if (mEffectClient != 0) {
8464 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8465 }
8466}
8467
8468
8469
8470void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8471{
8472 if (mEffectClient != 0) {
8473 mEffectClient->enableStatusChanged(enabled);
8474 }
8475}
8476
8477status_t AudioFlinger::EffectHandle::onTransact(
8478 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8479{
8480 return BnEffect::onTransact(code, data, reply, flags);
8481}
8482
8483
8484void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8485{
Glenn Kastena0d68332012-01-27 16:47:15 -08008486 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008487
8488 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008489 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008490 mPriority,
8491 mHasControl,
8492 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008493 mCblk ? mCblk->clientIndex : 0,
8494 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008495 );
8496
8497 if (locked) {
8498 mCblk->lock.unlock();
8499 }
8500}
8501
8502#undef LOG_TAG
8503#define LOG_TAG "AudioFlinger::EffectChain"
8504
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008505AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008506 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008507 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008508 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8509 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008510{
Dima Zavinfce7a472011-04-19 22:30:36 -07008511 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008512 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008513 return;
8514 }
8515 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8516 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008517}
8518
8519AudioFlinger::EffectChain::~EffectChain()
8520{
8521 if (mOwnInBuffer) {
8522 delete mInBuffer;
8523 }
8524
8525}
8526
Eric Laurent59255e42011-07-27 19:49:51 -07008527// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008528sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
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++) {
8533 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008534 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008535 }
8536 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008537 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008538}
8539
Eric Laurent59255e42011-07-27 19:49:51 -07008540// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008541sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008542{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008543 size_t size = mEffects.size();
8544
8545 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07008546 // by convention, return first effect if id provided is 0 (0 is never a valid id)
8547 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008548 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008549 }
8550 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008551 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008552}
8553
Eric Laurent59255e42011-07-27 19:49:51 -07008554// getEffectFromType_l() must be called with ThreadBase::mLock held
8555sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
8556 const effect_uuid_t *type)
8557{
Eric Laurent59255e42011-07-27 19:49:51 -07008558 size_t size = mEffects.size();
8559
8560 for (size_t i = 0; i < size; i++) {
8561 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008562 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07008563 }
8564 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008565 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008566}
8567
Mathias Agopian65ab4712010-07-14 17:59:35 -07008568// Must be called with EffectChain::mLock locked
8569void AudioFlinger::EffectChain::process_l()
8570{
Eric Laurentdac69112010-09-28 14:09:57 -07008571 sp<ThreadBase> thread = mThread.promote();
8572 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008573 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07008574 return;
8575 }
Dima Zavinfce7a472011-04-19 22:30:36 -07008576 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
8577 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08008578 // always process effects unless no more tracks are on the session and the effect tail
8579 // has been rendered
8580 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07008581 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008582 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07008583
Eric Laurent544fe9b2011-11-11 15:42:52 -08008584 if (!tracksOnSession && mTailBufferCount == 0) {
8585 doProcess = false;
8586 }
8587
8588 if (activeTrackCnt() == 0) {
8589 // if no track is active and the effect tail has not been rendered,
8590 // the input buffer must be cleared here as the mixer process will not do it
8591 if (tracksOnSession || mTailBufferCount > 0) {
8592 size_t numSamples = thread->frameCount() * thread->channelCount();
8593 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
8594 if (mTailBufferCount > 0) {
8595 mTailBufferCount--;
8596 }
8597 }
8598 }
Eric Laurentdac69112010-09-28 14:09:57 -07008599 }
8600
Mathias Agopian65ab4712010-07-14 17:59:35 -07008601 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08008602 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07008603 for (size_t i = 0; i < size; i++) {
8604 mEffects[i]->process();
8605 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008606 }
8607 for (size_t i = 0; i < size; i++) {
8608 mEffects[i]->updateState();
8609 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008610}
8611
Eric Laurentcab11242010-07-15 12:50:15 -07008612// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07008613status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008614{
8615 effect_descriptor_t desc = effect->desc();
8616 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
8617
8618 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07008619 effect->setChain(this);
8620 sp<ThreadBase> thread = mThread.promote();
8621 if (thread == 0) {
8622 return NO_INIT;
8623 }
8624 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008625
8626 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8627 // Auxiliary effects are inserted at the beginning of mEffects vector as
8628 // they are processed first and accumulated in chain input buffer
8629 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07008630
Mathias Agopian65ab4712010-07-14 17:59:35 -07008631 // the input buffer for auxiliary effect contains mono samples in
8632 // 32 bit format. This is to avoid saturation in AudoMixer
8633 // accumulation stage. Saturation is done in EffectModule::process() before
8634 // calling the process in effect engine
8635 size_t numSamples = thread->frameCount();
8636 int32_t *buffer = new int32_t[numSamples];
8637 memset(buffer, 0, numSamples * sizeof(int32_t));
8638 effect->setInBuffer((int16_t *)buffer);
8639 // auxiliary effects output samples to chain input buffer for further processing
8640 // by insert effects
8641 effect->setOutBuffer(mInBuffer);
8642 } else {
8643 // Insert effects are inserted at the end of mEffects vector as they are processed
8644 // after track and auxiliary effects.
8645 // Insert effect order as a function of indicated preference:
8646 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8647 // another effect is present
8648 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8649 // last effect claiming first position
8650 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8651 // first effect claiming last position
8652 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8653 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8654 // already present
8655
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008656 size_t size = mEffects.size();
8657 size_t idx_insert = size;
8658 ssize_t idx_insert_first = -1;
8659 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008660
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008661 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008662 effect_descriptor_t d = mEffects[i]->desc();
8663 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8664 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8665 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8666 // check invalid effect chaining combinations
8667 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8668 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008669 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008670 return INVALID_OPERATION;
8671 }
8672 // remember position of first insert effect and by default
8673 // select this as insert position for new effect
8674 if (idx_insert == size) {
8675 idx_insert = i;
8676 }
8677 // remember position of last insert effect claiming
8678 // first position
8679 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8680 idx_insert_first = i;
8681 }
8682 // remember position of first insert effect claiming
8683 // last position
8684 if (iPref == EFFECT_FLAG_INSERT_LAST &&
8685 idx_insert_last == -1) {
8686 idx_insert_last = i;
8687 }
8688 }
8689 }
8690
8691 // modify idx_insert from first position if needed
8692 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8693 if (idx_insert_last != -1) {
8694 idx_insert = idx_insert_last;
8695 } else {
8696 idx_insert = size;
8697 }
8698 } else {
8699 if (idx_insert_first != -1) {
8700 idx_insert = idx_insert_first + 1;
8701 }
8702 }
8703
8704 // always read samples from chain input buffer
8705 effect->setInBuffer(mInBuffer);
8706
8707 // if last effect in the chain, output samples to chain
8708 // output buffer, otherwise to chain input buffer
8709 if (idx_insert == size) {
8710 if (idx_insert != 0) {
8711 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
8712 mEffects[idx_insert-1]->configure();
8713 }
8714 effect->setOutBuffer(mOutBuffer);
8715 } else {
8716 effect->setOutBuffer(mInBuffer);
8717 }
8718 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008719
Steve Block3856b092011-10-20 11:56:00 +01008720 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008721 }
8722 effect->configure();
8723 return NO_ERROR;
8724}
8725
Eric Laurentcab11242010-07-15 12:50:15 -07008726// removeEffect_l() must be called with PlaybackThread::mLock held
8727size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008728{
8729 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008730 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008731 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
8732
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008733 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008734 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07008735 // calling stop here will remove pre-processing effect from the audio HAL.
8736 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
8737 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07008738 if (mEffects[i]->state() == EffectModule::ACTIVE ||
8739 mEffects[i]->state() == EffectModule::STOPPING) {
8740 mEffects[i]->stop();
8741 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008742 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
8743 delete[] effect->inBuffer();
8744 } else {
8745 if (i == size - 1 && i != 0) {
8746 mEffects[i - 1]->setOutBuffer(mOutBuffer);
8747 mEffects[i - 1]->configure();
8748 }
8749 }
8750 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01008751 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008752 break;
8753 }
8754 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008755
8756 return mEffects.size();
8757}
8758
Eric Laurentcab11242010-07-15 12:50:15 -07008759// setDevice_l() must be called with PlaybackThread::mLock held
8760void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008761{
8762 size_t size = mEffects.size();
8763 for (size_t i = 0; i < size; i++) {
8764 mEffects[i]->setDevice(device);
8765 }
8766}
8767
Eric Laurentcab11242010-07-15 12:50:15 -07008768// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08008769void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008770{
8771 size_t size = mEffects.size();
8772 for (size_t i = 0; i < size; i++) {
8773 mEffects[i]->setMode(mode);
8774 }
8775}
8776
Eric Laurentcab11242010-07-15 12:50:15 -07008777// setVolume_l() must be called with PlaybackThread::mLock held
8778bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008779{
8780 uint32_t newLeft = *left;
8781 uint32_t newRight = *right;
8782 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07008783 int ctrlIdx = -1;
8784 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008785
Eric Laurentcab11242010-07-15 12:50:15 -07008786 // first update volume controller
8787 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07008788 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07008789 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
8790 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07008791 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07008792 break;
8793 }
8794 }
8795
8796 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07008797 if (hasControl) {
8798 *left = mNewLeftVolume;
8799 *right = mNewRightVolume;
8800 }
8801 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07008802 }
8803
8804 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07008805 mLeftVolume = newLeft;
8806 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008807
8808 // second get volume update from volume controller
8809 if (ctrlIdx >= 0) {
8810 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07008811 mNewLeftVolume = newLeft;
8812 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008813 }
8814 // then indicate volume to all other effects in chain.
8815 // Pass altered volume to effects before volume controller
8816 // and requested volume to effects after controller
8817 uint32_t lVol = newLeft;
8818 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008819
Mathias Agopian65ab4712010-07-14 17:59:35 -07008820 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07008821 if ((int)i == ctrlIdx) continue;
8822 // this also works for ctrlIdx == -1 when there is no volume controller
8823 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008824 lVol = *left;
8825 rVol = *right;
8826 }
8827 mEffects[i]->setVolume(&lVol, &rVol, false);
8828 }
8829 *left = newLeft;
8830 *right = newRight;
8831
8832 return hasControl;
8833}
8834
Mathias Agopian65ab4712010-07-14 17:59:35 -07008835status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
8836{
8837 const size_t SIZE = 256;
8838 char buffer[SIZE];
8839 String8 result;
8840
8841 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
8842 result.append(buffer);
8843
8844 bool locked = tryLock(mLock);
8845 // failed to lock - AudioFlinger is probably deadlocked
8846 if (!locked) {
8847 result.append("\tCould not lock mutex:\n");
8848 }
8849
Eric Laurentcab11242010-07-15 12:50:15 -07008850 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
8851 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008852 mEffects.size(),
8853 (uint32_t)mInBuffer,
8854 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008855 mActiveTrackCnt);
8856 result.append(buffer);
8857 write(fd, result.string(), result.size());
8858
8859 for (size_t i = 0; i < mEffects.size(); ++i) {
8860 sp<EffectModule> effect = mEffects[i];
8861 if (effect != 0) {
8862 effect->dump(fd, args);
8863 }
8864 }
8865
8866 if (locked) {
8867 mLock.unlock();
8868 }
8869
8870 return NO_ERROR;
8871}
8872
Eric Laurent59255e42011-07-27 19:49:51 -07008873// must be called with ThreadBase::mLock held
8874void AudioFlinger::EffectChain::setEffectSuspended_l(
8875 const effect_uuid_t *type, bool suspend)
8876{
8877 sp<SuspendedEffectDesc> desc;
8878 // use effect type UUID timelow as key as there is no real risk of identical
8879 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008880 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008881 if (suspend) {
8882 if (index >= 0) {
8883 desc = mSuspendedEffects.valueAt(index);
8884 } else {
8885 desc = new SuspendedEffectDesc();
8886 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
8887 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01008888 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07008889 }
8890 if (desc->mRefCount++ == 0) {
8891 sp<EffectModule> effect = getEffectIfEnabled(type);
8892 if (effect != 0) {
8893 desc->mEffect = effect;
8894 effect->setSuspended(true);
8895 effect->setEnabled(false);
8896 }
8897 }
8898 } else {
8899 if (index < 0) {
8900 return;
8901 }
8902 desc = mSuspendedEffects.valueAt(index);
8903 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008904 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008905 desc->mRefCount = 1;
8906 }
8907 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01008908 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008909 if (desc->mEffect != 0) {
8910 sp<EffectModule> effect = desc->mEffect.promote();
8911 if (effect != 0) {
8912 effect->setSuspended(false);
8913 sp<EffectHandle> handle = effect->controlHandle();
8914 if (handle != 0) {
8915 effect->setEnabled(handle->enabled());
8916 }
8917 }
8918 desc->mEffect.clear();
8919 }
8920 mSuspendedEffects.removeItemsAt(index);
8921 }
8922 }
8923}
8924
8925// must be called with ThreadBase::mLock held
8926void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
8927{
8928 sp<SuspendedEffectDesc> desc;
8929
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008930 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07008931 if (suspend) {
8932 if (index >= 0) {
8933 desc = mSuspendedEffects.valueAt(index);
8934 } else {
8935 desc = new SuspendedEffectDesc();
8936 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01008937 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07008938 }
8939 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08008940 Vector< sp<EffectModule> > effects;
8941 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07008942 for (size_t i = 0; i < effects.size(); i++) {
8943 setEffectSuspended_l(&effects[i]->desc().type, true);
8944 }
8945 }
8946 } else {
8947 if (index < 0) {
8948 return;
8949 }
8950 desc = mSuspendedEffects.valueAt(index);
8951 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008952 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07008953 desc->mRefCount = 1;
8954 }
8955 if (--desc->mRefCount == 0) {
8956 Vector<const effect_uuid_t *> types;
8957 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8958 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8959 continue;
8960 }
8961 types.add(&mSuspendedEffects.valueAt(i)->mType);
8962 }
8963 for (size_t i = 0; i < types.size(); i++) {
8964 setEffectSuspended_l(types[i], false);
8965 }
Steve Block3856b092011-10-20 11:56:00 +01008966 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07008967 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8968 }
8969 }
8970}
8971
Eric Laurent6bffdb82011-09-23 08:40:41 -07008972
8973// The volume effect is used for automated tests only
8974#ifndef OPENSL_ES_H_
8975static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8976 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8977const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8978#endif //OPENSL_ES_H_
8979
Eric Laurentdb7c0792011-08-10 10:37:50 -07008980bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8981{
8982 // auxiliary effects and visualizer are never suspended on output mix
8983 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8984 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008985 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8986 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008987 return false;
8988 }
8989 return true;
8990}
8991
Glenn Kastend0539712012-01-30 12:56:03 -08008992void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07008993{
Glenn Kastend0539712012-01-30 12:56:03 -08008994 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07008995 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08008996 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
8997 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07008998 }
Eric Laurent59255e42011-07-27 19:49:51 -07008999 }
Eric Laurent59255e42011-07-27 19:49:51 -07009000}
9001
9002sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9003 const effect_uuid_t *type)
9004{
Glenn Kasten090f0192012-01-30 13:00:02 -08009005 sp<EffectModule> effect = getEffectFromType_l(type);
9006 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009007}
9008
9009void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9010 bool enabled)
9011{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009012 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009013 if (enabled) {
9014 if (index < 0) {
9015 // if the effect is not suspend check if all effects are suspended
9016 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9017 if (index < 0) {
9018 return;
9019 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009020 if (!isEffectEligibleForSuspend(effect->desc())) {
9021 return;
9022 }
Eric Laurent59255e42011-07-27 19:49:51 -07009023 setEffectSuspended_l(&effect->desc().type, enabled);
9024 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009025 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009026 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009027 return;
9028 }
Eric Laurent59255e42011-07-27 19:49:51 -07009029 }
Steve Block3856b092011-10-20 11:56:00 +01009030 ALOGV("checkSuspendOnEffectEnabled() enable suspending 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 // if effect is requested to suspended but was not yet enabled, supend it now.
9034 if (desc->mEffect == 0) {
9035 desc->mEffect = effect;
9036 effect->setEnabled(false);
9037 effect->setSuspended(true);
9038 }
9039 } else {
9040 if (index < 0) {
9041 return;
9042 }
Steve Block3856b092011-10-20 11:56:00 +01009043 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009044 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009045 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9046 desc->mEffect.clear();
9047 effect->setSuspended(false);
9048 }
9049}
9050
Mathias Agopian65ab4712010-07-14 17:59:35 -07009051#undef LOG_TAG
9052#define LOG_TAG "AudioFlinger"
9053
9054// ----------------------------------------------------------------------------
9055
9056status_t AudioFlinger::onTransact(
9057 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9058{
9059 return BnAudioFlinger::onTransact(code, data, reply, flags);
9060}
9061
Mathias Agopian65ab4712010-07-14 17:59:35 -07009062}; // namespace android