blob: 56a9942e7f870ea0bd905eeffb9db2e64d0395a7 [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
Glenn Kastend8e6fd32012-05-07 11:07:57 -070022//#define ATRACE_TAG ATRACE_TAG_AUDIO
23
Mathias Agopian65ab4712010-07-14 17:59:35 -070024#include <math.h>
25#include <signal.h>
26#include <sys/time.h>
27#include <sys/resource.h>
28
Gloria Wang9ee159b2011-02-24 14:51:45 -080029#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <binder/IServiceManager.h>
31#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070032#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070033#include <binder/Parcel.h>
34#include <binder/IPCThreadState.h>
35#include <utils/String16.h>
36#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070037#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038
Dima Zavinfce7a472011-04-19 22:30:36 -070039#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080041#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
Glenn Kastend3cee2f2012-03-13 17:55:35 -070043#undef ADD_BATTERY_DATA
44
45#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080046#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080047#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070048#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070049
50#include <private/media/AudioTrackShared.h>
51#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070052
Dima Zavin64760242011-05-11 14:15:23 -070053#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070054#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070055
56#include "AudioMixer.h"
57#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080058#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070059
Mathias Agopian65ab4712010-07-14 17:59:35 -070060#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070061#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070062#include <audio_effects/effect_ns.h>
63#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070064
Glenn Kasten3b21c502011-12-15 09:52:39 -080065#include <audio_utils/primitives.h>
66
Eric Laurentfeb0db62011-07-22 09:04:31 -070067#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080068
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070069// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080070#ifdef DEBUG_CPU_USAGE
71#include <cpustats/CentralTendencyStatistics.h>
72#include <cpustats/ThreadCpuUsage.h>
73#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070074
John Grossman4ff14ba2012-02-08 16:37:41 -080075#include <common_time/cc_helper.h>
76#include <common_time/local_clock.h>
77
Glenn Kasten58912562012-04-03 10:45:00 -070078#include "FastMixer.h"
79
80// NBAIO implementations
81#include "AudioStreamOutSink.h"
82#include "MonoPipe.h"
83#include "MonoPipeReader.h"
84#include "SourceAudioBufferProvider.h"
85
Glenn Kasten1dc28b72012-04-24 10:01:03 -070086#ifdef HAVE_REQUEST_PRIORITY
87#include "SchedulingPolicyService.h"
88#endif
89
Glenn Kasten58912562012-04-03 10:45:00 -070090#ifdef SOAKER
91#include "Soaker.h"
92#endif
93
Mathias Agopian65ab4712010-07-14 17:59:35 -070094// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070095
John Grossman1c345192012-03-27 14:00:17 -070096// Note: the following macro is used for extremely verbose logging message. In
97// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
98// 0; but one side effect of this is to turn all LOGV's as well. Some messages
99// are so verbose that we want to suppress them even when we have ALOG_ASSERT
100// turned on. Do not uncomment the #def below unless you really know what you
101// are doing and want to see all of the extremely verbose messages.
102//#define VERY_VERY_VERBOSE_LOGGING
103#ifdef VERY_VERY_VERBOSE_LOGGING
104#define ALOGVV ALOGV
105#else
106#define ALOGVV(a...) do { } while(0)
107#endif
Eric Laurentde070132010-07-13 04:45:46 -0700108
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109namespace android {
110
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800111static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
112static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700113
Mathias Agopian65ab4712010-07-14 17:59:35 -0700114static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800115static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700116
117// retry counts for buffer fill timeout
118// 50 * ~20msecs = 1 second
119static const int8_t kMaxTrackRetries = 50;
120static const int8_t kMaxTrackStartupRetries = 50;
121// allow less retry attempts on direct output thread.
122// direct outputs can be a scarce resource in audio hardware and should
123// be released as quickly as possible.
124static const int8_t kMaxTrackRetriesDirect = 2;
125
126static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800127static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128
Glenn Kasten7dede872011-12-13 11:04:14 -0800129// don't warn about blocked writes or record buffer overflows more often than this
130static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700131
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700132// RecordThread loop sleep time upon application overrun or audio HAL read error
133static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700134
Glenn Kasten7dede872011-12-13 11:04:14 -0800135// maximum time to wait for setParameters to complete
136static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700137
Eric Laurent7cafbb32011-11-22 18:50:29 -0800138// minimum sleep time for the mixer thread loop when tracks are active but in underrun
139static const uint32_t kMinThreadSleepTimeUs = 5000;
140// maximum divider applied to the active sleep time in the mixer thread loop
141static const uint32_t kMaxThreadSleepTimeShift = 2;
142
Glenn Kasten58912562012-04-03 10:45:00 -0700143// minimum normal mix buffer size, expressed in milliseconds rather than frames
144static const uint32_t kMinNormalMixBufferSizeMs = 20;
145
John Grossman4ff14ba2012-02-08 16:37:41 -0800146nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800147
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700148// Whether to use fast mixer
149static const enum {
150 FastMixer_Never, // never initialize or use: for debugging only
151 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
152 // normal mixer multiplier is 1
153 FastMixer_Static, // initialize if needed, then use all the time if initialized,
154 // multipler is calculated based on minimum normal mixer buffer size
155 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
156 // multipler is calculated based on minimum normal mixer buffer size
157 // FIXME for FastMixer_Dynamic:
158 // Supporting this option will require fixing HALs that can't handle large writes.
159 // For example, one HAL implementation returns an error from a large write,
160 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
161 // We could either fix the HAL implementations, or provide a wrapper that breaks
162 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
163} kUseFastMixer = FastMixer_Static;
164
Mathias Agopian65ab4712010-07-14 17:59:35 -0700165// ----------------------------------------------------------------------------
166
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700167#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800168// To collect the amplifier usage
169static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800170 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
171 if (service == NULL) {
172 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800173 return;
174 }
175
176 service->addBatteryData(params);
177}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700178#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800179
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700180static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700181{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700182 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700183 int rc;
184
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700185 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
186 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
187 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
188 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700189 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700190 }
191 rc = audio_hw_device_open(mod, dev);
192 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
193 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
194 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700195 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700196 }
197 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
198 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
199 rc = BAD_VALUE;
200 goto out;
201 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700202 return 0;
203
204out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700205 *dev = NULL;
206 return rc;
207}
208
Mathias Agopian65ab4712010-07-14 17:59:35 -0700209// ----------------------------------------------------------------------------
210
211AudioFlinger::AudioFlinger()
212 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800213 mPrimaryHardwareDev(NULL),
214 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
215 mMasterVolume(1.0f),
216 mMasterVolumeSupportLvl(MVS_NONE),
217 mMasterMute(false),
218 mNextUniqueId(1),
219 mMode(AUDIO_MODE_INVALID),
220 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700222}
223
224void AudioFlinger::onFirstRef()
225{
Dima Zavin799a70e2011-04-18 16:57:27 -0700226 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700227
Eric Laurent93575202011-01-18 18:39:02 -0800228 Mutex::Autolock _l(mLock);
229
Dima Zavin799a70e2011-04-18 16:57:27 -0700230 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800231 char val_str[PROPERTY_VALUE_MAX] = { 0 };
232 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
233 uint32_t int_val;
234 if (1 == sscanf(val_str, "%u", &int_val)) {
235 mStandbyTimeInNsecs = milliseconds(int_val);
236 ALOGI("Using %u mSec as standby time.", int_val);
237 } else {
238 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
239 ALOGI("Using default %u mSec as standby time.",
240 (uint32_t)(mStandbyTimeInNsecs / 1000000));
241 }
242 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700243
Eric Laurenta4c5a552012-03-29 10:12:40 -0700244 mMode = AUDIO_MODE_NORMAL;
245 mMasterVolumeSW = 1.0;
246 mMasterVolume = 1.0;
John Grossman4ff14ba2012-02-08 16:37:41 -0800247 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700248}
249
250AudioFlinger::~AudioFlinger()
251{
Dima Zavin799a70e2011-04-18 16:57:27 -0700252
Mathias Agopian65ab4712010-07-14 17:59:35 -0700253 while (!mRecordThreads.isEmpty()) {
254 // closeInput() will remove first entry from mRecordThreads
255 closeInput(mRecordThreads.keyAt(0));
256 }
257 while (!mPlaybackThreads.isEmpty()) {
258 // closeOutput() will remove first entry from mPlaybackThreads
259 closeOutput(mPlaybackThreads.keyAt(0));
260 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700261
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800262 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
263 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700264 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
265 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700266 }
267}
268
Eric Laurenta4c5a552012-03-29 10:12:40 -0700269static const char * const audio_interfaces[] = {
270 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
271 AUDIO_HARDWARE_MODULE_ID_A2DP,
272 AUDIO_HARDWARE_MODULE_ID_USB,
273};
274#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
275
276audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, uint32_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700277{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700278 // if module is 0, the request comes from an old policy manager and we should load
279 // well known modules
280 if (module == 0) {
281 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
282 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
283 loadHwModule_l(audio_interfaces[i]);
284 }
285 } else {
286 // check a match for the requested module handle
287 AudioHwDevice *audioHwdevice = mAudioHwDevs.valueFor(module);
288 if (audioHwdevice != NULL) {
289 return audioHwdevice->hwDevice();
290 }
291 }
292 // then try to find a module supporting the requested device.
Dima Zavin799a70e2011-04-18 16:57:27 -0700293 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700294 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700295 if ((dev->get_supported_devices(dev) & devices) == devices)
296 return dev;
297 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700298
Dima Zavin799a70e2011-04-18 16:57:27 -0700299 return NULL;
300}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700301
302status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
303{
304 const size_t SIZE = 256;
305 char buffer[SIZE];
306 String8 result;
307
308 result.append("Clients:\n");
309 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800310 sp<Client> client = mClients.valueAt(i).promote();
311 if (client != 0) {
312 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
313 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700314 }
315 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700316
317 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800318 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700319 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
320 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800321 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700322 result.append(buffer);
323 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700324 write(fd, result.string(), result.size());
325 return NO_ERROR;
326}
327
328
329status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
330{
331 const size_t SIZE = 256;
332 char buffer[SIZE];
333 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800334 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335
John Grossman4ff14ba2012-02-08 16:37:41 -0800336 snprintf(buffer, SIZE, "Hardware status: %d\n"
337 "Standby Time mSec: %u\n",
338 hardwareStatus,
339 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700340 result.append(buffer);
341 write(fd, result.string(), result.size());
342 return NO_ERROR;
343}
344
345status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
346{
347 const size_t SIZE = 256;
348 char buffer[SIZE];
349 String8 result;
350 snprintf(buffer, SIZE, "Permission Denial: "
351 "can't dump AudioFlinger from pid=%d, uid=%d\n",
352 IPCThreadState::self()->getCallingPid(),
353 IPCThreadState::self()->getCallingUid());
354 result.append(buffer);
355 write(fd, result.string(), result.size());
356 return NO_ERROR;
357}
358
359static bool tryLock(Mutex& mutex)
360{
361 bool locked = false;
362 for (int i = 0; i < kDumpLockRetries; ++i) {
363 if (mutex.tryLock() == NO_ERROR) {
364 locked = true;
365 break;
366 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800367 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700368 }
369 return locked;
370}
371
372status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
373{
Glenn Kasten44deb052012-02-05 18:09:08 -0800374 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700375 dumpPermissionDenial(fd, args);
376 } else {
377 // get state of hardware lock
378 bool hardwareLocked = tryLock(mHardwareLock);
379 if (!hardwareLocked) {
380 String8 result(kHardwareLockedString);
381 write(fd, result.string(), result.size());
382 } else {
383 mHardwareLock.unlock();
384 }
385
386 bool locked = tryLock(mLock);
387
388 // failed to lock - AudioFlinger is probably deadlocked
389 if (!locked) {
390 String8 result(kDeadlockedString);
391 write(fd, result.string(), result.size());
392 }
393
394 dumpClients(fd, args);
395 dumpInternals(fd, args);
396
397 // dump playback threads
398 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
399 mPlaybackThreads.valueAt(i)->dump(fd, args);
400 }
401
402 // dump record threads
403 for (size_t i = 0; i < mRecordThreads.size(); i++) {
404 mRecordThreads.valueAt(i)->dump(fd, args);
405 }
406
Dima Zavin799a70e2011-04-18 16:57:27 -0700407 // dump all hardware devs
408 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700409 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700410 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700411 }
412 if (locked) mLock.unlock();
413 }
414 return NO_ERROR;
415}
416
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800417sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
418{
419 // If pid is already in the mClients wp<> map, then use that entry
420 // (for which promote() is always != 0), otherwise create a new entry and Client.
421 sp<Client> client = mClients.valueFor(pid).promote();
422 if (client == 0) {
423 client = new Client(this, pid);
424 mClients.add(pid, client);
425 }
426
427 return client;
428}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700429
430// IAudioFlinger interface
431
432
433sp<IAudioTrack> AudioFlinger::createTrack(
434 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800435 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800437 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700438 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700439 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800440 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800442 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800443 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444 int *sessionId,
445 status_t *status)
446{
447 sp<PlaybackThread::Track> track;
448 sp<TrackHandle> trackHandle;
449 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700450 status_t lStatus;
451 int lSessionId;
452
Glenn Kasten263709e2012-01-06 08:40:01 -0800453 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
454 // but if someone uses binder directly they could bypass that and cause us to crash
455 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000456 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700457 lStatus = BAD_VALUE;
458 goto Exit;
459 }
460
461 {
462 Mutex::Autolock _l(mLock);
463 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700464 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700465 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000466 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700467 lStatus = BAD_VALUE;
468 goto Exit;
469 }
470
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800471 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700472
Steve Block3856b092011-10-20 11:56:00 +0100473 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700474 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700475 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700476 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
477 if (mPlaybackThreads.keyAt(i) != output) {
478 // prevent same audio session on different output threads
479 uint32_t sessions = t->hasAudioSession(*sessionId);
480 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000481 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700482 lStatus = BAD_VALUE;
483 goto Exit;
484 }
485 // check if an effect with same session ID is waiting for a track to be created
486 if (sessions & PlaybackThread::EFFECT_SESSION) {
487 effectThread = t.get();
488 }
Eric Laurentde070132010-07-13 04:45:46 -0700489 }
490 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700491 lSessionId = *sessionId;
492 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700493 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700494 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700495 if (sessionId != NULL) {
496 *sessionId = lSessionId;
497 }
498 }
Steve Block3856b092011-10-20 11:56:00 +0100499 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500
501 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800502 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700503
504 // move effect chain to this output thread if an effect on same session was waiting
505 // for a track to be created
506 if (lStatus == NO_ERROR && effectThread != NULL) {
507 Mutex::Autolock _dl(thread->mLock);
508 Mutex::Autolock _sl(effectThread->mLock);
509 moveEffectChain_l(lSessionId, effectThread, thread, true);
510 }
Eric Laurenta011e352012-03-29 15:51:43 -0700511
512 // Look for sync events awaiting for a session to be used.
513 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
514 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
515 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
516 track->setSyncEvent(mPendingSyncEvents[i]);
517 mPendingSyncEvents.removeAt(i);
518 i--;
519 }
520 }
521 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700522 }
523 if (lStatus == NO_ERROR) {
524 trackHandle = new TrackHandle(track);
525 } else {
526 // remove local strong reference to Client before deleting the Track so that the Client
527 // destructor is called by the TrackBase destructor with mLock held
528 client.clear();
529 track.clear();
530 }
531
532Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700533 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700534 *status = lStatus;
535 }
536 return trackHandle;
537}
538
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800539uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700540{
541 Mutex::Autolock _l(mLock);
542 PlaybackThread *thread = checkPlaybackThread_l(output);
543 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000544 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700545 return 0;
546 }
547 return thread->sampleRate();
548}
549
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800550int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700551{
552 Mutex::Autolock _l(mLock);
553 PlaybackThread *thread = checkPlaybackThread_l(output);
554 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000555 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700556 return 0;
557 }
558 return thread->channelCount();
559}
560
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800561audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700562{
563 Mutex::Autolock _l(mLock);
564 PlaybackThread *thread = checkPlaybackThread_l(output);
565 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000566 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800567 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700568 }
569 return thread->format();
570}
571
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800572size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700573{
574 Mutex::Autolock _l(mLock);
575 PlaybackThread *thread = checkPlaybackThread_l(output);
576 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000577 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578 return 0;
579 }
Glenn Kasten58912562012-04-03 10:45:00 -0700580 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
581 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700582 return thread->frameCount();
583}
584
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800585uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700586{
587 Mutex::Autolock _l(mLock);
588 PlaybackThread *thread = checkPlaybackThread_l(output);
589 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000590 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700591 return 0;
592 }
593 return thread->latency();
594}
595
596status_t AudioFlinger::setMasterVolume(float value)
597{
Eric Laurenta1884f92011-08-23 08:25:03 -0700598 status_t ret = initCheck();
599 if (ret != NO_ERROR) {
600 return ret;
601 }
602
Mathias Agopian65ab4712010-07-14 17:59:35 -0700603 // check calling permissions
604 if (!settingsAllowed()) {
605 return PERMISSION_DENIED;
606 }
607
John Grossman4ff14ba2012-02-08 16:37:41 -0800608 float swmv = value;
609
Eric Laurenta4c5a552012-03-29 10:12:40 -0700610 Mutex::Autolock _l(mLock);
611
Mathias Agopian65ab4712010-07-14 17:59:35 -0700612 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800613 if (MVS_NONE != mMasterVolumeSupportLvl) {
614 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
615 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700616 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
John Grossman4ff14ba2012-02-08 16:37:41 -0800617
618 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
619 if (NULL != dev->set_master_volume) {
620 dev->set_master_volume(dev, value);
621 }
622 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800623 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800624
625 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700626 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700627
John Grossman4ff14ba2012-02-08 16:37:41 -0800628 mMasterVolume = value;
629 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800630 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700631 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700632
633 return NO_ERROR;
634}
635
Glenn Kastenf78aee72012-01-04 11:00:47 -0800636status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700637{
Eric Laurenta1884f92011-08-23 08:25:03 -0700638 status_t ret = initCheck();
639 if (ret != NO_ERROR) {
640 return ret;
641 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700642
643 // check calling permissions
644 if (!settingsAllowed()) {
645 return PERMISSION_DENIED;
646 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800647 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000648 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700649 return BAD_VALUE;
650 }
651
652 { // scope for the lock
653 AutoMutex lock(mHardwareLock);
654 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700655 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700656 mHardwareStatus = AUDIO_HW_IDLE;
657 }
658
659 if (NO_ERROR == ret) {
660 Mutex::Autolock _l(mLock);
661 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800662 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700663 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700664 }
665
666 return ret;
667}
668
669status_t AudioFlinger::setMicMute(bool state)
670{
Eric Laurenta1884f92011-08-23 08:25:03 -0700671 status_t ret = initCheck();
672 if (ret != NO_ERROR) {
673 return ret;
674 }
675
Mathias Agopian65ab4712010-07-14 17:59:35 -0700676 // check calling permissions
677 if (!settingsAllowed()) {
678 return PERMISSION_DENIED;
679 }
680
681 AutoMutex lock(mHardwareLock);
682 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700683 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700684 mHardwareStatus = AUDIO_HW_IDLE;
685 return ret;
686}
687
688bool AudioFlinger::getMicMute() const
689{
Eric Laurenta1884f92011-08-23 08:25:03 -0700690 status_t ret = initCheck();
691 if (ret != NO_ERROR) {
692 return false;
693 }
694
Dima Zavinfce7a472011-04-19 22:30:36 -0700695 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800696 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700697 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700698 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700699 mHardwareStatus = AUDIO_HW_IDLE;
700 return state;
701}
702
703status_t AudioFlinger::setMasterMute(bool muted)
704{
705 // check calling permissions
706 if (!settingsAllowed()) {
707 return PERMISSION_DENIED;
708 }
709
Eric Laurent93575202011-01-18 18:39:02 -0800710 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800711 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -0700712 mMasterMute = muted;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800713 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700714 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700715
716 return NO_ERROR;
717}
718
719float AudioFlinger::masterVolume() const
720{
Glenn Kasten98067102011-12-13 11:47:54 -0800721 Mutex::Autolock _l(mLock);
722 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700723}
724
John Grossman4ff14ba2012-02-08 16:37:41 -0800725float AudioFlinger::masterVolumeSW() const
726{
727 Mutex::Autolock _l(mLock);
728 return masterVolumeSW_l();
729}
730
Mathias Agopian65ab4712010-07-14 17:59:35 -0700731bool AudioFlinger::masterMute() const
732{
Glenn Kasten98067102011-12-13 11:47:54 -0800733 Mutex::Autolock _l(mLock);
734 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700735}
736
John Grossman4ff14ba2012-02-08 16:37:41 -0800737float AudioFlinger::masterVolume_l() const
738{
739 if (MVS_FULL == mMasterVolumeSupportLvl) {
740 float ret_val;
741 AutoMutex lock(mHardwareLock);
742
743 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800744 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
745 (NULL != mPrimaryHardwareDev->get_master_volume),
746 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800747
748 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
749 mHardwareStatus = AUDIO_HW_IDLE;
750 return ret_val;
751 }
752
753 return mMasterVolume;
754}
755
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800756status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
757 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700758{
759 // check calling permissions
760 if (!settingsAllowed()) {
761 return PERMISSION_DENIED;
762 }
763
Glenn Kasten263709e2012-01-06 08:40:01 -0800764 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000765 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700766 return BAD_VALUE;
767 }
768
769 AutoMutex lock(mLock);
770 PlaybackThread *thread = NULL;
771 if (output) {
772 thread = checkPlaybackThread_l(output);
773 if (thread == NULL) {
774 return BAD_VALUE;
775 }
776 }
777
778 mStreamTypes[stream].volume = value;
779
780 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800781 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700782 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700783 }
784 } else {
785 thread->setStreamVolume(stream, value);
786 }
787
788 return NO_ERROR;
789}
790
Glenn Kastenfff6d712012-01-12 16:38:12 -0800791status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700792{
793 // check calling permissions
794 if (!settingsAllowed()) {
795 return PERMISSION_DENIED;
796 }
797
Glenn Kasten263709e2012-01-06 08:40:01 -0800798 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700799 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000800 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700801 return BAD_VALUE;
802 }
803
Eric Laurent93575202011-01-18 18:39:02 -0800804 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805 mStreamTypes[stream].mute = muted;
806 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700807 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700808
809 return NO_ERROR;
810}
811
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800812float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700813{
Glenn Kasten263709e2012-01-06 08:40:01 -0800814 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700815 return 0.0f;
816 }
817
818 AutoMutex lock(mLock);
819 float volume;
820 if (output) {
821 PlaybackThread *thread = checkPlaybackThread_l(output);
822 if (thread == NULL) {
823 return 0.0f;
824 }
825 volume = thread->streamVolume(stream);
826 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800827 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828 }
829
830 return volume;
831}
832
Glenn Kastenfff6d712012-01-12 16:38:12 -0800833bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700834{
Glenn Kasten263709e2012-01-06 08:40:01 -0800835 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700836 return true;
837 }
838
Glenn Kasten6637baa2012-01-09 09:40:36 -0800839 AutoMutex lock(mLock);
840 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700841}
842
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800843status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700844{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800845 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700846 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
847 // check calling permissions
848 if (!settingsAllowed()) {
849 return PERMISSION_DENIED;
850 }
851
Mathias Agopian65ab4712010-07-14 17:59:35 -0700852 // ioHandle == 0 means the parameters are global to the audio hardware interface
853 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700854 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700855 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800856 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700857 AutoMutex lock(mHardwareLock);
858 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
859 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
860 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
861 status_t result = dev->set_parameters(dev, keyValuePairs.string());
862 final_result = result ?: final_result;
863 }
864 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800865 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700866 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
867 AudioParameter param = AudioParameter(keyValuePairs);
868 String8 value;
869 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700870 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
871 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700872 for (size_t i = 0; i < mRecordThreads.size(); i++) {
873 sp<RecordThread> thread = mRecordThreads.valueAt(i);
874 RecordThread::RecordTrack *track = thread->track();
875 if (track != NULL) {
876 audio_devices_t device = (audio_devices_t)(
877 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700878 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700879 thread->setEffectSuspended(FX_IID_AEC,
880 suspend,
881 track->sessionId());
882 thread->setEffectSuspended(FX_IID_NS,
883 suspend,
884 track->sessionId());
885 }
886 }
Eric Laurentbee53372011-08-29 12:42:48 -0700887 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700888 }
889 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700890 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700891 }
892
893 // hold a strong ref on thread in case closeOutput() or closeInput() is called
894 // and the thread is exited once the lock is released
895 sp<ThreadBase> thread;
896 {
897 Mutex::Autolock _l(mLock);
898 thread = checkPlaybackThread_l(ioHandle);
899 if (thread == NULL) {
900 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800901 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700902 // indicate output device change to all input threads for pre processing
903 AudioParameter param = AudioParameter(keyValuePairs);
904 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700905 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
906 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700907 for (size_t i = 0; i < mRecordThreads.size(); i++) {
908 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
909 }
910 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700911 }
912 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800913 if (thread != 0) {
914 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700915 }
916 return BAD_VALUE;
917}
918
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800919String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700920{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800921// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
923
Eric Laurenta4c5a552012-03-29 10:12:40 -0700924 Mutex::Autolock _l(mLock);
925
Mathias Agopian65ab4712010-07-14 17:59:35 -0700926 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700927 String8 out_s8;
928
Dima Zavin799a70e2011-04-18 16:57:27 -0700929 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800930 char *s;
931 {
932 AutoMutex lock(mHardwareLock);
933 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700934 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800935 s = dev->get_parameters(dev, keys.string());
936 mHardwareStatus = AUDIO_HW_IDLE;
937 }
John Grossmanef7740b2012-02-09 11:28:36 -0800938 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700939 free(s);
940 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700941 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700942 }
943
Mathias Agopian65ab4712010-07-14 17:59:35 -0700944 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
945 if (playbackThread != NULL) {
946 return playbackThread->getParameters(keys);
947 }
948 RecordThread *recordThread = checkRecordThread_l(ioHandle);
949 if (recordThread != NULL) {
950 return recordThread->getParameters(keys);
951 }
952 return String8("");
953}
954
Glenn Kastenf587ba52012-01-26 16:25:10 -0800955size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700956{
Eric Laurenta1884f92011-08-23 08:25:03 -0700957 status_t ret = initCheck();
958 if (ret != NO_ERROR) {
959 return 0;
960 }
961
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800962 AutoMutex lock(mHardwareLock);
963 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700964 struct audio_config config = {
965 sample_rate: sampleRate,
966 channel_mask: audio_channel_in_mask_from_count(channelCount),
967 format: format,
968 };
969 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800970 mHardwareStatus = AUDIO_HW_IDLE;
971 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700972}
973
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800974unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700975{
976 if (ioHandle == 0) {
977 return 0;
978 }
979
980 Mutex::Autolock _l(mLock);
981
982 RecordThread *recordThread = checkRecordThread_l(ioHandle);
983 if (recordThread != NULL) {
984 return recordThread->getInputFramesLost();
985 }
986 return 0;
987}
988
989status_t AudioFlinger::setVoiceVolume(float value)
990{
Eric Laurenta1884f92011-08-23 08:25:03 -0700991 status_t ret = initCheck();
992 if (ret != NO_ERROR) {
993 return ret;
994 }
995
Mathias Agopian65ab4712010-07-14 17:59:35 -0700996 // check calling permissions
997 if (!settingsAllowed()) {
998 return PERMISSION_DENIED;
999 }
1000
1001 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001002 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -07001003 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001004 mHardwareStatus = AUDIO_HW_IDLE;
1005
1006 return ret;
1007}
1008
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001009status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1010 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001011{
1012 status_t status;
1013
1014 Mutex::Autolock _l(mLock);
1015
1016 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1017 if (playbackThread != NULL) {
1018 return playbackThread->getRenderPosition(halFrames, dspFrames);
1019 }
1020
1021 return BAD_VALUE;
1022}
1023
1024void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1025{
1026
1027 Mutex::Autolock _l(mLock);
1028
Glenn Kastenbb001922012-02-03 11:10:26 -08001029 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001030 if (mNotificationClients.indexOfKey(pid) < 0) {
1031 sp<NotificationClient> notificationClient = new NotificationClient(this,
1032 client,
1033 pid);
Steve Block3856b092011-10-20 11:56:00 +01001034 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035
1036 mNotificationClients.add(pid, notificationClient);
1037
1038 sp<IBinder> binder = client->asBinder();
1039 binder->linkToDeath(notificationClient);
1040
1041 // the config change is always sent from playback or record threads to avoid deadlock
1042 // with AudioSystem::gLock
1043 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1044 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1045 }
1046
1047 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1048 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1049 }
1050 }
1051}
1052
1053void AudioFlinger::removeNotificationClient(pid_t pid)
1054{
1055 Mutex::Autolock _l(mLock);
1056
Glenn Kastena3b09252012-01-20 09:19:01 -08001057 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001058
Steve Block3856b092011-10-20 11:56:00 +01001059 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001060 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001061 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001062 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001063 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001064 ALOGV(" pid %d @ %d", ref->mPid, i);
1065 if (ref->mPid == pid) {
1066 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001067 mAudioSessionRefs.removeAt(i);
1068 delete ref;
1069 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001070 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001071 } else {
1072 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001073 }
1074 }
1075 if (removed) {
1076 purgeStaleEffects_l();
1077 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078}
1079
1080// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001081void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001082{
1083 size_t size = mNotificationClients.size();
1084 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001085 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1086 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001087 }
1088}
1089
1090// removeClient_l() must be called with AudioFlinger::mLock held
1091void AudioFlinger::removeClient_l(pid_t pid)
1092{
Steve Block3856b092011-10-20 11:56:00 +01001093 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001094 mClients.removeItem(pid);
1095}
1096
1097
1098// ----------------------------------------------------------------------------
1099
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001100AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
1101 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001102 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001103 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001104 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001105 // mChannelMask
1106 mChannelCount(0),
1107 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1108 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001109 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001110 mDevice(device),
1111 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001112{
1113}
1114
1115AudioFlinger::ThreadBase::~ThreadBase()
1116{
1117 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001118 // do not lock the mutex in destructor
1119 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001120 if (mPowerManager != 0) {
1121 sp<IBinder> binder = mPowerManager->asBinder();
1122 binder->unlinkToDeath(mDeathRecipient);
1123 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001124}
1125
1126void AudioFlinger::ThreadBase::exit()
1127{
Steve Block3856b092011-10-20 11:56:00 +01001128 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001129 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001130 // This lock prevents the following race in thread (uniprocessor for illustration):
1131 // if (!exitPending()) {
1132 // // context switch from here to exit()
1133 // // exit() calls requestExit(), what exitPending() observes
1134 // // exit() calls signal(), which is dropped since no waiters
1135 // // context switch back from exit() to here
1136 // mWaitWorkCV.wait(...);
1137 // // now thread is hung
1138 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001139 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001140 requestExit();
1141 mWaitWorkCV.signal();
1142 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001143 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1144 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001145 requestExitAndWait();
1146}
1147
Mathias Agopian65ab4712010-07-14 17:59:35 -07001148status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1149{
1150 status_t status;
1151
Steve Block3856b092011-10-20 11:56:00 +01001152 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001153 Mutex::Autolock _l(mLock);
1154
1155 mNewParameters.add(keyValuePairs);
1156 mWaitWorkCV.signal();
1157 // wait condition with timeout in case the thread loop has exited
1158 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001159 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001160 status = mParamStatus;
1161 mWaitWorkCV.signal();
1162 } else {
1163 status = TIMED_OUT;
1164 }
1165 return status;
1166}
1167
1168void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1169{
1170 Mutex::Autolock _l(mLock);
1171 sendConfigEvent_l(event, param);
1172}
1173
1174// sendConfigEvent_l() must be called with ThreadBase::mLock held
1175void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1176{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001177 ConfigEvent configEvent;
1178 configEvent.mEvent = event;
1179 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001180 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001181 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001182 mWaitWorkCV.signal();
1183}
1184
1185void AudioFlinger::ThreadBase::processConfigEvents()
1186{
1187 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001188 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001189 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001190 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001191 mConfigEvents.removeAt(0);
1192 // release mLock before locking AudioFlinger mLock: lock order is always
1193 // AudioFlinger then ThreadBase to avoid cross deadlock
1194 mLock.unlock();
1195 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001196 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001197 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001198 mLock.lock();
1199 }
1200 mLock.unlock();
1201}
1202
1203status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1204{
1205 const size_t SIZE = 256;
1206 char buffer[SIZE];
1207 String8 result;
1208
1209 bool locked = tryLock(mLock);
1210 if (!locked) {
1211 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1212 write(fd, buffer, strlen(buffer));
1213 }
1214
Eric Laurent612bbb52012-03-14 15:03:26 -07001215 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1216 result.append(buffer);
1217 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1218 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001219 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1220 result.append(buffer);
1221 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1222 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001223 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1224 result.append(buffer);
1225 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001226 result.append(buffer);
1227 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1228 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001229 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1230 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001231 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1232 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001233 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001234 result.append(buffer);
1235
1236 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1237 result.append(buffer);
1238 result.append(" Index Command");
1239 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1240 snprintf(buffer, SIZE, "\n %02d ", i);
1241 result.append(buffer);
1242 result.append(mNewParameters[i]);
1243 }
1244
1245 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1246 result.append(buffer);
1247 snprintf(buffer, SIZE, " Index event param\n");
1248 result.append(buffer);
1249 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001250 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001251 result.append(buffer);
1252 }
1253 result.append("\n");
1254
1255 write(fd, result.string(), result.size());
1256
1257 if (locked) {
1258 mLock.unlock();
1259 }
1260 return NO_ERROR;
1261}
1262
Eric Laurent1d2bff02011-07-24 17:49:51 -07001263status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1264{
1265 const size_t SIZE = 256;
1266 char buffer[SIZE];
1267 String8 result;
1268
1269 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1270 write(fd, buffer, strlen(buffer));
1271
1272 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1273 sp<EffectChain> chain = mEffectChains[i];
1274 if (chain != 0) {
1275 chain->dump(fd, args);
1276 }
1277 }
1278 return NO_ERROR;
1279}
1280
Eric Laurentfeb0db62011-07-22 09:04:31 -07001281void AudioFlinger::ThreadBase::acquireWakeLock()
1282{
1283 Mutex::Autolock _l(mLock);
1284 acquireWakeLock_l();
1285}
1286
1287void AudioFlinger::ThreadBase::acquireWakeLock_l()
1288{
1289 if (mPowerManager == 0) {
1290 // use checkService() to avoid blocking if power service is not up yet
1291 sp<IBinder> binder =
1292 defaultServiceManager()->checkService(String16("power"));
1293 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001294 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001295 } else {
1296 mPowerManager = interface_cast<IPowerManager>(binder);
1297 binder->linkToDeath(mDeathRecipient);
1298 }
1299 }
1300 if (mPowerManager != 0) {
1301 sp<IBinder> binder = new BBinder();
1302 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1303 binder,
1304 String16(mName));
1305 if (status == NO_ERROR) {
1306 mWakeLockToken = binder;
1307 }
Steve Block3856b092011-10-20 11:56:00 +01001308 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001309 }
1310}
1311
1312void AudioFlinger::ThreadBase::releaseWakeLock()
1313{
1314 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001315 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001316}
1317
1318void AudioFlinger::ThreadBase::releaseWakeLock_l()
1319{
1320 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001321 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001322 if (mPowerManager != 0) {
1323 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1324 }
1325 mWakeLockToken.clear();
1326 }
1327}
1328
1329void AudioFlinger::ThreadBase::clearPowerManager()
1330{
1331 Mutex::Autolock _l(mLock);
1332 releaseWakeLock_l();
1333 mPowerManager.clear();
1334}
1335
1336void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1337{
1338 sp<ThreadBase> thread = mThread.promote();
1339 if (thread != 0) {
1340 thread->clearPowerManager();
1341 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001342 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001343}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001344
Eric Laurent59255e42011-07-27 19:49:51 -07001345void AudioFlinger::ThreadBase::setEffectSuspended(
1346 const effect_uuid_t *type, bool suspend, int sessionId)
1347{
1348 Mutex::Autolock _l(mLock);
1349 setEffectSuspended_l(type, suspend, sessionId);
1350}
1351
1352void AudioFlinger::ThreadBase::setEffectSuspended_l(
1353 const effect_uuid_t *type, bool suspend, int sessionId)
1354{
Glenn Kasten090f0192012-01-30 13:00:02 -08001355 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001356 if (chain != 0) {
1357 if (type != NULL) {
1358 chain->setEffectSuspended_l(type, suspend);
1359 } else {
1360 chain->setEffectSuspendedAll_l(suspend);
1361 }
1362 }
1363
1364 updateSuspendedSessions_l(type, suspend, sessionId);
1365}
1366
1367void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1368{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001369 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001370 if (index < 0) {
1371 return;
1372 }
1373
1374 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1375 mSuspendedSessions.editValueAt(index);
1376
1377 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001378 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001379 for (int j = 0; j < desc->mRefCount; j++) {
1380 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1381 chain->setEffectSuspendedAll_l(true);
1382 } else {
Steve Block3856b092011-10-20 11:56:00 +01001383 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001384 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001385 chain->setEffectSuspended_l(&desc->mType, true);
1386 }
1387 }
1388 }
1389}
1390
Eric Laurent59255e42011-07-27 19:49:51 -07001391void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1392 bool suspend,
1393 int sessionId)
1394{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001395 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001396
1397 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1398
1399 if (suspend) {
1400 if (index >= 0) {
1401 sessionEffects = mSuspendedSessions.editValueAt(index);
1402 } else {
1403 mSuspendedSessions.add(sessionId, sessionEffects);
1404 }
1405 } else {
1406 if (index < 0) {
1407 return;
1408 }
1409 sessionEffects = mSuspendedSessions.editValueAt(index);
1410 }
1411
1412
1413 int key = EffectChain::kKeyForSuspendAll;
1414 if (type != NULL) {
1415 key = type->timeLow;
1416 }
1417 index = sessionEffects.indexOfKey(key);
1418
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001419 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001420 if (suspend) {
1421 if (index >= 0) {
1422 desc = sessionEffects.valueAt(index);
1423 } else {
1424 desc = new SuspendedSessionDesc();
1425 if (type != NULL) {
1426 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1427 }
1428 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001429 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001430 }
1431 desc->mRefCount++;
1432 } else {
1433 if (index < 0) {
1434 return;
1435 }
1436 desc = sessionEffects.valueAt(index);
1437 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001438 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001439 sessionEffects.removeItemsAt(index);
1440 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001441 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001442 sessionId);
1443 mSuspendedSessions.removeItem(sessionId);
1444 }
1445 }
1446 }
1447 if (!sessionEffects.isEmpty()) {
1448 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1449 }
1450}
1451
1452void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1453 bool enabled,
1454 int sessionId)
1455{
1456 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001457 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1458}
Eric Laurent59255e42011-07-27 19:49:51 -07001459
Eric Laurenta85a74a2011-10-19 11:44:54 -07001460void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1461 bool enabled,
1462 int sessionId)
1463{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001464 if (mType != RECORD) {
1465 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1466 // another session. This gives the priority to well behaved effect control panels
1467 // and applications not using global effects.
1468 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1469 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1470 }
1471 }
Eric Laurent59255e42011-07-27 19:49:51 -07001472
1473 sp<EffectChain> chain = getEffectChain_l(sessionId);
1474 if (chain != 0) {
1475 chain->checkSuspendOnEffectEnabled(effect, enabled);
1476 }
1477}
1478
Mathias Agopian65ab4712010-07-14 17:59:35 -07001479// ----------------------------------------------------------------------------
1480
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001481AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1482 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001483 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001484 uint32_t device,
1485 type_t type)
1486 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001487 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1488 // Assumes constructor is called by AudioFlinger with it's mLock held,
1489 // but it would be safer to explicitly pass initial masterMute as parameter
1490 mMasterMute(audioFlinger->masterMute_l()),
1491 // mStreamTypes[] initialized in constructor body
1492 mOutput(output),
1493 // Assumes constructor is called by AudioFlinger with it's mLock held,
1494 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001495 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001496 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001497 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001498 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001499 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten288ed212012-04-25 17:52:27 -07001500 // index 0 is reserved for normal mixer's submix
1501 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502{
Glenn Kasten480b4682012-02-28 12:30:08 -08001503 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001504
Mathias Agopian65ab4712010-07-14 17:59:35 -07001505 readOutputParameters();
1506
Glenn Kasten263709e2012-01-06 08:40:01 -08001507 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001508 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1509 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1510 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001511 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1512 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001513 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001514 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1515 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001516}
1517
1518AudioFlinger::PlaybackThread::~PlaybackThread()
1519{
1520 delete [] mMixBuffer;
1521}
1522
1523status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1524{
1525 dumpInternals(fd, args);
1526 dumpTracks(fd, args);
1527 dumpEffectChains(fd, args);
1528 return NO_ERROR;
1529}
1530
1531status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1532{
1533 const size_t SIZE = 256;
1534 char buffer[SIZE];
1535 String8 result;
1536
Glenn Kasten58912562012-04-03 10:45:00 -07001537 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1538 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1539 const stream_type_t *st = &mStreamTypes[i];
1540 if (i > 0) {
1541 result.appendFormat(", ");
1542 }
1543 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1544 if (st->mute) {
1545 result.append("M");
1546 }
1547 }
1548 result.append("\n");
1549 write(fd, result.string(), result.length());
1550 result.clear();
1551
Mathias Agopian65ab4712010-07-14 17:59:35 -07001552 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1553 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001554 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001555 for (size_t i = 0; i < mTracks.size(); ++i) {
1556 sp<Track> track = mTracks[i];
1557 if (track != 0) {
1558 track->dump(buffer, SIZE);
1559 result.append(buffer);
1560 }
1561 }
1562
1563 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1564 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001565 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001566 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001567 sp<Track> track = mActiveTracks[i].promote();
1568 if (track != 0) {
1569 track->dump(buffer, SIZE);
1570 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001571 }
1572 }
1573 write(fd, result.string(), result.size());
1574 return NO_ERROR;
1575}
1576
Mathias Agopian65ab4712010-07-14 17:59:35 -07001577status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1578{
1579 const size_t SIZE = 256;
1580 char buffer[SIZE];
1581 String8 result;
1582
1583 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1584 result.append(buffer);
1585 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1586 result.append(buffer);
1587 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1588 result.append(buffer);
1589 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1590 result.append(buffer);
1591 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1592 result.append(buffer);
1593 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1594 result.append(buffer);
1595 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1596 result.append(buffer);
1597 write(fd, result.string(), result.size());
1598
1599 dumpBase(fd, args);
1600
1601 return NO_ERROR;
1602}
1603
1604// Thread virtuals
1605status_t AudioFlinger::PlaybackThread::readyToRun()
1606{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001607 status_t status = initCheck();
1608 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001609 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001610 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001611 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001613 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614}
1615
1616void AudioFlinger::PlaybackThread::onFirstRef()
1617{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001618 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001619}
1620
1621// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001622sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001623 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001624 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001625 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001626 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001627 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001628 int frameCount,
1629 const sp<IMemory>& sharedBuffer,
1630 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001631 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001632 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001633 status_t *status)
1634{
1635 sp<Track> track;
1636 status_t lStatus;
1637
Glenn Kasten73d22752012-03-19 13:38:30 -07001638 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1639
1640 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001641 if (flags & IAudioFlinger::TRACK_FAST) {
1642 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001643 // not timed
1644 (!isTimed) &&
1645 // either of these use cases:
1646 (
1647 // use case 1: shared buffer with any frame count
1648 (
1649 (sharedBuffer != 0)
1650 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001651 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001652 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001653 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001654 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001655 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001656 )
1657 ) &&
1658 // PCM data
1659 audio_is_linear_pcm(format) &&
1660 // mono or stereo
1661 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1662 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001663#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001664 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001665 (sampleRate == mSampleRate) &&
1666#endif
1667 // normal mixer has an associated fast mixer
1668 hasFastMixer() &&
1669 // there are sufficient fast track slots available
1670 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001671 // FIXME test that MixerThread for this fast track has a capable output HAL
1672 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001673 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001674 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1675 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001676 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001677 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001678 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001679 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001680 } else {
1681 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001682 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1683 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1684 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1685 audio_is_linear_pcm(format),
1686 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001687 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001688 // For compatibility with AudioTrack calculation, buffer depth is forced
1689 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1690 // This is probably too conservative, but legacy application code may depend on it.
1691 // If you change this calculation, also review the start threshold which is related.
1692 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1693 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1694 if (minBufCount < 2) {
1695 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001696 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001697 int minFrameCount = mNormalFrameCount * minBufCount;
1698 if (frameCount < minFrameCount) {
1699 frameCount = minFrameCount;
1700 }
1701 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001702 }
1703
Mathias Agopian65ab4712010-07-14 17:59:35 -07001704 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001705 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1706 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001707 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001708 "for output %p with format %d",
1709 sampleRate, format, channelMask, mOutput, mFormat);
1710 lStatus = BAD_VALUE;
1711 goto Exit;
1712 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001713 }
1714 } else {
1715 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1716 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001717 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001718 lStatus = BAD_VALUE;
1719 goto Exit;
1720 }
1721 }
1722
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001723 lStatus = initCheck();
1724 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001725 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001726 goto Exit;
1727 }
1728
1729 { // scope for mLock
1730 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001731
1732 // all tracks in same audio session must share the same routing strategy otherwise
1733 // conflicts will happen when tracks are moved from one output to another by audio policy
1734 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001735 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001736 for (size_t i = 0; i < mTracks.size(); ++i) {
1737 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001738 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001739 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001740 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001741 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001742 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001743 lStatus = BAD_VALUE;
1744 goto Exit;
1745 }
1746 }
1747 }
1748
John Grossman4ff14ba2012-02-08 16:37:41 -08001749 if (!isTimed) {
1750 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001751 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001752 } else {
1753 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1754 channelMask, frameCount, sharedBuffer, sessionId);
1755 }
1756 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001757 lStatus = NO_MEMORY;
1758 goto Exit;
1759 }
1760 mTracks.add(track);
1761
1762 sp<EffectChain> chain = getEffectChain_l(sessionId);
1763 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001764 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001765 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001766 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001767 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001768 }
1769 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001770
1771#ifdef HAVE_REQUEST_PRIORITY
1772 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1773 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1774 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1775 // so ask activity manager to do this on our behalf
1776 int err = requestPriority(callingPid, tid, 1);
1777 if (err != 0) {
1778 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1779 1, callingPid, tid, err);
1780 }
1781 }
1782#endif
1783
Mathias Agopian65ab4712010-07-14 17:59:35 -07001784 lStatus = NO_ERROR;
1785
1786Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001787 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001788 *status = lStatus;
1789 }
1790 return track;
1791}
1792
1793uint32_t AudioFlinger::PlaybackThread::latency() const
1794{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001795 Mutex::Autolock _l(mLock);
1796 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001797 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001798 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001799 return 0;
1800 }
1801}
1802
Glenn Kasten6637baa2012-01-09 09:40:36 -08001803void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001804{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001805 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001806 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001807}
1808
Glenn Kasten6637baa2012-01-09 09:40:36 -08001809void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001810{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001811 Mutex::Autolock _l(mLock);
1812 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001813}
1814
Glenn Kasten6637baa2012-01-09 09:40:36 -08001815void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001816{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001817 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001818 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001819}
1820
Glenn Kasten6637baa2012-01-09 09:40:36 -08001821void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001822{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001823 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001824 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825}
1826
Glenn Kastenfff6d712012-01-12 16:38:12 -08001827float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001828{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001829 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001830 return mStreamTypes[stream].volume;
1831}
1832
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833// addTrack_l() must be called with ThreadBase::mLock held
1834status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1835{
1836 status_t status = ALREADY_EXISTS;
1837
1838 // set retry count for buffer fill
1839 track->mRetryCount = kMaxTrackStartupRetries;
1840 if (mActiveTracks.indexOf(track) < 0) {
1841 // the track is newly added, make sure it fills up all its
1842 // buffers before playing. This is to ensure the client will
1843 // effectively get the latency it requested.
1844 track->mFillingUpStatus = Track::FS_FILLING;
1845 track->mResetDone = false;
1846 mActiveTracks.add(track);
1847 if (track->mainBuffer() != mMixBuffer) {
1848 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1849 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001850 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001851 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001852 }
1853 }
1854
1855 status = NO_ERROR;
1856 }
1857
Steve Block3856b092011-10-20 11:56:00 +01001858 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001859 mWaitWorkCV.broadcast();
1860
1861 return status;
1862}
1863
1864// destroyTrack_l() must be called with ThreadBase::mLock held
1865void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1866{
1867 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001868 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001869 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001870 removeTrack_l(track);
1871 }
1872}
1873
1874void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1875{
1876 mTracks.remove(track);
1877 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001878 // redundant as track is about to be destroyed, for dumpsys only
1879 track->mName = -1;
1880 if (track->isFastTrack()) {
1881 int index = track->mFastIndex;
1882 ALOG_ASSERT(0 < index && index < FastMixerState::kMaxFastTracks);
1883 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1884 mFastTrackAvailMask |= 1 << index;
1885 // redundant as track is about to be destroyed, for dumpsys only
1886 track->mFastIndex = -1;
1887 }
Eric Laurentb469b942011-05-09 12:09:06 -07001888 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1889 if (chain != 0) {
1890 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001891 }
1892}
1893
1894String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1895{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001896 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001897 char *s;
1898
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001899 Mutex::Autolock _l(mLock);
1900 if (initCheck() != NO_ERROR) {
1901 return out_s8;
1902 }
1903
Dima Zavin799a70e2011-04-18 16:57:27 -07001904 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001905 out_s8 = String8(s);
1906 free(s);
1907 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001908}
1909
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001910// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001911void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1912 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001913 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001914
Steve Block3856b092011-10-20 11:56:00 +01001915 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916
1917 switch (event) {
1918 case AudioSystem::OUTPUT_OPENED:
1919 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001920 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001921 desc.samplingRate = mSampleRate;
1922 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001923 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001924 desc.latency = latency();
1925 param2 = &desc;
1926 break;
1927
1928 case AudioSystem::STREAM_CONFIG_CHANGED:
1929 param2 = &param;
1930 case AudioSystem::OUTPUT_CLOSED:
1931 default:
1932 break;
1933 }
1934 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1935}
1936
1937void AudioFlinger::PlaybackThread::readOutputParameters()
1938{
Dima Zavin799a70e2011-04-18 16:57:27 -07001939 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001940 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1941 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001942 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001943 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001944 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001945 if (mFrameCount & 15) {
1946 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1947 mFrameCount);
1948 }
1949
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001950 // Calculate size of normal mix buffer relative to the HAL output buffer size
1951 uint32_t multiple = 1;
1952 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07001953 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001954 multiple = (minNormalFrameCount + mFrameCount - 1) / mFrameCount;
1955 // force multiple to be even, for compatibility with doubling of fast tracks due to HAL SRC
1956 // (it would be unusual for the normal mix buffer size to not be a multiple of fast track)
1957 // FIXME this rounding up should not be done if no HAL SRC
1958 if ((multiple > 2) && (multiple & 1)) {
1959 ++multiple;
Glenn Kasten58912562012-04-03 10:45:00 -07001960 }
Glenn Kasten58912562012-04-03 10:45:00 -07001961 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001962 mNormalFrameCount = multiple * mFrameCount;
Glenn Kasten58912562012-04-03 10:45:00 -07001963 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001964
1965 // FIXME - Current mixer implementation only supports stereo output: Always
1966 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001967 delete[] mMixBuffer;
Glenn Kasten58912562012-04-03 10:45:00 -07001968 mMixBuffer = new int16_t[mNormalFrameCount * 2];
1969 memset(mMixBuffer, 0, mNormalFrameCount * 2 * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970
Eric Laurentde070132010-07-13 04:45:46 -07001971 // force reconfiguration of effect chains and engines to take new buffer size and audio
1972 // parameters into account
1973 // Note that mLock is not held when readOutputParameters() is called from the constructor
1974 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1975 // matter.
1976 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1977 Vector< sp<EffectChain> > effectChains = mEffectChains;
1978 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001979 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001980 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001981}
1982
1983status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1984{
Glenn Kastena0d68332012-01-27 16:47:15 -08001985 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001986 return BAD_VALUE;
1987 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001988 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001989 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001990 return INVALID_OPERATION;
1991 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001992 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001993
Dima Zavin799a70e2011-04-18 16:57:27 -07001994 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001995}
1996
Eric Laurent39e94f82010-07-28 01:32:47 -07001997uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001998{
1999 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002000 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002001 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002002 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002003 }
2004
2005 for (size_t i = 0; i < mTracks.size(); ++i) {
2006 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002007 if (sessionId == track->sessionId() &&
2008 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002009 result |= TRACK_SESSION;
2010 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002011 }
2012 }
2013
Eric Laurent39e94f82010-07-28 01:32:47 -07002014 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002015}
2016
Eric Laurentde070132010-07-13 04:45:46 -07002017uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2018{
Dima Zavinfce7a472011-04-19 22:30:36 -07002019 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002020 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002021 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2022 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002023 }
2024 for (size_t i = 0; i < mTracks.size(); i++) {
2025 sp<Track> track = mTracks[i];
2026 if (sessionId == track->sessionId() &&
2027 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002028 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002029 }
2030 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002031 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002032}
2033
Mathias Agopian65ab4712010-07-14 17:59:35 -07002034
Glenn Kastenaed850d2012-01-26 09:46:34 -08002035AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002036{
2037 Mutex::Autolock _l(mLock);
2038 return mOutput;
2039}
2040
2041AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2042{
2043 Mutex::Autolock _l(mLock);
2044 AudioStreamOut *output = mOutput;
2045 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002046 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2047 // must push a NULL and wait for ack
2048 mOutputSink.clear();
2049 mPipeSink.clear();
2050 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002051 return output;
2052}
2053
2054// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002055audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002056{
2057 if (mOutput == NULL) {
2058 return NULL;
2059 }
2060 return &mOutput->stream->common;
2061}
2062
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002063uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002064{
2065 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
2066 // decoding and transfer time. So sleeping for half of the latency would likely cause
2067 // underruns
2068 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002069 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002070 } else {
2071 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
2072 }
2073}
2074
Eric Laurenta011e352012-03-29 15:51:43 -07002075status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2076{
2077 if (!isValidSyncEvent(event)) {
2078 return BAD_VALUE;
2079 }
2080
2081 Mutex::Autolock _l(mLock);
2082
2083 for (size_t i = 0; i < mTracks.size(); ++i) {
2084 sp<Track> track = mTracks[i];
2085 if (event->triggerSession() == track->sessionId()) {
2086 track->setSyncEvent(event);
2087 return NO_ERROR;
2088 }
2089 }
2090
2091 return NAME_NOT_FOUND;
2092}
2093
2094bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2095{
2096 switch (event->type()) {
2097 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2098 return true;
2099 default:
2100 break;
2101 }
2102 return false;
2103}
2104
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105// ----------------------------------------------------------------------------
2106
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002107AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002108 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002109 : PlaybackThread(audioFlinger, output, id, device, type),
2110 // mAudioMixer below
2111#ifdef SOAKER
2112 mSoaker(NULL),
2113#endif
2114 // mFastMixer below
2115 mFastMixerFutex(0)
2116 // mOutputSink below
2117 // mPipeSink below
2118 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002119{
Glenn Kasten58912562012-04-03 10:45:00 -07002120 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2121 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2122 "mFrameCount=%d, mNormalFrameCount=%d",
2123 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2124 mNormalFrameCount);
2125 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2126
Mathias Agopian65ab4712010-07-14 17:59:35 -07002127 // FIXME - Current mixer implementation only supports stereo output
2128 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002129 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002130 }
Glenn Kasten58912562012-04-03 10:45:00 -07002131
2132 // create an NBAIO sink for the HAL output stream, and negotiate
2133 mOutputSink = new AudioStreamOutSink(output->stream);
2134 size_t numCounterOffers = 0;
2135 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2136 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2137 ALOG_ASSERT(index == 0);
2138
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002139 // initialize fast mixer depending on configuration
2140 bool initFastMixer;
2141 switch (kUseFastMixer) {
2142 case FastMixer_Never:
2143 initFastMixer = false;
2144 break;
2145 case FastMixer_Always:
2146 initFastMixer = true;
2147 break;
2148 case FastMixer_Static:
2149 case FastMixer_Dynamic:
2150 initFastMixer = mFrameCount < mNormalFrameCount;
2151 break;
2152 }
2153 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002154
2155 // create a MonoPipe to connect our submix to FastMixer
2156 NBAIO_Format format = mOutputSink->format();
2157 // frame count will be rounded up to a power of 2, so this formula should work well
2158 MonoPipe *monoPipe = new MonoPipe((mNormalFrameCount * 3) / 2, format,
2159 true /*writeCanBlock*/);
2160 const NBAIO_Format offers[1] = {format};
2161 size_t numCounterOffers = 0;
2162 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2163 ALOG_ASSERT(index == 0);
2164 mPipeSink = monoPipe;
2165
2166#ifdef SOAKER
2167 // create a soaker as workaround for governor issues
2168 mSoaker = new Soaker();
2169 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE
2170 mSoaker->run("Soaker", PRIORITY_LOWEST);
2171#endif
2172
2173 // create fast mixer and configure it initially with just one fast track for our submix
2174 mFastMixer = new FastMixer();
2175 FastMixerStateQueue *sq = mFastMixer->sq();
2176 FastMixerState *state = sq->begin();
2177 FastTrack *fastTrack = &state->mFastTracks[0];
2178 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2179 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2180 fastTrack->mVolumeProvider = NULL;
2181 fastTrack->mGeneration++;
2182 state->mFastTracksGen++;
2183 state->mTrackMask = 1;
2184 // fast mixer will use the HAL output sink
2185 state->mOutputSink = mOutputSink.get();
2186 state->mOutputSinkGen++;
2187 state->mFrameCount = mFrameCount;
2188 state->mCommand = FastMixerState::COLD_IDLE;
2189 // already done in constructor initialization list
2190 //mFastMixerFutex = 0;
2191 state->mColdFutexAddr = &mFastMixerFutex;
2192 state->mColdGen++;
2193 state->mDumpState = &mFastMixerDumpState;
2194 sq->end();
2195 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2196
2197 // start the fast mixer
2198 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2199#ifdef HAVE_REQUEST_PRIORITY
2200 pid_t tid = mFastMixer->getTid();
2201 int err = requestPriority(getpid_cached, tid, 2);
2202 if (err != 0) {
2203 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2204 2, getpid_cached, tid, err);
2205 }
2206#endif
2207
2208 } else {
2209 mFastMixer = NULL;
2210 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002211
2212 switch (kUseFastMixer) {
2213 case FastMixer_Never:
2214 case FastMixer_Dynamic:
2215 mNormalSink = mOutputSink;
2216 break;
2217 case FastMixer_Always:
2218 mNormalSink = mPipeSink;
2219 break;
2220 case FastMixer_Static:
2221 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2222 break;
2223 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002224}
2225
2226AudioFlinger::MixerThread::~MixerThread()
2227{
Glenn Kasten58912562012-04-03 10:45:00 -07002228 if (mFastMixer != NULL) {
2229 FastMixerStateQueue *sq = mFastMixer->sq();
2230 FastMixerState *state = sq->begin();
2231 if (state->mCommand == FastMixerState::COLD_IDLE) {
2232 int32_t old = android_atomic_inc(&mFastMixerFutex);
2233 if (old == -1) {
2234 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2235 }
2236 }
2237 state->mCommand = FastMixerState::EXIT;
2238 sq->end();
2239 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2240 mFastMixer->join();
2241 // Though the fast mixer thread has exited, it's state queue is still valid.
2242 // We'll use that extract the final state which contains one remaining fast track
2243 // corresponding to our sub-mix.
2244 state = sq->begin();
2245 ALOG_ASSERT(state->mTrackMask == 1);
2246 FastTrack *fastTrack = &state->mFastTracks[0];
2247 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2248 delete fastTrack->mBufferProvider;
2249 sq->end(false /*didModify*/);
2250 delete mFastMixer;
2251#ifdef SOAKER
2252 if (mSoaker != NULL) {
2253 mSoaker->requestExitAndWait();
2254 }
2255 delete mSoaker;
2256#endif
2257 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002258 delete mAudioMixer;
2259}
2260
Glenn Kasten83efdd02012-02-24 07:21:32 -08002261class CpuStats {
2262public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002263 CpuStats();
2264 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002265#ifdef DEBUG_CPU_USAGE
2266private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002267 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2268 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2269
2270 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2271
2272 int mCpuNum; // thread's current CPU number
2273 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002274#endif
2275};
2276
Glenn Kasten190a46f2012-03-06 11:27:10 -08002277CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002278#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002279 : mCpuNum(-1), mCpukHz(-1)
2280#endif
2281{
2282}
2283
2284void CpuStats::sample(const String8 &title) {
2285#ifdef DEBUG_CPU_USAGE
2286 // get current thread's delta CPU time in wall clock ns
2287 double wcNs;
2288 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2289
2290 // record sample for wall clock statistics
2291 if (valid) {
2292 mWcStats.sample(wcNs);
2293 }
2294
2295 // get the current CPU number
2296 int cpuNum = sched_getcpu();
2297
2298 // get the current CPU frequency in kHz
2299 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2300
2301 // check if either CPU number or frequency changed
2302 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2303 mCpuNum = cpuNum;
2304 mCpukHz = cpukHz;
2305 // ignore sample for purposes of cycles
2306 valid = false;
2307 }
2308
2309 // if no change in CPU number or frequency, then record sample for cycle statistics
2310 if (valid && mCpukHz > 0) {
2311 double cycles = wcNs * cpukHz * 0.000001;
2312 mHzStats.sample(cycles);
2313 }
2314
2315 unsigned n = mWcStats.n();
2316 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002317 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002318 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002319 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2320 double perLoop = elapsed / (double) n;
2321 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002322 double perLoop1k = perLoop * 0.001;
2323 double mean = mWcStats.mean();
2324 double stddev = mWcStats.stddev();
2325 double minimum = mWcStats.minimum();
2326 double maximum = mWcStats.maximum();
2327 double meanCycles = mHzStats.mean();
2328 double stddevCycles = mHzStats.stddev();
2329 double minCycles = mHzStats.minimum();
2330 double maxCycles = mHzStats.maximum();
2331 mCpuUsage.resetElapsed();
2332 mWcStats.reset();
2333 mHzStats.reset();
2334 ALOGD("CPU usage for %s over past %.1f secs\n"
2335 " (%u mixer loops at %.1f mean ms per loop):\n"
2336 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2337 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2338 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2339 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002340 elapsed * .000000001, n, perLoop * .000001,
2341 mean * .001,
2342 stddev * .001,
2343 minimum * .001,
2344 maximum * .001,
2345 mean / perLoop100,
2346 stddev / perLoop100,
2347 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002348 maximum / perLoop100,
2349 meanCycles / perLoop1k,
2350 stddevCycles / perLoop1k,
2351 minCycles / perLoop1k,
2352 maxCycles / perLoop1k);
2353
Glenn Kasten83efdd02012-02-24 07:21:32 -08002354 }
2355 }
2356#endif
2357};
2358
Glenn Kasten37d825e2012-02-24 07:21:48 -08002359void AudioFlinger::PlaybackThread::checkSilentMode_l()
2360{
2361 if (!mMasterMute) {
2362 char value[PROPERTY_VALUE_MAX];
2363 if (property_get("ro.audio.silent", value, "0") > 0) {
2364 char *endptr;
2365 unsigned long ul = strtoul(value, &endptr, 0);
2366 if (*endptr == '\0' && ul != 0) {
2367 ALOGD("Silence is golden");
2368 // The setprop command will not allow a property to be changed after
2369 // the first time it is set, so we don't have to worry about un-muting.
2370 setMasterMute_l(true);
2371 }
2372 }
2373 }
2374}
2375
Glenn Kasten000f0e32012-03-01 17:10:56 -08002376bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002377{
2378 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002379
Glenn Kasten000f0e32012-03-01 17:10:56 -08002380 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002381
2382 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002383 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002384if (mType == MIXER) {
2385 longStandbyExit = false;
2386}
Glenn Kasten688a6402012-02-29 07:57:06 -08002387
Glenn Kasten000f0e32012-03-01 17:10:56 -08002388 // DUPLICATING
2389 // FIXME could this be made local to while loop?
2390 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002391
Glenn Kasten66fcab92012-02-24 14:59:21 -08002392 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002393 sleepTime = idleSleepTime;
2394
2395if (mType == MIXER) {
2396 sleepTimeShift = 0;
2397}
2398
Glenn Kasten83efdd02012-02-24 07:21:32 -08002399 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002400 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002401
Eric Laurentfeb0db62011-07-22 09:04:31 -07002402 acquireWakeLock();
2403
Mathias Agopian65ab4712010-07-14 17:59:35 -07002404 while (!exitPending())
2405 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002406 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002407
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002408 Vector< sp<EffectChain> > effectChains;
2409
Mathias Agopian65ab4712010-07-14 17:59:35 -07002410 processConfigEvents();
2411
Mathias Agopian65ab4712010-07-14 17:59:35 -07002412 { // scope for mLock
2413
2414 Mutex::Autolock _l(mLock);
2415
2416 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002417 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002418 }
2419
Glenn Kastenfa26a852012-03-06 11:28:04 -08002420 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002421
Mathias Agopian65ab4712010-07-14 17:59:35 -07002422 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002423 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002424 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002425 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002426
2427 threadLoop_standby();
2428
Mathias Agopian65ab4712010-07-14 17:59:35 -07002429 mStandby = true;
2430 mBytesWritten = 0;
2431 }
2432
Glenn Kasten3e074702012-02-28 18:40:35 -08002433 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002434 // we're about to wait, flush the binder command buffer
2435 IPCThreadState::self()->flushCommands();
2436
Glenn Kastenfa26a852012-03-06 11:28:04 -08002437 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002438
Mathias Agopian65ab4712010-07-14 17:59:35 -07002439 if (exitPending()) break;
2440
Eric Laurentfeb0db62011-07-22 09:04:31 -07002441 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002442 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002443 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002444 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002445 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002446 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002447
Eric Laurentda747442012-04-25 18:53:13 -07002448 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002449 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002450
Glenn Kasten37d825e2012-02-24 07:21:48 -08002451 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002452
Glenn Kasten000f0e32012-03-01 17:10:56 -08002453 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002454 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002455 if (mType == MIXER) {
2456 sleepTimeShift = 0;
2457 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002458
Mathias Agopian65ab4712010-07-14 17:59:35 -07002459 continue;
2460 }
2461 }
2462
Glenn Kasten81028042012-04-30 18:15:12 -07002463 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002464 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002465
2466 // prevent any changes in effect chain list and in each effect chain
2467 // during mixing and effect process as the audio buffers could be deleted
2468 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002469 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002470 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002471
Glenn Kastenfec279f2012-03-08 07:47:15 -08002472 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002473 threadLoop_mix();
2474 } else {
2475 threadLoop_sleepTime();
2476 }
2477
2478 if (mSuspended > 0) {
2479 sleepTime = suspendSleepTimeUs();
2480 }
2481
2482 // only process effects if we're going to write
2483 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002484 for (size_t i = 0; i < effectChains.size(); i ++) {
2485 effectChains[i]->process_l();
2486 }
2487 }
2488
2489 // enable changes in effect chain
2490 unlockEffectChains(effectChains);
2491
2492 // sleepTime == 0 means we must write to audio hardware
2493 if (sleepTime == 0) {
2494
2495 threadLoop_write();
2496
2497if (mType == MIXER) {
2498 // write blocked detection
2499 nsecs_t now = systemTime();
2500 nsecs_t delta = now - mLastWriteTime;
2501 if (!mStandby && delta > maxPeriod) {
2502 mNumDelayedWrites++;
2503 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002504 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten000f0e32012-03-01 17:10:56 -08002505 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2506 ns2ms(delta), mNumDelayedWrites, this);
2507 lastWarning = now;
2508 }
2509 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2510 // a different threshold. Or completely removed for what it is worth anyway...
2511 if (mStandby) {
2512 longStandbyExit = true;
2513 }
2514 }
2515}
2516
2517 mStandby = false;
2518 } else {
2519 usleep(sleepTime);
2520 }
2521
Glenn Kasten58912562012-04-03 10:45:00 -07002522 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002523 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002524 // same lock. This will also mutate and push a new fast mixer state.
2525 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002526 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002527
Glenn Kastenfa26a852012-03-06 11:28:04 -08002528 // FIXME I don't understand the need for this here;
2529 // it was in the original code but maybe the
2530 // assignment in saveOutputTracks() makes this unnecessary?
2531 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002532
2533 // Effect chains will be actually deleted here if they were removed from
2534 // mEffectChains list during mixing or effects processing
2535 effectChains.clear();
2536
2537 // FIXME Note that the above .clear() is no longer necessary since effectChains
2538 // is now local to this block, but will keep it for now (at least until merge done).
2539 }
2540
2541if (mType == MIXER || mType == DIRECT) {
2542 // put output stream into standby mode
2543 if (!mStandby) {
2544 mOutput->stream->common.standby(&mOutput->stream->common);
2545 }
2546}
2547if (mType == DUPLICATING) {
2548 // for DuplicatingThread, standby mode is handled by the outputTracks
2549}
2550
2551 releaseWakeLock();
2552
2553 ALOGV("Thread %p type %d exiting", this, mType);
2554 return false;
2555}
2556
Glenn Kasten288ed212012-04-25 17:52:27 -07002557// returns (via tracksToRemove) a set of tracks to remove.
Glenn Kasten58912562012-04-03 10:45:00 -07002558void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2559{
Glenn Kasten58912562012-04-03 10:45:00 -07002560 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2561}
2562
2563void AudioFlinger::MixerThread::threadLoop_write()
2564{
2565 // FIXME we should only do one push per cycle; confirm this is true
2566 // Start the fast mixer if it's not already running
2567 if (mFastMixer != NULL) {
2568 FastMixerStateQueue *sq = mFastMixer->sq();
2569 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002570 if (state->mCommand != FastMixerState::MIX_WRITE &&
2571 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002572 if (state->mCommand == FastMixerState::COLD_IDLE) {
2573 int32_t old = android_atomic_inc(&mFastMixerFutex);
2574 if (old == -1) {
2575 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2576 }
2577 }
2578 state->mCommand = FastMixerState::MIX_WRITE;
2579 sq->end();
2580 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002581 if (kUseFastMixer == FastMixer_Dynamic) {
2582 mNormalSink = mPipeSink;
2583 }
Glenn Kasten58912562012-04-03 10:45:00 -07002584 } else {
2585 sq->end(false /*didModify*/);
2586 }
2587 }
2588 PlaybackThread::threadLoop_write();
2589}
2590
Glenn Kasten000f0e32012-03-01 17:10:56 -08002591// shared by MIXER and DIRECT, overridden by DUPLICATING
2592void AudioFlinger::PlaybackThread::threadLoop_write()
2593{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002594 // FIXME rewrite to reduce number of system calls
2595 mLastWriteTime = systemTime();
2596 mInWrite = true;
Glenn Kasten58912562012-04-03 10:45:00 -07002597
Glenn Kasten58912562012-04-03 10:45:00 -07002598#define mBitShift 2 // FIXME
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002599 size_t count = mixBufferSize >> mBitShift;
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002600 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002601 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002602 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002603 if (framesWritten > 0) {
2604 size_t bytesWritten = framesWritten << mBitShift;
2605 mBytesWritten += bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002606 }
2607
Glenn Kasten952eeb22012-03-06 11:30:57 -08002608 mNumWrites++;
2609 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002610}
2611
Glenn Kasten58912562012-04-03 10:45:00 -07002612void AudioFlinger::MixerThread::threadLoop_standby()
2613{
2614 // Idle the fast mixer if it's currently running
2615 if (mFastMixer != NULL) {
2616 FastMixerStateQueue *sq = mFastMixer->sq();
2617 FastMixerState *state = sq->begin();
2618 if (!(state->mCommand & FastMixerState::IDLE)) {
2619 state->mCommand = FastMixerState::COLD_IDLE;
2620 state->mColdFutexAddr = &mFastMixerFutex;
2621 state->mColdGen++;
2622 mFastMixerFutex = 0;
2623 sq->end();
2624 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2625 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002626 if (kUseFastMixer == FastMixer_Dynamic) {
2627 mNormalSink = mOutputSink;
2628 }
Glenn Kasten58912562012-04-03 10:45:00 -07002629 } else {
2630 sq->end(false /*didModify*/);
2631 }
2632 }
2633 PlaybackThread::threadLoop_standby();
2634}
2635
Glenn Kasten000f0e32012-03-01 17:10:56 -08002636// shared by MIXER and DIRECT, overridden by DUPLICATING
2637void AudioFlinger::PlaybackThread::threadLoop_standby()
2638{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002639 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2640 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002641}
2642
2643void AudioFlinger::MixerThread::threadLoop_mix()
2644{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002645 // obtain the presentation timestamp of the next output buffer
2646 int64_t pts;
2647 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002648
Glenn Kasten952eeb22012-03-06 11:30:57 -08002649 if (NULL != mOutput->stream->get_next_write_timestamp) {
2650 status = mOutput->stream->get_next_write_timestamp(
2651 mOutput->stream, &pts);
2652 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002653
Glenn Kasten952eeb22012-03-06 11:30:57 -08002654 if (status != NO_ERROR) {
2655 pts = AudioBufferProvider::kInvalidPTS;
2656 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002657
Glenn Kasten952eeb22012-03-06 11:30:57 -08002658 // mix buffers...
2659 mAudioMixer->process(pts);
2660 // increase sleep time progressively when application underrun condition clears.
2661 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2662 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2663 // such that we would underrun the audio HAL.
2664 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2665 sleepTimeShift--;
2666 }
2667 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002668 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002669 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002670}
2671
2672void AudioFlinger::MixerThread::threadLoop_sleepTime()
2673{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002674 // If no tracks are ready, sleep once for the duration of an output
2675 // buffer size, then write 0s to the output
2676 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002677 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002678 sleepTime = activeSleepTime >> sleepTimeShift;
2679 if (sleepTime < kMinThreadSleepTimeUs) {
2680 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002681 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002682 // reduce sleep time in case of consecutive application underruns to avoid
2683 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2684 // duration we would end up writing less data than needed by the audio HAL if
2685 // the condition persists.
2686 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2687 sleepTimeShift++;
2688 }
2689 } else {
2690 sleepTime = idleSleepTime;
2691 }
2692 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002693 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002694 memset (mMixBuffer, 0, mixBufferSize);
2695 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002696 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002697 }
2698 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002699}
2700
2701// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002702AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002703 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002704{
2705
Glenn Kasten29c23c32012-01-26 13:37:52 -08002706 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002707 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002708 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002709 size_t mixedTracks = 0;
2710 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002711 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002712 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002713 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002714
2715 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002716 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002717
Eric Laurent571d49c2010-08-11 05:20:11 -07002718 if (masterMute) {
2719 masterVolume = 0;
2720 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002721 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002722 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002723 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002724 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002725 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002726 masterVolume = (float)((v + (1 << 23)) >> 24);
2727 chain.clear();
2728 }
2729
Glenn Kasten288ed212012-04-25 17:52:27 -07002730 // prepare a new state to push
2731 FastMixerStateQueue *sq = NULL;
2732 FastMixerState *state = NULL;
2733 bool didModify = false;
2734 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2735 if (mFastMixer != NULL) {
2736 sq = mFastMixer->sq();
2737 state = sq->begin();
2738 }
2739
Mathias Agopian65ab4712010-07-14 17:59:35 -07002740 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002741 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002742 if (t == 0) continue;
2743
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002744 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002745 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002746
Glenn Kasten288ed212012-04-25 17:52:27 -07002747 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002748 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002749
2750 // It's theoretically possible (though unlikely) for a fast track to be created
2751 // and then removed within the same normal mix cycle. This is not a problem, as
2752 // the track never becomes active so it's fast mixer slot is never touched.
2753 // The converse, of removing an (active) track and then creating a new track
2754 // at the identical fast mixer slot within the same normal mix cycle,
2755 // is impossible because the slot isn't marked available until the end of each cycle.
2756 int j = track->mFastIndex;
2757 FastTrack *fastTrack = &state->mFastTracks[j];
2758
2759 // Determine whether the track is currently in underrun condition,
2760 // and whether it had a recent underrun.
2761 uint32_t underruns = mFastMixerDumpState.mTracks[j].mUnderruns;
2762 uint32_t recentUnderruns = (underruns - (track->mObservedUnderruns & ~1)) >> 1;
2763 // don't count underruns that occur while stopping or pausing
2764 if (!(track->isStopped() || track->isPausing())) {
2765 track->mUnderrunCount += recentUnderruns;
2766 }
2767 track->mObservedUnderruns = underruns;
2768
2769 // This is similar to the formula for normal tracks,
2770 // with a few modifications for fast tracks.
2771 bool isActive;
2772 if (track->isStopped()) {
2773 // track stays active after stop() until first underrun
2774 isActive = recentUnderruns == 0;
2775 } else if (track->isPaused() || track->isTerminated()) {
2776 isActive = false;
2777 } else if (track->isPausing()) {
2778 // ramp down is not yet implemented
2779 isActive = true;
2780 track->setPaused();
2781 } else if (track->isResuming()) {
2782 // ramp up is not yet implemented
2783 isActive = true;
2784 track->mState = TrackBase::ACTIVE;
2785 } else {
2786 // no minimum frame count for fast tracks; continual underrun is allowed,
2787 // but later could implement automatic pause after several consecutive underruns,
2788 // or auto-mute yet still consider the track active and continue to service it
2789 isActive = true;
2790 }
2791
2792 if (isActive) {
2793 // was it previously inactive?
2794 if (!(state->mTrackMask & (1 << j))) {
2795 ExtendedAudioBufferProvider *eabp = track;
2796 VolumeProvider *vp = track;
2797 fastTrack->mBufferProvider = eabp;
2798 fastTrack->mVolumeProvider = vp;
2799 fastTrack->mSampleRate = track->mSampleRate;
2800 fastTrack->mChannelMask = track->mChannelMask;
2801 fastTrack->mGeneration++;
2802 state->mTrackMask |= 1 << j;
2803 didModify = true;
2804 // no acknowledgement required for newly active tracks
2805 }
2806 // cache the combined master volume and stream type volume for fast mixer; this
2807 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2808 track->mCachedVolume = track->isMuted() ?
2809 0 : masterVolume * mStreamTypes[track->streamType()].volume;
2810 ++fastTracks;
2811 } else {
2812 // was it previously active?
2813 if (state->mTrackMask & (1 << j)) {
2814 fastTrack->mBufferProvider = NULL;
2815 fastTrack->mGeneration++;
2816 state->mTrackMask &= ~(1 << j);
2817 didModify = true;
2818 // If any fast tracks were removed, we must wait for acknowledgement
2819 // because we're about to decrement the last sp<> on those tracks.
2820 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
2821 }
2822 // Remainder of this block is copied from similar code for normal tracks
2823 if (track->isStopped()) {
2824 // Can't reset directly, as fast mixer is still polling this track
2825 // track->reset();
2826 // So instead mark this track as needing to be reset after push with ack
2827 resetMask |= 1 << i;
2828 }
2829 // This would be incomplete if we auto-paused on underrun
2830 size_t audioHALFrames =
2831 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2832 size_t framesWritten =
2833 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2834 if (track->presentationComplete(framesWritten, audioHALFrames)) {
2835 tracksToRemove->add(track);
2836 }
2837 // Avoids a misleading display in dumpsys
2838 track->mObservedUnderruns &= ~1;
Glenn Kasten58912562012-04-03 10:45:00 -07002839 }
2840 continue;
2841 }
2842
2843 { // local variable scope to avoid goto warning
2844
Mathias Agopian65ab4712010-07-14 17:59:35 -07002845 audio_track_cblk_t* cblk = track->cblk();
2846
2847 // The first time a track is added we wait
2848 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002849 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002850 // make sure that we have enough frames to mix one full buffer.
2851 // enforce this condition only once to enable draining the buffer in case the client
2852 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07002853 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002854 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002855 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07002856 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07002857 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002858 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07002859 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07002860 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002861 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07002862 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08002863 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07002864 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08002865 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2866 // the minimum track buffer size is normally twice the number of frames necessary
2867 // to fill one buffer and the resampler should not leave more than one buffer worth
2868 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002869 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002870 }
2871 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002872 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002873 !track->isPaused() && !track->isTerminated())
2874 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002875 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002876
2877 mixedTracks++;
2878
2879 // track->mainBuffer() != mMixBuffer means there is an effect chain
2880 // connected to the track
2881 chain.clear();
2882 if (track->mainBuffer() != mMixBuffer) {
2883 chain = getEffectChain_l(track->sessionId());
2884 // Delegate volume control to effect in track effect chain if needed
2885 if (chain != 0) {
2886 tracksWithEffect++;
2887 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002888 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002889 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002890 }
2891 }
2892
2893
2894 int param = AudioMixer::VOLUME;
2895 if (track->mFillingUpStatus == Track::FS_FILLED) {
2896 // no ramp for the first volume setting
2897 track->mFillingUpStatus = Track::FS_ACTIVE;
2898 if (track->mState == TrackBase::RESUMING) {
2899 track->mState = TrackBase::ACTIVE;
2900 param = AudioMixer::RAMP_VOLUME;
2901 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002902 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002903 } else if (cblk->server != 0) {
2904 // If the track is stopped before the first frame was mixed,
2905 // do not apply ramp
2906 param = AudioMixer::RAMP_VOLUME;
2907 }
2908
2909 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002910 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002911 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002912 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002913 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002914 if (track->isPausing()) {
2915 track->setPaused();
2916 }
2917 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002918
Mathias Agopian65ab4712010-07-14 17:59:35 -07002919 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002920 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002921 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002922 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002923 vl = vlr & 0xFFFF;
2924 vr = vlr >> 16;
2925 // track volumes come from shared memory, so can't be trusted and must be clamped
2926 if (vl > MAX_GAIN_INT) {
2927 ALOGV("Track left volume out of range: %04X", vl);
2928 vl = MAX_GAIN_INT;
2929 }
2930 if (vr > MAX_GAIN_INT) {
2931 ALOGV("Track right volume out of range: %04X", vr);
2932 vr = MAX_GAIN_INT;
2933 }
2934 // now apply the master volume and stream type volume
2935 vl = (uint32_t)(v * vl) << 12;
2936 vr = (uint32_t)(v * vr) << 12;
2937 // assuming master volume and stream type volume each go up to 1.0,
2938 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002939
Glenn Kasten05632a52012-01-03 14:22:33 -08002940 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2941 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002942 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002943 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002944 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002945 }
2946 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002947 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002948 // Delegate volume control to effect in track effect chain if needed
2949 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2950 // Do not ramp volume if volume is controlled by effect
2951 param = AudioMixer::VOLUME;
2952 track->mHasVolumeController = true;
2953 } else {
2954 // force no volume ramp when volume controller was just disabled or removed
2955 // from effect chain to avoid volume spike
2956 if (track->mHasVolumeController) {
2957 param = AudioMixer::VOLUME;
2958 }
2959 track->mHasVolumeController = false;
2960 }
2961
2962 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002963 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002964 vl = (vl + (1 << 11)) >> 12;
2965 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
2966 vr = (vr + (1 << 11)) >> 12;
2967 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002968
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002969 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 -07002970
Mathias Agopian65ab4712010-07-14 17:59:35 -07002971 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002972 mAudioMixer->setBufferProvider(name, track);
2973 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002974
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002975 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
2976 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
2977 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002978 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002979 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002980 AudioMixer::TRACK,
2981 AudioMixer::FORMAT, (void *)track->format());
2982 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002983 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002984 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002985 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002986 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002987 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002988 AudioMixer::RESAMPLE,
2989 AudioMixer::SAMPLE_RATE,
2990 (void *)(cblk->sampleRate));
2991 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002992 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002993 AudioMixer::TRACK,
2994 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2995 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002996 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002997 AudioMixer::TRACK,
2998 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2999
3000 // reset retry count
3001 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003002
Eric Laurent27741442012-01-17 19:20:12 -08003003 // If one track is ready, set the mixer ready if:
3004 // - the mixer was not ready during previous round OR
3005 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003006 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003007 mixerStatus != MIXER_TRACKS_ENABLED) {
3008 mixerStatus = MIXER_TRACKS_READY;
3009 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003010 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003011 //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 -07003012 if (track->isStopped()) {
3013 track->reset();
3014 }
Eric Laurent83faee02012-04-27 18:24:29 -07003015 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3016 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003017 // We have consumed all the buffers of this track.
3018 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003019 // TODO: use actual buffer filling status instead of latency when available from
3020 // audio HAL
3021 size_t audioHALFrames =
3022 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3023 size_t framesWritten =
3024 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3025 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3026 tracksToRemove->add(track);
3027 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003028 } else {
3029 // No buffers for this track. Give it a few chances to
3030 // fill a buffer, then remove it from active list.
3031 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003032 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003033 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003034 // indicate to client process that the track was disabled because of underrun;
3035 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003036 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003037 // If one track is not ready, mark the mixer also not ready if:
3038 // - the mixer was ready during previous round OR
3039 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003040 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003041 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003042 mixerStatus = MIXER_TRACKS_ENABLED;
3043 }
3044 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003045 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003046 }
Glenn Kasten58912562012-04-03 10:45:00 -07003047
3048 } // local variable scope to avoid goto warning
3049track_is_ready: ;
3050
Mathias Agopian65ab4712010-07-14 17:59:35 -07003051 }
3052
Glenn Kasten288ed212012-04-25 17:52:27 -07003053 // Push the new FastMixer state if necessary
3054 if (didModify) {
3055 state->mFastTracksGen++;
3056 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3057 if (kUseFastMixer == FastMixer_Dynamic &&
3058 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3059 state->mCommand = FastMixerState::COLD_IDLE;
3060 state->mColdFutexAddr = &mFastMixerFutex;
3061 state->mColdGen++;
3062 mFastMixerFutex = 0;
3063 if (kUseFastMixer == FastMixer_Dynamic) {
3064 mNormalSink = mOutputSink;
3065 }
3066 // If we go into cold idle, need to wait for acknowledgement
3067 // so that fast mixer stops doing I/O.
3068 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3069 }
3070 sq->end();
3071 }
3072 if (sq != NULL) {
3073 sq->end(didModify);
3074 sq->push(block);
3075 }
3076
3077 // Now perform the deferred reset on fast tracks that have stopped
3078 while (resetMask != 0) {
3079 size_t i = __builtin_ctz(resetMask);
3080 ALOG_ASSERT(i < count);
3081 resetMask &= ~(1 << i);
3082 sp<Track> t = mActiveTracks[i].promote();
3083 if (t == 0) continue;
3084 Track* track = t.get();
3085 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3086 track->reset();
3087 }
Glenn Kasten58912562012-04-03 10:45:00 -07003088
Mathias Agopian65ab4712010-07-14 17:59:35 -07003089 // remove all the tracks that need to be...
3090 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003091 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003092 for (size_t i=0 ; i<count ; i++) {
3093 const sp<Track>& track = tracksToRemove->itemAt(i);
3094 mActiveTracks.remove(track);
3095 if (track->mainBuffer() != mMixBuffer) {
3096 chain = getEffectChain_l(track->sessionId());
3097 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003098 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003099 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003100 }
3101 }
3102 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003103 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003104 }
3105 }
3106 }
3107
3108 // mix buffer must be cleared if all tracks are connected to an
3109 // effect chain as in this case the mixer will not write to
3110 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003111 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3112 // FIXME as a performance optimization, should remember previous zero status
3113 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003114 }
3115
Glenn Kasten58912562012-04-03 10:45:00 -07003116 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003117 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003118 if (fastTracks > 0) {
3119 mixerStatus = MIXER_TRACKS_READY;
3120 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003121 return mixerStatus;
3122}
3123
Glenn Kasten66fcab92012-02-24 14:59:21 -08003124/*
3125The derived values that are cached:
3126 - mixBufferSize from frame count * frame size
3127 - activeSleepTime from activeSleepTimeUs()
3128 - idleSleepTime from idleSleepTimeUs()
3129 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3130 - maxPeriod from frame count and sample rate (MIXER only)
3131
3132The parameters that affect these derived values are:
3133 - frame count
3134 - frame size
3135 - sample rate
3136 - device type: A2DP or not
3137 - device latency
3138 - format: PCM or not
3139 - active sleep time
3140 - idle sleep time
3141*/
3142
3143void AudioFlinger::PlaybackThread::cacheParameters_l()
3144{
Glenn Kasten58912562012-04-03 10:45:00 -07003145 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003146 activeSleepTime = activeSleepTimeUs();
3147 idleSleepTime = idleSleepTimeUs();
3148}
3149
Glenn Kastenfff6d712012-01-12 16:38:12 -08003150void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003151{
Steve Block3856b092011-10-20 11:56:00 +01003152 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003153 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003154 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003155
Mathias Agopian65ab4712010-07-14 17:59:35 -07003156 size_t size = mTracks.size();
3157 for (size_t i = 0; i < size; i++) {
3158 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003159 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003160 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003161 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003162 }
3163 }
3164}
3165
Mathias Agopian65ab4712010-07-14 17:59:35 -07003166// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003167int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003168{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003169 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003170}
3171
3172// deleteTrackName_l() must be called with ThreadBase::mLock held
3173void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3174{
Steve Block3856b092011-10-20 11:56:00 +01003175 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003176 mAudioMixer->deleteTrackName(name);
3177}
3178
3179// checkForNewParameters_l() must be called with ThreadBase::mLock held
3180bool AudioFlinger::MixerThread::checkForNewParameters_l()
3181{
Glenn Kasten58912562012-04-03 10:45:00 -07003182 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3183 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 bool reconfig = false;
3185
3186 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003187
3188 if (mFastMixer != NULL) {
3189 FastMixerStateQueue *sq = mFastMixer->sq();
3190 FastMixerState *state = sq->begin();
3191 if (!(state->mCommand & FastMixerState::IDLE)) {
3192 previousCommand = state->mCommand;
3193 state->mCommand = FastMixerState::HOT_IDLE;
3194 sq->end();
3195 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3196 } else {
3197 sq->end(false /*didModify*/);
3198 }
3199 }
3200
Mathias Agopian65ab4712010-07-14 17:59:35 -07003201 status_t status = NO_ERROR;
3202 String8 keyValuePair = mNewParameters[0];
3203 AudioParameter param = AudioParameter(keyValuePair);
3204 int value;
3205
3206 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3207 reconfig = true;
3208 }
3209 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003210 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003211 status = BAD_VALUE;
3212 } else {
3213 reconfig = true;
3214 }
3215 }
3216 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003217 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003218 status = BAD_VALUE;
3219 } else {
3220 reconfig = true;
3221 }
3222 }
3223 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3224 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003225 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003226 // if frame count is changed after track creation
3227 if (!mTracks.isEmpty()) {
3228 status = INVALID_OPERATION;
3229 } else {
3230 reconfig = true;
3231 }
3232 }
3233 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003234#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003235 // when changing the audio output device, call addBatteryData to notify
3236 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003237 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003238 uint32_t params = 0;
3239 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003240 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003241 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3242 }
3243
3244 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003245 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003246 // check if any other device (except speaker) is on
3247 if (value & deviceWithoutSpeaker ) {
3248 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3249 }
3250
3251 if (params != 0) {
3252 addBatteryData(params);
3253 }
3254 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003255#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003256
Mathias Agopian65ab4712010-07-14 17:59:35 -07003257 // forward device change to effects that have requested to be
3258 // aware of attached audio device.
3259 mDevice = (uint32_t)value;
3260 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003261 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003262 }
3263 }
3264
3265 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003266 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003267 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003268 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003269 mOutput->stream->common.standby(&mOutput->stream->common);
3270 mStandby = true;
3271 mBytesWritten = 0;
3272 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003273 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003274 }
3275 if (status == NO_ERROR && reconfig) {
3276 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003277 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3278 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003279 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003280 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003281 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003282 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003283 if (name < 0) break;
3284 mTracks[i]->mName = name;
3285 // limit track sample rate to 2 x new output sample rate
3286 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3287 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3288 }
3289 }
3290 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3291 }
3292 }
3293
3294 mNewParameters.removeAt(0);
3295
3296 mParamStatus = status;
3297 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003298 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3299 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003300 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003301 }
Glenn Kasten58912562012-04-03 10:45:00 -07003302
3303 if (!(previousCommand & FastMixerState::IDLE)) {
3304 ALOG_ASSERT(mFastMixer != NULL);
3305 FastMixerStateQueue *sq = mFastMixer->sq();
3306 FastMixerState *state = sq->begin();
3307 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3308 state->mCommand = previousCommand;
3309 sq->end();
3310 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3311 }
3312
Mathias Agopian65ab4712010-07-14 17:59:35 -07003313 return reconfig;
3314}
3315
3316status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3317{
3318 const size_t SIZE = 256;
3319 char buffer[SIZE];
3320 String8 result;
3321
3322 PlaybackThread::dumpInternals(fd, args);
3323
3324 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3325 result.append(buffer);
3326 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003327
3328 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3329 FastMixerDumpState copy = mFastMixerDumpState;
3330 copy.dump(fd);
3331
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332 return NO_ERROR;
3333}
3334
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003335uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003336{
Glenn Kasten58912562012-04-03 10:45:00 -07003337 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003338}
3339
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003340uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003341{
Glenn Kasten58912562012-04-03 10:45:00 -07003342 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003343}
3344
Glenn Kasten66fcab92012-02-24 14:59:21 -08003345void AudioFlinger::MixerThread::cacheParameters_l()
3346{
3347 PlaybackThread::cacheParameters_l();
3348
3349 // FIXME: Relaxed timing because of a certain device that can't meet latency
3350 // Should be reduced to 2x after the vendor fixes the driver issue
3351 // increase threshold again due to low power audio mode. The way this warning
3352 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003353 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003354}
3355
Mathias Agopian65ab4712010-07-14 17:59:35 -07003356// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003357AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3358 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003359 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003360 // mLeftVolFloat, mRightVolFloat
3361 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07003362{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003363}
3364
3365AudioFlinger::DirectOutputThread::~DirectOutputThread()
3366{
3367}
3368
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003369AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3370 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003371)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003372{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003373 sp<Track> trackToRemove;
3374
Glenn Kastenfec279f2012-03-08 07:47:15 -08003375 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003376
Glenn Kasten952eeb22012-03-06 11:30:57 -08003377 // find out which tracks need to be processed
3378 if (mActiveTracks.size() != 0) {
3379 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003380 // The track died recently
3381 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003382
Glenn Kasten952eeb22012-03-06 11:30:57 -08003383 Track* const track = t.get();
3384 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003385
Glenn Kasten952eeb22012-03-06 11:30:57 -08003386 // The first time a track is added we wait
3387 // for all its buffers to be filled before processing it
3388 if (cblk->framesReady() && track->isReady() &&
3389 !track->isPaused() && !track->isTerminated())
3390 {
3391 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003392
Glenn Kasten952eeb22012-03-06 11:30:57 -08003393 if (track->mFillingUpStatus == Track::FS_FILLED) {
3394 track->mFillingUpStatus = Track::FS_ACTIVE;
3395 mLeftVolFloat = mRightVolFloat = 0;
3396 mLeftVolShort = mRightVolShort = 0;
3397 if (track->mState == TrackBase::RESUMING) {
3398 track->mState = TrackBase::ACTIVE;
3399 rampVolume = true;
3400 }
3401 } else if (cblk->server != 0) {
3402 // If the track is stopped before the first frame was mixed,
3403 // do not apply ramp
3404 rampVolume = true;
3405 }
3406 // compute volume for this track
3407 float left, right;
3408 if (track->isMuted() || mMasterMute || track->isPausing() ||
3409 mStreamTypes[track->streamType()].mute) {
3410 left = right = 0;
3411 if (track->isPausing()) {
3412 track->setPaused();
3413 }
3414 } else {
3415 float typeVolume = mStreamTypes[track->streamType()].volume;
3416 float v = mMasterVolume * typeVolume;
3417 uint32_t vlr = cblk->getVolumeLR();
3418 float v_clamped = v * (vlr & 0xFFFF);
3419 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3420 left = v_clamped/MAX_GAIN;
3421 v_clamped = v * (vlr >> 16);
3422 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3423 right = v_clamped/MAX_GAIN;
3424 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003425
Glenn Kasten952eeb22012-03-06 11:30:57 -08003426 if (left != mLeftVolFloat || right != mRightVolFloat) {
3427 mLeftVolFloat = left;
3428 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003429
Glenn Kasten952eeb22012-03-06 11:30:57 -08003430 // If audio HAL implements volume control,
3431 // force software volume to nominal value
3432 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
3433 left = 1.0f;
3434 right = 1.0f;
3435 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003436
Glenn Kasten952eeb22012-03-06 11:30:57 -08003437 // Convert volumes from float to 8.24
3438 uint32_t vl = (uint32_t)(left * (1 << 24));
3439 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003440
Glenn Kasten952eeb22012-03-06 11:30:57 -08003441 // Delegate volume control to effect in track effect chain if needed
3442 // only one effect chain can be present on DirectOutputThread, so if
3443 // there is one, the track is connected to it
3444 if (!mEffectChains.isEmpty()) {
3445 // Do not ramp volume if volume is controlled by effect
3446 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003447 rampVolume = false;
3448 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003449 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003450
Glenn Kasten952eeb22012-03-06 11:30:57 -08003451 // Convert volumes from 8.24 to 4.12 format
3452 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
3453 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3454 leftVol = (uint16_t)v_clamped;
3455 v_clamped = (vr + (1 << 11)) >> 12;
3456 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3457 rightVol = (uint16_t)v_clamped;
3458 } else {
3459 leftVol = mLeftVolShort;
3460 rightVol = mRightVolShort;
3461 rampVolume = false;
3462 }
3463
3464 // reset retry count
3465 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003466 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003467 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003468 } else {
3469 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
3470 if (track->isStopped()) {
3471 track->reset();
3472 }
3473 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
3474 // We have consumed all the buffers of this track.
3475 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003476 // TODO: implement behavior for compressed audio
3477 size_t audioHALFrames =
3478 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3479 size_t framesWritten =
3480 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3481 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3482 trackToRemove = track;
3483 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003484 } else {
3485 // No buffers for this track. Give it a few chances to
3486 // fill a buffer, then remove it from active list.
3487 if (--(track->mRetryCount) <= 0) {
3488 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3489 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003490 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003491 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003492 }
3493 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003494 }
3495 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003496
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003497 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003498 // remove all the tracks that need to be...
3499 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003500 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003501 mActiveTracks.remove(trackToRemove);
3502 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003503 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003504 trackToRemove->sessionId());
3505 mEffectChains[0]->decActiveTrackCnt();
3506 }
3507 if (trackToRemove->isTerminated()) {
3508 removeTrack_l(trackToRemove);
3509 }
3510 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003511
Glenn Kastenfec279f2012-03-08 07:47:15 -08003512 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003513}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003514
Glenn Kasten000f0e32012-03-01 17:10:56 -08003515void AudioFlinger::DirectOutputThread::threadLoop_mix()
3516{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003517 AudioBufferProvider::Buffer buffer;
3518 size_t frameCount = mFrameCount;
3519 int8_t *curBuf = (int8_t *)mMixBuffer;
3520 // output audio to hardware
3521 while (frameCount) {
3522 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003523 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003524 if (CC_UNLIKELY(buffer.raw == NULL)) {
3525 memset(curBuf, 0, frameCount * mFrameSize);
3526 break;
3527 }
3528 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3529 frameCount -= buffer.frameCount;
3530 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003531 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003532 }
3533 sleepTime = 0;
3534 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003535 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003536
3537 // apply volume
3538
3539 // Do not apply volume on compressed audio
3540 if (!audio_is_linear_pcm(mFormat)) {
3541 return;
3542 }
3543
3544 // convert to signed 16 bit before volume calculation
3545 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3546 size_t count = mFrameCount * mChannelCount;
3547 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
3548 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003549 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003550 *dst-- = (int16_t)(*src--^0x80) << 8;
3551 }
3552 }
3553
3554 frameCount = mFrameCount;
3555 int16_t *out = mMixBuffer;
3556 if (rampVolume) {
3557 if (mChannelCount == 1) {
3558 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3559 int32_t vlInc = d / (int32_t)frameCount;
3560 int32_t vl = ((int32_t)mLeftVolShort << 16);
3561 do {
3562 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3563 out++;
3564 vl += vlInc;
3565 } while (--frameCount);
3566
3567 } else {
3568 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3569 int32_t vlInc = d / (int32_t)frameCount;
3570 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3571 int32_t vrInc = d / (int32_t)frameCount;
3572 int32_t vl = ((int32_t)mLeftVolShort << 16);
3573 int32_t vr = ((int32_t)mRightVolShort << 16);
3574 do {
3575 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3576 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3577 out += 2;
3578 vl += vlInc;
3579 vr += vrInc;
3580 } while (--frameCount);
3581 }
3582 } else {
3583 if (mChannelCount == 1) {
3584 do {
3585 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3586 out++;
3587 } while (--frameCount);
3588 } else {
3589 do {
3590 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3591 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3592 out += 2;
3593 } while (--frameCount);
3594 }
3595 }
3596
3597 // convert back to unsigned 8 bit after volume calculation
3598 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3599 size_t count = mFrameCount * mChannelCount;
3600 int16_t *src = mMixBuffer;
3601 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003602 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003603 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3604 }
3605 }
3606
3607 mLeftVolShort = leftVol;
3608 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003609}
3610
3611void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3612{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003613 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003614 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003615 sleepTime = activeSleepTime;
3616 } else {
3617 sleepTime = idleSleepTime;
3618 }
3619 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003620 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003621 sleepTime = 0;
3622 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003623}
3624
3625// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003626int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003627{
3628 return 0;
3629}
3630
3631// deleteTrackName_l() must be called with ThreadBase::mLock held
3632void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3633{
3634}
3635
3636// checkForNewParameters_l() must be called with ThreadBase::mLock held
3637bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3638{
3639 bool reconfig = false;
3640
3641 while (!mNewParameters.isEmpty()) {
3642 status_t status = NO_ERROR;
3643 String8 keyValuePair = mNewParameters[0];
3644 AudioParameter param = AudioParameter(keyValuePair);
3645 int value;
3646
3647 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3648 // do not accept frame count changes if tracks are open as the track buffer
3649 // size depends on frame count and correct behavior would not be garantied
3650 // if frame count is changed after track creation
3651 if (!mTracks.isEmpty()) {
3652 status = INVALID_OPERATION;
3653 } else {
3654 reconfig = true;
3655 }
3656 }
3657 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003658 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003659 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003660 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003661 mOutput->stream->common.standby(&mOutput->stream->common);
3662 mStandby = true;
3663 mBytesWritten = 0;
3664 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003665 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003666 }
3667 if (status == NO_ERROR && reconfig) {
3668 readOutputParameters();
3669 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3670 }
3671 }
3672
3673 mNewParameters.removeAt(0);
3674
3675 mParamStatus = status;
3676 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003677 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3678 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003679 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003680 }
3681 return reconfig;
3682}
3683
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003684uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003685{
3686 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003687 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003688 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003689 } else {
3690 time = 10000;
3691 }
3692 return time;
3693}
3694
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003695uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003696{
3697 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003698 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003699 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003700 } else {
3701 time = 10000;
3702 }
3703 return time;
3704}
3705
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003706uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003707{
3708 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003709 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003710 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3711 } else {
3712 time = 10000;
3713 }
3714 return time;
3715}
3716
Glenn Kasten66fcab92012-02-24 14:59:21 -08003717void AudioFlinger::DirectOutputThread::cacheParameters_l()
3718{
3719 PlaybackThread::cacheParameters_l();
3720
3721 // use shorter standby delay as on normal output to release
3722 // hardware resources as soon as possible
3723 standbyDelay = microseconds(activeSleepTime*2);
3724}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003725
Mathias Agopian65ab4712010-07-14 17:59:35 -07003726// ----------------------------------------------------------------------------
3727
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003728AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003729 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003730 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3731 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003732{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003733 addOutputTrack(mainThread);
3734}
3735
3736AudioFlinger::DuplicatingThread::~DuplicatingThread()
3737{
3738 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3739 mOutputTracks[i]->destroy();
3740 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003741}
3742
Glenn Kasten000f0e32012-03-01 17:10:56 -08003743void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003744{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003745 // mix buffers...
3746 if (outputsReady(outputTracks)) {
3747 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3748 } else {
3749 memset(mMixBuffer, 0, mixBufferSize);
3750 }
3751 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003752 writeFrames = mNormalFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003753}
3754
3755void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3756{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003757 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003758 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003759 sleepTime = activeSleepTime;
3760 } else {
3761 sleepTime = idleSleepTime;
3762 }
3763 } else if (mBytesWritten != 0) {
3764 // flush remaining overflow buffers in output tracks
3765 for (size_t i = 0; i < outputTracks.size(); i++) {
3766 if (outputTracks[i]->isActive()) {
3767 sleepTime = 0;
3768 writeFrames = 0;
3769 memset(mMixBuffer, 0, mixBufferSize);
3770 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003771 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003772 }
3773 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003774}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003775
Glenn Kasten000f0e32012-03-01 17:10:56 -08003776void AudioFlinger::DuplicatingThread::threadLoop_write()
3777{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003778 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003779 for (size_t i = 0; i < outputTracks.size(); i++) {
3780 outputTracks[i]->write(mMixBuffer, writeFrames);
3781 }
3782 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003783}
Glenn Kasten688a6402012-02-29 07:57:06 -08003784
Glenn Kasten000f0e32012-03-01 17:10:56 -08003785void AudioFlinger::DuplicatingThread::threadLoop_standby()
3786{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003787 // DuplicatingThread implements standby by stopping all tracks
3788 for (size_t i = 0; i < outputTracks.size(); i++) {
3789 outputTracks[i]->stop();
3790 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003791}
3792
Glenn Kastenfa26a852012-03-06 11:28:04 -08003793void AudioFlinger::DuplicatingThread::saveOutputTracks()
3794{
3795 outputTracks = mOutputTracks;
3796}
3797
3798void AudioFlinger::DuplicatingThread::clearOutputTracks()
3799{
3800 outputTracks.clear();
3801}
3802
Mathias Agopian65ab4712010-07-14 17:59:35 -07003803void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3804{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003805 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003806 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003807 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003808 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003809 this,
3810 mSampleRate,
3811 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003812 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003813 frameCount);
3814 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003815 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003816 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003817 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003818 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003819 }
3820}
3821
3822void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3823{
3824 Mutex::Autolock _l(mLock);
3825 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003826 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003827 mOutputTracks[i]->destroy();
3828 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003829 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003830 return;
3831 }
3832 }
Steve Block3856b092011-10-20 11:56:00 +01003833 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003834}
3835
Glenn Kasten438b0362012-03-06 11:24:48 -08003836// caller must hold mLock
3837void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003838{
3839 mWaitTimeMs = UINT_MAX;
3840 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3841 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003842 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003843 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3844 if (waitTimeMs < mWaitTimeMs) {
3845 mWaitTimeMs = waitTimeMs;
3846 }
3847 }
3848 }
3849}
3850
3851
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003852bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003853{
3854 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003855 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003856 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003857 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003858 return false;
3859 }
3860 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3861 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003862 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003863 return false;
3864 }
3865 }
3866 return true;
3867}
3868
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003869uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003870{
3871 return (mWaitTimeMs * 1000) / 2;
3872}
3873
Glenn Kasten66fcab92012-02-24 14:59:21 -08003874void AudioFlinger::DuplicatingThread::cacheParameters_l()
3875{
3876 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3877 updateWaitTime_l();
3878
3879 MixerThread::cacheParameters_l();
3880}
3881
Mathias Agopian65ab4712010-07-14 17:59:35 -07003882// ----------------------------------------------------------------------------
3883
3884// TrackBase constructor must be called with AudioFlinger::mLock held
3885AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003886 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003887 const sp<Client>& client,
3888 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003889 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003890 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003891 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003892 const sp<IMemory>& sharedBuffer,
3893 int sessionId)
3894 : RefBase(),
3895 mThread(thread),
3896 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003897 mCblk(NULL),
3898 // mBuffer
3899 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003900 mFrameCount(0),
3901 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07003902 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003903 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003904 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003905 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003906 // mChannelCount
3907 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003908{
Steve Block3856b092011-10-20 11:56:00 +01003909 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003910
Steve Blockb8a80522011-12-20 16:23:08 +00003911 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003912 size_t size = sizeof(audio_track_cblk_t);
3913 uint8_t channelCount = popcount(channelMask);
3914 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3915 if (sharedBuffer == 0) {
3916 size += bufferSize;
3917 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003918
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003919 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003920 mCblkMemory = client->heap()->allocate(size);
3921 if (mCblkMemory != 0) {
3922 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003923 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003924 new(mCblk) audio_track_cblk_t();
3925 // clear all buffers
3926 mCblk->frameCount = frameCount;
3927 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003928// uncomment the following lines to quickly test 32-bit wraparound
3929// mCblk->user = 0xffff0000;
3930// mCblk->server = 0xffff0000;
3931// mCblk->userBase = 0xffff0000;
3932// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003933 mChannelCount = channelCount;
3934 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003935 if (sharedBuffer == 0) {
3936 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3937 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3938 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003939 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003940 mCblk->flags = CBLK_UNDERRUN_ON;
3941 } else {
3942 mBuffer = sharedBuffer->pointer();
3943 }
3944 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3945 }
3946 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003947 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003948 client->heap()->dump("AudioTrack");
3949 return;
3950 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003951 } else {
3952 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07003953 // construct the shared structure in-place.
3954 new(mCblk) audio_track_cblk_t();
3955 // clear all buffers
3956 mCblk->frameCount = frameCount;
3957 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003958// uncomment the following lines to quickly test 32-bit wraparound
3959// mCblk->user = 0xffff0000;
3960// mCblk->server = 0xffff0000;
3961// mCblk->userBase = 0xffff0000;
3962// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003963 mChannelCount = channelCount;
3964 mChannelMask = channelMask;
3965 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3966 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3967 // Force underrun condition to avoid false underrun callback until first data is
3968 // written to buffer (other flags are cleared)
3969 mCblk->flags = CBLK_UNDERRUN_ON;
3970 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003971 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003972}
3973
3974AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3975{
Glenn Kastena0d68332012-01-27 16:47:15 -08003976 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003977 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003978 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003979 } else {
3980 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003981 }
3982 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003983 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003984 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003985 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003986 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003987 // If the client's reference count drops to zero, the associated destructor
3988 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3989 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003990 mClient.clear();
3991 }
3992}
3993
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08003994// AudioBufferProvider interface
3995// getNextBuffer() = 0;
3996// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07003997void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3998{
Glenn Kastene0feee32011-12-13 11:53:26 -08003999 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004000 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004001 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004002 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004003 buffer->frameCount = 0;
4004}
4005
4006bool AudioFlinger::ThreadBase::TrackBase::step() {
4007 bool result;
4008 audio_track_cblk_t* cblk = this->cblk();
4009
4010 result = cblk->stepServer(mFrameCount);
4011 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004012 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004013 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004014 }
4015 return result;
4016}
4017
4018void AudioFlinger::ThreadBase::TrackBase::reset() {
4019 audio_track_cblk_t* cblk = this->cblk();
4020
4021 cblk->user = 0;
4022 cblk->server = 0;
4023 cblk->userBase = 0;
4024 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004025 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004026 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004027}
4028
Mathias Agopian65ab4712010-07-14 17:59:35 -07004029int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4030 return (int)mCblk->sampleRate;
4031}
4032
Mathias Agopian65ab4712010-07-14 17:59:35 -07004033void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4034 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004035 size_t frameSize = cblk->frameSize;
4036 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4037 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004038
4039 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004040 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4041 "TrackBase::getBuffer buffer out of range:\n"
4042 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4043 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004044 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004045 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004046
4047 return bufferStart;
4048}
4049
Eric Laurenta011e352012-03-29 15:51:43 -07004050status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4051{
4052 mSyncEvents.add(event);
4053 return NO_ERROR;
4054}
4055
Mathias Agopian65ab4712010-07-14 17:59:35 -07004056// ----------------------------------------------------------------------------
4057
4058// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4059AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004060 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004061 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004062 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004063 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004064 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004065 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004066 int frameCount,
4067 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004068 int sessionId,
4069 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004070 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004071 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004072 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004073 // mRetryCount initialized later when needed
4074 mSharedBuffer(sharedBuffer),
4075 mStreamType(streamType),
4076 mName(-1), // see note below
4077 mMainBuffer(thread->mixBuffer()),
4078 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004079 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004080 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004081 mFlags(flags),
4082 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004083 mObservedUnderruns(0),
4084 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004085 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004086{
4087 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004088 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4089 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004090 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten58912562012-04-03 10:45:00 -07004091 if (flags & IAudioFlinger::TRACK_FAST) {
4092 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4093 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4094 int i = __builtin_ctz(thread->mFastTrackAvailMask);
4095 ALOG_ASSERT(0 < i && i < FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004096 // FIXME This is too eager. We allocate a fast track index before the
4097 // fast track becomes active. Since fast tracks are a scarce resource,
4098 // this means we are potentially denying other more important fast tracks from
4099 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004100 mFastIndex = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004101 // Read the initial underruns because this field is never cleared by the fast mixer
4102 mObservedUnderruns = thread->getFastTrackUnderruns(i) & ~1;
Glenn Kasten58912562012-04-03 10:45:00 -07004103 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004104 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004105 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07004106 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kastenf9959012012-03-19 11:14:37 -07004107 if (mName < 0) {
4108 ALOGE("no more track names available");
Glenn Kasten288ed212012-04-25 17:52:27 -07004109 // FIXME bug - if sufficient fast track indices, but insufficient normal mixer names,
4110 // then we leak a fast track index. Should swap these two sections, or better yet
4111 // only allocate a normal mixer name for normal tracks.
Glenn Kastenf9959012012-03-19 11:14:37 -07004112 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004113 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004114 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004115}
4116
4117AudioFlinger::PlaybackThread::Track::~Track()
4118{
Steve Block3856b092011-10-20 11:56:00 +01004119 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004120 sp<ThreadBase> thread = mThread.promote();
4121 if (thread != 0) {
4122 Mutex::Autolock _l(thread->mLock);
4123 mState = TERMINATED;
4124 }
4125}
4126
4127void AudioFlinger::PlaybackThread::Track::destroy()
4128{
4129 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4130 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004131 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004132 // we must acquire a strong reference on this Track before locking mLock
4133 // here so that the destructor is called only when exiting this function.
4134 // On the other hand, as long as Track::destroy() is only called by
4135 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4136 // this Track with its member mTrack.
4137 sp<Track> keep(this);
4138 { // scope for mLock
4139 sp<ThreadBase> thread = mThread.promote();
4140 if (thread != 0) {
4141 if (!isOutputTrack()) {
4142 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004143 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004144
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004145#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004146 // to track the speaker usage
4147 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004148#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004149 }
4150 AudioSystem::releaseOutput(thread->id());
4151 }
4152 Mutex::Autolock _l(thread->mLock);
4153 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4154 playbackThread->destroyTrack_l(this);
4155 }
4156 }
4157}
4158
Glenn Kasten288ed212012-04-25 17:52:27 -07004159/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4160{
Glenn Kastene213c862012-04-25 13:46:15 -07004161 result.append(" Name Client Type Fmt Chn mask Session mFrCnt fCount S M F SRate L dB R dB "
4162 " Server User Main buf Aux Buf Flags FastUnder\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004163}
4164
Mathias Agopian65ab4712010-07-14 17:59:35 -07004165void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4166{
Glenn Kasten83d86532012-01-17 14:39:34 -08004167 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004168 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004169 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004170 } else {
4171 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4172 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004173 track_state state = mState;
4174 char stateChar;
4175 switch (state) {
4176 case IDLE:
4177 stateChar = 'I';
4178 break;
4179 case TERMINATED:
4180 stateChar = 'T';
4181 break;
4182 case STOPPED:
4183 stateChar = 'S';
4184 break;
4185 case RESUMING:
4186 stateChar = 'R';
4187 break;
4188 case ACTIVE:
4189 stateChar = 'A';
4190 break;
4191 case PAUSING:
4192 stateChar = 'p';
4193 break;
4194 case PAUSED:
4195 stateChar = 'P';
4196 break;
4197 default:
4198 stateChar = '?';
4199 break;
4200 }
4201 bool nowInUnderrun = mObservedUnderruns & 1;
Glenn Kastene213c862012-04-25 13:46:15 -07004202 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4203 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004204 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004205 mStreamType,
4206 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004207 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004208 mSessionId,
4209 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004210 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004211 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004212 mMute,
4213 mFillingUpStatus,
4214 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004215 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4216 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004217 mCblk->server,
4218 mCblk->user,
4219 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004220 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004221 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004222 mUnderrunCount,
4223 nowInUnderrun ? '*' : ' ');
Mathias Agopian65ab4712010-07-14 17:59:35 -07004224}
4225
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004226// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004227status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004228 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004229{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004230 audio_track_cblk_t* cblk = this->cblk();
4231 uint32_t framesReady;
4232 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004233
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004234 // Check if last stepServer failed, try to step now
4235 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004236 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4237 // Since the fast mixer is higher priority than client callback thread,
4238 // it does not result in priority inversion for client.
4239 // But a non-blocking solution would be preferable to avoid
4240 // fast mixer being unable to tryLock(), and
4241 // to avoid the extra context switches if the client wakes up,
4242 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004243 if (!step()) goto getNextBuffer_exit;
4244 ALOGV("stepServer recovered");
4245 mStepServerFailed = false;
4246 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004247
Glenn Kasten288ed212012-04-25 17:52:27 -07004248 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004249 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004250
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004251 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004252 uint32_t s = cblk->server;
4253 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4254
4255 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4256 if (framesReq > framesReady) {
4257 framesReq = framesReady;
4258 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004259 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004260 framesReq = bufferEnd - s;
4261 }
4262
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004263 buffer->raw = getBuffer(s, framesReq);
4264 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004265
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004266 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004267 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004268 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004269
4270getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004271 buffer->raw = NULL;
4272 buffer->frameCount = 0;
4273 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4274 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004275}
4276
Glenn Kasten288ed212012-04-25 17:52:27 -07004277// Note that framesReady() takes a mutex on the control block using tryLock().
4278// This could result in priority inversion if framesReady() is called by the normal mixer,
4279// as the normal mixer thread runs at lower
4280// priority than the client's callback thread: there is a short window within framesReady()
4281// during which the normal mixer could be preempted, and the client callback would block.
4282// Another problem can occur if framesReady() is called by the fast mixer:
4283// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4284// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4285size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004286 return mCblk->framesReady();
4287}
4288
Glenn Kasten288ed212012-04-25 17:52:27 -07004289// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004290bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004291 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004292
John Grossman4ff14ba2012-02-08 16:37:41 -08004293 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004294 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4295 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004296 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004297 return true;
4298 }
4299 return false;
4300}
4301
Glenn Kasten3acbd052012-02-28 10:39:56 -08004302status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004303 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004304{
4305 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004306 ALOGV("start(%d), calling pid %d session %d",
4307 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004308
Mathias Agopian65ab4712010-07-14 17:59:35 -07004309 sp<ThreadBase> thread = mThread.promote();
4310 if (thread != 0) {
4311 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004312 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004313 // here the track could be either new, or restarted
4314 // in both cases "unstop" the track
4315 if (mState == PAUSED) {
4316 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004317 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004318 } else {
4319 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004320 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004321 }
4322
4323 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4324 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004325 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004326 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004327
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004328#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004329 // to track the speaker usage
4330 if (status == NO_ERROR) {
4331 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4332 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004333#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004334 }
4335 if (status == NO_ERROR) {
4336 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4337 playbackThread->addTrack_l(this);
4338 } else {
4339 mState = state;
4340 }
4341 } else {
4342 status = BAD_VALUE;
4343 }
4344 return status;
4345}
4346
4347void AudioFlinger::PlaybackThread::Track::stop()
4348{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004349 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004350 sp<ThreadBase> thread = mThread.promote();
4351 if (thread != 0) {
4352 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004353 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004354 if (mState > STOPPED) {
4355 mState = STOPPED;
4356 // If the track is not active (PAUSED and buffers full), flush buffers
4357 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4358 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4359 reset();
4360 }
Steve Block3856b092011-10-20 11:56:00 +01004361 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004362 }
4363 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4364 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004365 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004366 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004367
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004368#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004369 // to track the speaker usage
4370 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004371#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004372 }
4373 }
4374}
4375
4376void AudioFlinger::PlaybackThread::Track::pause()
4377{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004378 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004379 sp<ThreadBase> thread = mThread.promote();
4380 if (thread != 0) {
4381 Mutex::Autolock _l(thread->mLock);
4382 if (mState == ACTIVE || mState == RESUMING) {
4383 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004384 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004385 if (!isOutputTrack()) {
4386 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004387 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004388 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004389
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004390#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004391 // to track the speaker usage
4392 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004393#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004394 }
4395 }
4396 }
4397}
4398
4399void AudioFlinger::PlaybackThread::Track::flush()
4400{
Steve Block3856b092011-10-20 11:56:00 +01004401 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004402 sp<ThreadBase> thread = mThread.promote();
4403 if (thread != 0) {
4404 Mutex::Autolock _l(thread->mLock);
4405 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
4406 return;
4407 }
4408 // No point remaining in PAUSED state after a flush => go to
4409 // STOPPED state
4410 mState = STOPPED;
4411
Eric Laurent38ccae22011-03-28 18:37:07 -07004412 // do not reset the track if it is still in the process of being stopped or paused.
4413 // this will be done by prepareTracks_l() when the track is stopped.
4414 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4415 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4416 reset();
4417 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004418 }
4419}
4420
4421void AudioFlinger::PlaybackThread::Track::reset()
4422{
4423 // Do not reset twice to avoid discarding data written just after a flush and before
4424 // the audioflinger thread detects the track is stopped.
4425 if (!mResetDone) {
4426 TrackBase::reset();
4427 // Force underrun condition to avoid false underrun callback until first data is
4428 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004429 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4430 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004431 mFillingUpStatus = FS_FILLING;
4432 mResetDone = true;
Eric Laurenta011e352012-03-29 15:51:43 -07004433 mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004434 }
4435}
4436
4437void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4438{
4439 mMute = muted;
4440}
4441
Mathias Agopian65ab4712010-07-14 17:59:35 -07004442status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4443{
4444 status_t status = DEAD_OBJECT;
4445 sp<ThreadBase> thread = mThread.promote();
4446 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004447 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4448 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004449 }
4450 return status;
4451}
4452
4453void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4454{
4455 mAuxEffectId = EffectId;
4456 mAuxBuffer = buffer;
4457}
4458
Eric Laurenta011e352012-03-29 15:51:43 -07004459bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4460 size_t audioHalFrames)
4461{
4462 // a track is considered presented when the total number of frames written to audio HAL
4463 // corresponds to the number of frames written when presentationComplete() is called for the
4464 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4465 if (mPresentationCompleteFrames == 0) {
4466 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4467 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4468 mPresentationCompleteFrames, audioHalFrames);
4469 }
4470 if (framesWritten >= mPresentationCompleteFrames) {
4471 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4472 mSessionId, framesWritten);
4473 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
4474 mPresentationCompleteFrames = 0;
4475 return true;
4476 }
4477 return false;
4478}
4479
4480void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4481{
4482 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4483 if (mSyncEvents[i]->type() == type) {
4484 mSyncEvents[i]->trigger();
4485 mSyncEvents.removeAt(i);
4486 i--;
4487 }
4488 }
4489}
4490
Glenn Kasten58912562012-04-03 10:45:00 -07004491// implement VolumeBufferProvider interface
4492
4493uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4494{
4495 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4496 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4497 uint32_t vlr = mCblk->getVolumeLR();
4498 uint32_t vl = vlr & 0xFFFF;
4499 uint32_t vr = vlr >> 16;
4500 // track volumes come from shared memory, so can't be trusted and must be clamped
4501 if (vl > MAX_GAIN_INT) {
4502 vl = MAX_GAIN_INT;
4503 }
4504 if (vr > MAX_GAIN_INT) {
4505 vr = MAX_GAIN_INT;
4506 }
4507 // now apply the cached master volume and stream type volume;
4508 // this is trusted but lacks any synchronization or barrier so may be stale
4509 float v = mCachedVolume;
4510 vl *= v;
4511 vr *= v;
4512 // re-combine into U4.16
4513 vlr = (vr << 16) | (vl & 0xFFFF);
4514 // FIXME look at mute, pause, and stop flags
4515 return vlr;
4516}
Eric Laurenta011e352012-03-29 15:51:43 -07004517
John Grossman4ff14ba2012-02-08 16:37:41 -08004518// timed audio tracks
4519
4520sp<AudioFlinger::PlaybackThread::TimedTrack>
4521AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004522 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004523 const sp<Client>& client,
4524 audio_stream_type_t streamType,
4525 uint32_t sampleRate,
4526 audio_format_t format,
4527 uint32_t channelMask,
4528 int frameCount,
4529 const sp<IMemory>& sharedBuffer,
4530 int sessionId) {
4531 if (!client->reserveTimedTrack())
4532 return NULL;
4533
Glenn Kastena0356762012-03-19 10:38:51 -07004534 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004535 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4536 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004537}
4538
4539AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004540 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004541 const sp<Client>& client,
4542 audio_stream_type_t streamType,
4543 uint32_t sampleRate,
4544 audio_format_t format,
4545 uint32_t channelMask,
4546 int frameCount,
4547 const sp<IMemory>& sharedBuffer,
4548 int sessionId)
4549 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004550 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004551 mQueueHeadInFlight(false),
4552 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004553 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004554 mTimedSilenceBuffer(NULL),
4555 mTimedSilenceBufferSize(0),
4556 mTimedAudioOutputOnTime(false),
4557 mMediaTimeTransformValid(false)
4558{
4559 LocalClock lc;
4560 mLocalTimeFreq = lc.getLocalFreq();
4561
4562 mLocalTimeToSampleTransform.a_zero = 0;
4563 mLocalTimeToSampleTransform.b_zero = 0;
4564 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4565 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4566 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4567 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004568
4569 mMediaTimeToSampleTransform.a_zero = 0;
4570 mMediaTimeToSampleTransform.b_zero = 0;
4571 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4572 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4573 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4574 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004575}
4576
4577AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4578 mClient->releaseTimedTrack();
4579 delete [] mTimedSilenceBuffer;
4580}
4581
4582status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4583 size_t size, sp<IMemory>* buffer) {
4584
4585 Mutex::Autolock _l(mTimedBufferQueueLock);
4586
4587 trimTimedBufferQueue_l();
4588
4589 // lazily initialize the shared memory heap for timed buffers
4590 if (mTimedMemoryDealer == NULL) {
4591 const int kTimedBufferHeapSize = 512 << 10;
4592
4593 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4594 "AudioFlingerTimed");
4595 if (mTimedMemoryDealer == NULL)
4596 return NO_MEMORY;
4597 }
4598
4599 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4600 if (newBuffer == NULL) {
4601 newBuffer = mTimedMemoryDealer->allocate(size);
4602 if (newBuffer == NULL)
4603 return NO_MEMORY;
4604 }
4605
4606 *buffer = newBuffer;
4607 return NO_ERROR;
4608}
4609
4610// caller must hold mTimedBufferQueueLock
4611void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4612 int64_t mediaTimeNow;
4613 {
4614 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4615 if (!mMediaTimeTransformValid)
4616 return;
4617
4618 int64_t targetTimeNow;
4619 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4620 ? mCCHelper.getCommonTime(&targetTimeNow)
4621 : mCCHelper.getLocalTime(&targetTimeNow);
4622
4623 if (OK != res)
4624 return;
4625
4626 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4627 &mediaTimeNow)) {
4628 return;
4629 }
4630 }
4631
John Grossman1c345192012-03-27 14:00:17 -07004632 size_t trimEnd;
4633 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004634 int64_t bufEnd;
4635
John Grossmanc95cfbb2012-04-12 11:53:11 -07004636 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4637 // We have a next buffer. Just use its PTS as the PTS of the frame
4638 // following the last frame in this buffer. If the stream is sparse
4639 // (ie, there are deliberate gaps left in the stream which should be
4640 // filled with silence by the TimedAudioTrack), then this can result
4641 // in one extra buffer being left un-trimmed when it could have
4642 // been. In general, this is not typical, and we would rather
4643 // optimized away the TS calculation below for the more common case
4644 // where PTSes are contiguous.
4645 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4646 } else {
4647 // We have no next buffer. Compute the PTS of the frame following
4648 // the last frame in this buffer by computing the duration of of
4649 // this frame in media time units and adding it to the PTS of the
4650 // buffer.
4651 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4652 / mCblk->frameSize;
4653
4654 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4655 &bufEnd)) {
4656 ALOGE("Failed to convert frame count of %lld to media time"
4657 " duration" " (scale factor %d/%u) in %s",
4658 frameCount,
4659 mMediaTimeToSampleTransform.a_to_b_numer,
4660 mMediaTimeToSampleTransform.a_to_b_denom,
4661 __PRETTY_FUNCTION__);
4662 break;
4663 }
4664 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004665 }
John Grossman9fbdee12012-03-26 17:51:46 -07004666
4667 if (bufEnd > mediaTimeNow)
4668 break;
4669
4670 // Is the buffer we want to use in the middle of a mix operation right
4671 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4672 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004673 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004674 mTrimQueueHeadOnRelease = true;
4675 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004676 }
4677
John Grossman9fbdee12012-03-26 17:51:46 -07004678 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004679 if (trimStart < trimEnd) {
4680 // Update the bookkeeping for framesReady()
4681 for (size_t i = trimStart; i < trimEnd; ++i) {
4682 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4683 }
4684
4685 // Now actually remove the buffers from the queue.
4686 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004687 }
4688}
4689
John Grossman1c345192012-03-27 14:00:17 -07004690void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4691 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004692 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4693 "%s called (reason \"%s\"), but timed buffer queue has no"
4694 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004695
4696 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4697 mTimedBufferQueue.removeAt(0);
4698}
4699
4700void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4701 const TimedBuffer& buf,
4702 const char* logTag) {
4703 uint32_t bufBytes = buf.buffer()->size();
4704 uint32_t consumedAlready = buf.position();
4705
Eric Laurentb388e532012-04-14 13:32:48 -07004706 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004707 "Bad bookkeeping while updating frames pending. Timed buffer is"
4708 " only %u bytes long, but claims to have consumed %u"
4709 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004710 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004711
4712 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004713 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4714 "Bad bookkeeping while updating frames pending. Should have at"
4715 " least %u queued frames, but we think we have only %u. (update"
4716 " reason: \"%s\")",
4717 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004718
4719 mFramesPendingInQueue -= bufFrames;
4720}
4721
John Grossman4ff14ba2012-02-08 16:37:41 -08004722status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4723 const sp<IMemory>& buffer, int64_t pts) {
4724
4725 {
4726 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4727 if (!mMediaTimeTransformValid)
4728 return INVALID_OPERATION;
4729 }
4730
4731 Mutex::Autolock _l(mTimedBufferQueueLock);
4732
John Grossman1c345192012-03-27 14:00:17 -07004733 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4734 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004735 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4736
4737 return NO_ERROR;
4738}
4739
4740status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4741 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4742
John Grossman1c345192012-03-27 14:00:17 -07004743 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4744 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4745 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004746
4747 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4748 target == TimedAudioTrack::COMMON_TIME)) {
4749 return BAD_VALUE;
4750 }
4751
4752 Mutex::Autolock lock(mMediaTimeTransformLock);
4753 mMediaTimeTransform = xform;
4754 mMediaTimeTransformTarget = target;
4755 mMediaTimeTransformValid = true;
4756
4757 return NO_ERROR;
4758}
4759
4760#define min(a, b) ((a) < (b) ? (a) : (b))
4761
4762// implementation of getNextBuffer for tracks whose buffers have timestamps
4763status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4764 AudioBufferProvider::Buffer* buffer, int64_t pts)
4765{
4766 if (pts == AudioBufferProvider::kInvalidPTS) {
4767 buffer->raw = 0;
4768 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07004769 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004770 return INVALID_OPERATION;
4771 }
4772
John Grossman4ff14ba2012-02-08 16:37:41 -08004773 Mutex::Autolock _l(mTimedBufferQueueLock);
4774
John Grossman9fbdee12012-03-26 17:51:46 -07004775 ALOG_ASSERT(!mQueueHeadInFlight,
4776 "getNextBuffer called without releaseBuffer!");
4777
John Grossman4ff14ba2012-02-08 16:37:41 -08004778 while (true) {
4779
4780 // if we have no timed buffers, then fail
4781 if (mTimedBufferQueue.isEmpty()) {
4782 buffer->raw = 0;
4783 buffer->frameCount = 0;
4784 return NOT_ENOUGH_DATA;
4785 }
4786
4787 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4788
4789 // calculate the PTS of the head of the timed buffer queue expressed in
4790 // local time
4791 int64_t headLocalPTS;
4792 {
4793 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4794
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004795 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004796
4797 if (mMediaTimeTransform.a_to_b_denom == 0) {
4798 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07004799 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004800 return NO_ERROR;
4801 }
4802
4803 int64_t transformedPTS;
4804 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4805 &transformedPTS)) {
4806 // the transform failed. this shouldn't happen, but if it does
4807 // then just drop this buffer
4808 ALOGW("timedGetNextBuffer transform failed");
4809 buffer->raw = 0;
4810 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07004811 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08004812 return NO_ERROR;
4813 }
4814
4815 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4816 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4817 &headLocalPTS)) {
4818 buffer->raw = 0;
4819 buffer->frameCount = 0;
4820 return INVALID_OPERATION;
4821 }
4822 } else {
4823 headLocalPTS = transformedPTS;
4824 }
4825 }
4826
4827 // adjust the head buffer's PTS to reflect the portion of the head buffer
4828 // that has already been consumed
4829 int64_t effectivePTS = headLocalPTS +
4830 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4831
4832 // Calculate the delta in samples between the head of the input buffer
4833 // queue and the start of the next output buffer that will be written.
4834 // If the transformation fails because of over or underflow, it means
4835 // that the sample's position in the output stream is so far out of
4836 // whack that it should just be dropped.
4837 int64_t sampleDelta;
4838 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4839 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004840 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
4841 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08004842 continue;
4843 }
4844 if (!mLocalTimeToSampleTransform.doForwardTransform(
4845 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07004846 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004847 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08004848 continue;
4849 }
4850
John Grossman1c345192012-03-27 14:00:17 -07004851 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
4852 " sampleDelta=[%d.%08x]",
4853 head.pts(), head.position(), pts,
4854 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
4855 + (sampleDelta >> 32)),
4856 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08004857
4858 // if the delta between the ideal placement for the next input sample and
4859 // the current output position is within this threshold, then we will
4860 // concatenate the next input samples to the previous output
4861 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07004862 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08004863
4864 // if this is the first buffer of audio that we're emitting from this track
4865 // then it should be almost exactly on time.
4866 const int64_t kSampleStartupThreshold = 1LL << 32;
4867
4868 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07004869 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004870 // the next input is close enough to being on time, so concatenate it
4871 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07004872 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004873
John Grossman1c345192012-03-27 14:00:17 -07004874 ALOGVV("*** on time: head.pos=%d frameCount=%u",
4875 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08004876 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07004877 }
4878
4879 // Looks like our output is not on time. Reset our on timed status.
4880 // Next time we mix samples from our input queue, then should be within
4881 // the StartupThreshold.
4882 mTimedAudioOutputOnTime = false;
4883 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004884 // the gap between the current output position and the proper start of
4885 // the next input sample is too big, so fill it with silence
4886 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4887
John Grossman9fbdee12012-03-26 17:51:46 -07004888 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004889 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4890 return NO_ERROR;
4891 } else {
4892 // the next input sample is late
4893 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4894 size_t onTimeSamplePosition =
4895 head.position() + lateFrames * mCblk->frameSize;
4896
4897 if (onTimeSamplePosition > head.buffer()->size()) {
4898 // all the remaining samples in the head are too late, so
4899 // drop it and move on
4900 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004901 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08004902 continue;
4903 } else {
4904 // skip over the late samples
4905 head.setPosition(onTimeSamplePosition);
4906
4907 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07004908 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004909
4910 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4911 return NO_ERROR;
4912 }
4913 }
4914 }
4915}
4916
4917// Yield samples from the timed buffer queue head up to the given output
4918// buffer's capacity.
4919//
4920// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004921void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004922 AudioBufferProvider::Buffer* buffer) {
4923
4924 const TimedBuffer& head = mTimedBufferQueue[0];
4925
4926 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4927 head.position());
4928
4929 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4930 mCblk->frameSize);
4931 size_t framesRequested = buffer->frameCount;
4932 buffer->frameCount = min(framesLeftInHead, framesRequested);
4933
John Grossman9fbdee12012-03-26 17:51:46 -07004934 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08004935 mTimedAudioOutputOnTime = true;
4936}
4937
4938// Yield samples of silence up to the given output buffer's capacity
4939//
4940// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07004941void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08004942 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4943
4944 // lazily allocate a buffer filled with silence
4945 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4946 delete [] mTimedSilenceBuffer;
4947 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4948 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4949 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4950 }
4951
4952 buffer->raw = mTimedSilenceBuffer;
4953 size_t framesRequested = buffer->frameCount;
4954 buffer->frameCount = min(numFrames, framesRequested);
4955
4956 mTimedAudioOutputOnTime = false;
4957}
4958
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004959// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004960void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4961 AudioBufferProvider::Buffer* buffer) {
4962
4963 Mutex::Autolock _l(mTimedBufferQueueLock);
4964
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004965 // If the buffer which was just released is part of the buffer at the head
4966 // of the queue, be sure to update the amt of the buffer which has been
4967 // consumed. If the buffer being returned is not part of the head of the
4968 // queue, its either because the buffer is part of the silence buffer, or
4969 // because the head of the timed queue was trimmed after the mixer called
4970 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07004971 if (buffer->raw == mTimedSilenceBuffer) {
4972 ALOG_ASSERT(!mQueueHeadInFlight,
4973 "Queue head in flight during release of silence buffer!");
4974 goto done;
4975 }
4976
4977 ALOG_ASSERT(mQueueHeadInFlight,
4978 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
4979 " head in flight.");
4980
4981 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004982 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004983
4984 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07004985 void* end = reinterpret_cast<void*>(
4986 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
4987 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08004988
John Grossman9fbdee12012-03-26 17:51:46 -07004989 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
4990 "released buffer not within the head of the timed buffer"
4991 " queue; qHead = [%p, %p], released buffer = %p",
4992 start, end, buffer->raw);
4993
4994 head.setPosition(head.position() +
4995 (buffer->frameCount * mCblk->frameSize));
4996 mQueueHeadInFlight = false;
4997
John Grossman1c345192012-03-27 14:00:17 -07004998 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
4999 "Bad bookkeeping during releaseBuffer! Should have at"
5000 " least %u queued frames, but we think we have only %u",
5001 buffer->frameCount, mFramesPendingInQueue);
5002
5003 mFramesPendingInQueue -= buffer->frameCount;
5004
John Grossman9fbdee12012-03-26 17:51:46 -07005005 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5006 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005007 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005008 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005009 }
John Grossman9fbdee12012-03-26 17:51:46 -07005010 } else {
5011 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5012 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005013 }
5014
John Grossman9fbdee12012-03-26 17:51:46 -07005015done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005016 buffer->raw = 0;
5017 buffer->frameCount = 0;
5018}
5019
Glenn Kasten288ed212012-04-25 17:52:27 -07005020size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005021 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005022 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005023}
5024
5025AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5026 : mPTS(0), mPosition(0) {}
5027
5028AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5029 const sp<IMemory>& buffer, int64_t pts)
5030 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5031
Mathias Agopian65ab4712010-07-14 17:59:35 -07005032// ----------------------------------------------------------------------------
5033
5034// RecordTrack constructor must be called with AudioFlinger::mLock held
5035AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005036 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005037 const sp<Client>& client,
5038 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005039 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005040 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005041 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005042 int sessionId)
5043 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005044 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005045 mOverflow(false)
5046{
5047 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005048 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5049 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5050 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5051 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5052 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5053 } else {
5054 mCblk->frameSize = sizeof(int8_t);
5055 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005056 }
5057}
5058
5059AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5060{
5061 sp<ThreadBase> thread = mThread.promote();
5062 if (thread != 0) {
5063 AudioSystem::releaseInput(thread->id());
5064 }
5065}
5066
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005067// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005068status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005069{
5070 audio_track_cblk_t* cblk = this->cblk();
5071 uint32_t framesAvail;
5072 uint32_t framesReq = buffer->frameCount;
5073
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005074 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005075 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005076 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005077 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005078 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005079 }
5080
5081 framesAvail = cblk->framesAvailable_l();
5082
Glenn Kastenf6b16782011-12-15 09:51:17 -08005083 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005084 uint32_t s = cblk->server;
5085 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5086
5087 if (framesReq > framesAvail) {
5088 framesReq = framesAvail;
5089 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005090 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005091 framesReq = bufferEnd - s;
5092 }
5093
5094 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08005095 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005096
5097 buffer->frameCount = framesReq;
5098 return NO_ERROR;
5099 }
5100
5101getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005102 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005103 buffer->frameCount = 0;
5104 return NOT_ENOUGH_DATA;
5105}
5106
Glenn Kasten3acbd052012-02-28 10:39:56 -08005107status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005108 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005109{
5110 sp<ThreadBase> thread = mThread.promote();
5111 if (thread != 0) {
5112 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005113 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005114 } else {
5115 return BAD_VALUE;
5116 }
5117}
5118
5119void AudioFlinger::RecordThread::RecordTrack::stop()
5120{
5121 sp<ThreadBase> thread = mThread.promote();
5122 if (thread != 0) {
5123 RecordThread *recordThread = (RecordThread *)thread.get();
5124 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005125 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005126 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005127 // read from buffer
5128 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005129 }
5130}
5131
5132void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5133{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005134 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005135 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005136 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005137 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005138 mSessionId,
5139 mFrameCount,
5140 mState,
5141 mCblk->sampleRate,
5142 mCblk->server,
5143 mCblk->user);
5144}
5145
5146
5147// ----------------------------------------------------------------------------
5148
5149AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005150 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005151 DuplicatingThread *sourceThread,
5152 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005153 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005154 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005155 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005156 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5157 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005158 mActive(false), mSourceThread(sourceThread)
5159{
5160
Mathias Agopian65ab4712010-07-14 17:59:35 -07005161 if (mCblk != NULL) {
5162 mCblk->flags |= CBLK_DIRECTION_OUT;
5163 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005164 mOutBuffer.frameCount = 0;
5165 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005166 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005167 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5168 mCblk, mBuffer, mCblk->buffers,
5169 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005170 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005171 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005172 }
5173}
5174
5175AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5176{
5177 clearBufferQueue();
5178}
5179
Glenn Kasten3acbd052012-02-28 10:39:56 -08005180status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005181 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005182{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005183 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005184 if (status != NO_ERROR) {
5185 return status;
5186 }
5187
5188 mActive = true;
5189 mRetryCount = 127;
5190 return status;
5191}
5192
5193void AudioFlinger::PlaybackThread::OutputTrack::stop()
5194{
5195 Track::stop();
5196 clearBufferQueue();
5197 mOutBuffer.frameCount = 0;
5198 mActive = false;
5199}
5200
5201bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5202{
5203 Buffer *pInBuffer;
5204 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005205 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005206 bool outputBufferFull = false;
5207 inBuffer.frameCount = frames;
5208 inBuffer.i16 = data;
5209
5210 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5211
5212 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005213 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005214 sp<ThreadBase> thread = mThread.promote();
5215 if (thread != 0) {
5216 MixerThread *mixerThread = (MixerThread *)thread.get();
5217 if (mCblk->frameCount > frames){
5218 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5219 uint32_t startFrames = (mCblk->frameCount - frames);
5220 pInBuffer = new Buffer;
5221 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5222 pInBuffer->frameCount = startFrames;
5223 pInBuffer->i16 = pInBuffer->mBuffer;
5224 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5225 mBufferQueue.add(pInBuffer);
5226 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005227 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005228 }
5229 }
5230 }
5231 }
5232
5233 while (waitTimeLeftMs) {
5234 // First write pending buffers, then new data
5235 if (mBufferQueue.size()) {
5236 pInBuffer = mBufferQueue.itemAt(0);
5237 } else {
5238 pInBuffer = &inBuffer;
5239 }
5240
5241 if (pInBuffer->frameCount == 0) {
5242 break;
5243 }
5244
5245 if (mOutBuffer.frameCount == 0) {
5246 mOutBuffer.frameCount = pInBuffer->frameCount;
5247 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005248 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005249 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005250 outputBufferFull = true;
5251 break;
5252 }
5253 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5254 if (waitTimeLeftMs >= waitTimeMs) {
5255 waitTimeLeftMs -= waitTimeMs;
5256 } else {
5257 waitTimeLeftMs = 0;
5258 }
5259 }
5260
5261 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5262 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5263 mCblk->stepUser(outFrames);
5264 pInBuffer->frameCount -= outFrames;
5265 pInBuffer->i16 += outFrames * channelCount;
5266 mOutBuffer.frameCount -= outFrames;
5267 mOutBuffer.i16 += outFrames * channelCount;
5268
5269 if (pInBuffer->frameCount == 0) {
5270 if (mBufferQueue.size()) {
5271 mBufferQueue.removeAt(0);
5272 delete [] pInBuffer->mBuffer;
5273 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005274 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005275 } else {
5276 break;
5277 }
5278 }
5279 }
5280
5281 // If we could not write all frames, allocate a buffer and queue it for next time.
5282 if (inBuffer.frameCount) {
5283 sp<ThreadBase> thread = mThread.promote();
5284 if (thread != 0 && !thread->standby()) {
5285 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5286 pInBuffer = new Buffer;
5287 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5288 pInBuffer->frameCount = inBuffer.frameCount;
5289 pInBuffer->i16 = pInBuffer->mBuffer;
5290 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5291 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005292 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005293 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005294 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005295 }
5296 }
5297 }
5298
5299 // Calling write() with a 0 length buffer, means that no more data will be written:
5300 // If no more buffers are pending, fill output track buffer to make sure it is started
5301 // by output mixer.
5302 if (frames == 0 && mBufferQueue.size() == 0) {
5303 if (mCblk->user < mCblk->frameCount) {
5304 frames = mCblk->frameCount - mCblk->user;
5305 pInBuffer = new Buffer;
5306 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5307 pInBuffer->frameCount = frames;
5308 pInBuffer->i16 = pInBuffer->mBuffer;
5309 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5310 mBufferQueue.add(pInBuffer);
5311 } else if (mActive) {
5312 stop();
5313 }
5314 }
5315
5316 return outputBufferFull;
5317}
5318
5319status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5320{
5321 int active;
5322 status_t result;
5323 audio_track_cblk_t* cblk = mCblk;
5324 uint32_t framesReq = buffer->frameCount;
5325
Steve Block3856b092011-10-20 11:56:00 +01005326// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005327 buffer->frameCount = 0;
5328
5329 uint32_t framesAvail = cblk->framesAvailable();
5330
5331
5332 if (framesAvail == 0) {
5333 Mutex::Autolock _l(cblk->lock);
5334 goto start_loop_here;
5335 while (framesAvail == 0) {
5336 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005337 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005338 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005339 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005340 }
5341 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5342 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005343 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005344 }
5345 // read the server count again
5346 start_loop_here:
5347 framesAvail = cblk->framesAvailable_l();
5348 }
5349 }
5350
5351// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005352// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005353// }
5354
5355 if (framesReq > framesAvail) {
5356 framesReq = framesAvail;
5357 }
5358
5359 uint32_t u = cblk->user;
5360 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5361
Marco Nelissena1472d92012-03-30 14:36:54 -07005362 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005363 framesReq = bufferEnd - u;
5364 }
5365
5366 buffer->frameCount = framesReq;
5367 buffer->raw = (void *)cblk->buffer(u);
5368 return NO_ERROR;
5369}
5370
5371
5372void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5373{
5374 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005375
5376 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005377 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005378 delete [] pBuffer->mBuffer;
5379 delete pBuffer;
5380 }
5381 mBufferQueue.clear();
5382}
5383
5384// ----------------------------------------------------------------------------
5385
5386AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5387 : RefBase(),
5388 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005389 // 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 -07005390 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005391 mPid(pid),
5392 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005393{
5394 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5395}
5396
5397// Client destructor must be called with AudioFlinger::mLock held
5398AudioFlinger::Client::~Client()
5399{
5400 mAudioFlinger->removeClient_l(mPid);
5401}
5402
Glenn Kasten435dbe62012-01-30 10:15:48 -08005403sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005404{
5405 return mMemoryDealer;
5406}
5407
John Grossman4ff14ba2012-02-08 16:37:41 -08005408// Reserve one of the limited slots for a timed audio track associated
5409// with this client
5410bool AudioFlinger::Client::reserveTimedTrack()
5411{
5412 const int kMaxTimedTracksPerClient = 4;
5413
5414 Mutex::Autolock _l(mTimedTrackLock);
5415
5416 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5417 ALOGW("can not create timed track - pid %d has exceeded the limit",
5418 mPid);
5419 return false;
5420 }
5421
5422 mTimedTrackCount++;
5423 return true;
5424}
5425
5426// Release a slot for a timed audio track
5427void AudioFlinger::Client::releaseTimedTrack()
5428{
5429 Mutex::Autolock _l(mTimedTrackLock);
5430 mTimedTrackCount--;
5431}
5432
Mathias Agopian65ab4712010-07-14 17:59:35 -07005433// ----------------------------------------------------------------------------
5434
5435AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5436 const sp<IAudioFlingerClient>& client,
5437 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005438 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005439{
5440}
5441
5442AudioFlinger::NotificationClient::~NotificationClient()
5443{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005444}
5445
5446void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5447{
5448 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005449 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005450}
5451
5452// ----------------------------------------------------------------------------
5453
5454AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5455 : BnAudioTrack(),
5456 mTrack(track)
5457{
5458}
5459
5460AudioFlinger::TrackHandle::~TrackHandle() {
5461 // just stop the track on deletion, associated resources
5462 // will be freed from the main thread once all pending buffers have
5463 // been played. Unless it's not in the active track list, in which
5464 // case we free everything now...
5465 mTrack->destroy();
5466}
5467
Glenn Kasten90716c52012-01-26 13:40:12 -08005468sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5469 return mTrack->getCblk();
5470}
5471
Glenn Kasten3acbd052012-02-28 10:39:56 -08005472status_t AudioFlinger::TrackHandle::start() {
5473 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005474}
5475
5476void AudioFlinger::TrackHandle::stop() {
5477 mTrack->stop();
5478}
5479
5480void AudioFlinger::TrackHandle::flush() {
5481 mTrack->flush();
5482}
5483
5484void AudioFlinger::TrackHandle::mute(bool e) {
5485 mTrack->mute(e);
5486}
5487
5488void AudioFlinger::TrackHandle::pause() {
5489 mTrack->pause();
5490}
5491
Mathias Agopian65ab4712010-07-14 17:59:35 -07005492status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5493{
5494 return mTrack->attachAuxEffect(EffectId);
5495}
5496
John Grossman4ff14ba2012-02-08 16:37:41 -08005497status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5498 sp<IMemory>* buffer) {
5499 if (!mTrack->isTimedTrack())
5500 return INVALID_OPERATION;
5501
5502 PlaybackThread::TimedTrack* tt =
5503 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5504 return tt->allocateTimedBuffer(size, buffer);
5505}
5506
5507status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5508 int64_t pts) {
5509 if (!mTrack->isTimedTrack())
5510 return INVALID_OPERATION;
5511
5512 PlaybackThread::TimedTrack* tt =
5513 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5514 return tt->queueTimedBuffer(buffer, pts);
5515}
5516
5517status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5518 const LinearTransform& xform, int target) {
5519
5520 if (!mTrack->isTimedTrack())
5521 return INVALID_OPERATION;
5522
5523 PlaybackThread::TimedTrack* tt =
5524 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5525 return tt->setMediaTimeTransform(
5526 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5527}
5528
Mathias Agopian65ab4712010-07-14 17:59:35 -07005529status_t AudioFlinger::TrackHandle::onTransact(
5530 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5531{
5532 return BnAudioTrack::onTransact(code, data, reply, flags);
5533}
5534
5535// ----------------------------------------------------------------------------
5536
5537sp<IAudioRecord> AudioFlinger::openRecord(
5538 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005539 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005540 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005541 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005542 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005543 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005544 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005545 int *sessionId,
5546 status_t *status)
5547{
5548 sp<RecordThread::RecordTrack> recordTrack;
5549 sp<RecordHandle> recordHandle;
5550 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005551 status_t lStatus;
5552 RecordThread *thread;
5553 size_t inFrameCount;
5554 int lSessionId;
5555
5556 // check calling permissions
5557 if (!recordingAllowed()) {
5558 lStatus = PERMISSION_DENIED;
5559 goto Exit;
5560 }
5561
5562 // add client to list
5563 { // scope for mLock
5564 Mutex::Autolock _l(mLock);
5565 thread = checkRecordThread_l(input);
5566 if (thread == NULL) {
5567 lStatus = BAD_VALUE;
5568 goto Exit;
5569 }
5570
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005571 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005572
5573 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005574 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005575 lSessionId = *sessionId;
5576 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005577 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005578 if (sessionId != NULL) {
5579 *sessionId = lSessionId;
5580 }
5581 }
5582 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005583 recordTrack = thread->createRecordTrack_l(client,
5584 sampleRate,
5585 format,
5586 channelMask,
5587 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005588 lSessionId,
5589 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005590 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005591 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005592 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5593 // destructor is called by the TrackBase destructor with mLock held
5594 client.clear();
5595 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005596 goto Exit;
5597 }
5598
5599 // return to handle to client
5600 recordHandle = new RecordHandle(recordTrack);
5601 lStatus = NO_ERROR;
5602
5603Exit:
5604 if (status) {
5605 *status = lStatus;
5606 }
5607 return recordHandle;
5608}
5609
5610// ----------------------------------------------------------------------------
5611
5612AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5613 : BnAudioRecord(),
5614 mRecordTrack(recordTrack)
5615{
5616}
5617
5618AudioFlinger::RecordHandle::~RecordHandle() {
5619 stop();
5620}
5621
Glenn Kasten90716c52012-01-26 13:40:12 -08005622sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5623 return mRecordTrack->getCblk();
5624}
5625
Glenn Kasten3acbd052012-02-28 10:39:56 -08005626status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005627 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005628 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005629}
5630
5631void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005632 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005633 mRecordTrack->stop();
5634}
5635
Mathias Agopian65ab4712010-07-14 17:59:35 -07005636status_t AudioFlinger::RecordHandle::onTransact(
5637 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5638{
5639 return BnAudioRecord::onTransact(code, data, reply, flags);
5640}
5641
5642// ----------------------------------------------------------------------------
5643
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005644AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5645 AudioStreamIn *input,
5646 uint32_t sampleRate,
5647 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005648 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005649 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005650 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005651 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5652 // mRsmpInIndex and mInputBytes set by readInputParameters()
5653 mReqChannelCount(popcount(channels)),
5654 mReqSampleRate(sampleRate)
5655 // mBytesRead is only meaningful while active, and so is cleared in start()
5656 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005657{
Glenn Kasten480b4682012-02-28 12:30:08 -08005658 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005659
Mathias Agopian65ab4712010-07-14 17:59:35 -07005660 readInputParameters();
5661}
5662
5663
5664AudioFlinger::RecordThread::~RecordThread()
5665{
5666 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005667 delete mResampler;
5668 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005669}
5670
5671void AudioFlinger::RecordThread::onFirstRef()
5672{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005673 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005674}
5675
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005676status_t AudioFlinger::RecordThread::readyToRun()
5677{
5678 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005679 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005680 return status;
5681}
5682
Mathias Agopian65ab4712010-07-14 17:59:35 -07005683bool AudioFlinger::RecordThread::threadLoop()
5684{
5685 AudioBufferProvider::Buffer buffer;
5686 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005687 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005688
Eric Laurent44d98482010-09-30 16:12:31 -07005689 nsecs_t lastWarning = 0;
5690
Eric Laurentfeb0db62011-07-22 09:04:31 -07005691 acquireWakeLock();
5692
Mathias Agopian65ab4712010-07-14 17:59:35 -07005693 // start recording
5694 while (!exitPending()) {
5695
5696 processConfigEvents();
5697
5698 { // scope for mLock
5699 Mutex::Autolock _l(mLock);
5700 checkForNewParameters_l();
5701 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5702 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005703 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704 mStandby = true;
5705 }
5706
5707 if (exitPending()) break;
5708
Eric Laurentfeb0db62011-07-22 09:04:31 -07005709 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005710 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005711 // go to sleep
5712 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005713 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005714 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005715 continue;
5716 }
5717 if (mActiveTrack != 0) {
5718 if (mActiveTrack->mState == TrackBase::PAUSING) {
5719 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005720 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005721 mStandby = true;
5722 }
5723 mActiveTrack.clear();
5724 mStartStopCond.broadcast();
5725 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5726 if (mReqChannelCount != mActiveTrack->channelCount()) {
5727 mActiveTrack.clear();
5728 mStartStopCond.broadcast();
5729 } else if (mBytesRead != 0) {
5730 // record start succeeds only if first read from audio input
5731 // succeeds
5732 if (mBytesRead > 0) {
5733 mActiveTrack->mState = TrackBase::ACTIVE;
5734 } else {
5735 mActiveTrack.clear();
5736 }
5737 mStartStopCond.broadcast();
5738 }
5739 mStandby = false;
5740 }
5741 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005742 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005743 }
5744
5745 if (mActiveTrack != 0) {
5746 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5747 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005748 unlockEffectChains(effectChains);
5749 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005750 continue;
5751 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005752 for (size_t i = 0; i < effectChains.size(); i ++) {
5753 effectChains[i]->process_l();
5754 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005755
Mathias Agopian65ab4712010-07-14 17:59:35 -07005756 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005757 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005758 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08005759 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005760 // no resampling
5761 while (framesOut) {
5762 size_t framesIn = mFrameCount - mRsmpInIndex;
5763 if (framesIn) {
5764 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5765 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5766 if (framesIn > framesOut)
5767 framesIn = framesOut;
5768 mRsmpInIndex += framesIn;
5769 framesOut -= framesIn;
5770 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07005771 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005772 memcpy(dst, src, framesIn * mFrameSize);
5773 } else {
5774 int16_t *src16 = (int16_t *)src;
5775 int16_t *dst16 = (int16_t *)dst;
5776 if (mChannelCount == 1) {
5777 while (framesIn--) {
5778 *dst16++ = *src16;
5779 *dst16++ = *src16++;
5780 }
5781 } else {
5782 while (framesIn--) {
5783 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5784 src16 += 2;
5785 }
5786 }
5787 }
5788 }
5789 if (framesOut && mFrameCount == mRsmpInIndex) {
5790 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005791 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005792 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005793 framesOut = 0;
5794 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005795 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005796 mRsmpInIndex = 0;
5797 }
5798 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005799 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005800 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5801 // Force input into standby so that it tries to
5802 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005803 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005804 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005805 }
5806 mRsmpInIndex = mFrameCount;
5807 framesOut = 0;
5808 buffer.frameCount = 0;
5809 }
5810 }
5811 }
5812 } else {
5813 // resampling
5814
5815 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5816 // alter output frame count as if we were expecting stereo samples
5817 if (mChannelCount == 1 && mReqChannelCount == 1) {
5818 framesOut >>= 1;
5819 }
5820 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5821 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5822 // are 32 bit aligned which should be always true.
5823 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005824 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005825 // the resampler always outputs stereo samples: do post stereo to mono conversion
5826 int16_t *src = (int16_t *)mRsmpOutBuffer;
5827 int16_t *dst = buffer.i16;
5828 while (framesOut--) {
5829 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5830 src += 2;
5831 }
5832 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005833 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005834 }
5835
5836 }
Eric Laurenta011e352012-03-29 15:51:43 -07005837 if (mFramestoDrop == 0) {
5838 mActiveTrack->releaseBuffer(&buffer);
5839 } else {
5840 if (mFramestoDrop > 0) {
5841 mFramestoDrop -= buffer.frameCount;
5842 if (mFramestoDrop < 0) {
5843 mFramestoDrop = 0;
5844 }
5845 }
5846 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005847 mActiveTrack->overflow();
5848 }
5849 // client isn't retrieving buffers fast enough
5850 else {
Eric Laurent44d98482010-09-30 16:12:31 -07005851 if (!mActiveTrack->setOverflow()) {
5852 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08005853 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005854 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07005855 lastWarning = now;
5856 }
5857 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005858 // Release the processor for a while before asking for a new buffer.
5859 // This will give the application more chance to read from the buffer and
5860 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005861 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005862 }
5863 }
Eric Laurentec437d82011-07-26 20:54:46 -07005864 // enable changes in effect chain
5865 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005866 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005867 }
5868
5869 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005870 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005871 }
5872 mActiveTrack.clear();
5873
5874 mStartStopCond.broadcast();
5875
Eric Laurentfeb0db62011-07-22 09:04:31 -07005876 releaseWakeLock();
5877
Steve Block3856b092011-10-20 11:56:00 +01005878 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005879 return false;
5880}
5881
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005882
5883sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5884 const sp<AudioFlinger::Client>& client,
5885 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005886 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005887 int channelMask,
5888 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005889 int sessionId,
5890 status_t *status)
5891{
5892 sp<RecordTrack> track;
5893 status_t lStatus;
5894
5895 lStatus = initCheck();
5896 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005897 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005898 goto Exit;
5899 }
5900
5901 { // scope for mLock
5902 Mutex::Autolock _l(mLock);
5903
5904 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005905 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005906
Glenn Kasten7378ca52012-01-20 13:44:40 -08005907 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005908 lStatus = NO_MEMORY;
5909 goto Exit;
5910 }
5911
5912 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005913 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5914 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005915 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005916 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5917 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005918 }
5919 lStatus = NO_ERROR;
5920
5921Exit:
5922 if (status) {
5923 *status = lStatus;
5924 }
5925 return track;
5926}
5927
Eric Laurenta011e352012-03-29 15:51:43 -07005928status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08005929 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005930 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005931{
Glenn Kasten58912562012-04-03 10:45:00 -07005932 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005933 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005934 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07005935
5936 if (event == AudioSystem::SYNC_EVENT_NONE) {
5937 mSyncStartEvent.clear();
5938 mFramestoDrop = 0;
5939 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
5940 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
5941 triggerSession,
5942 recordTrack->sessionId(),
5943 syncStartEventCallback,
5944 this);
5945 mFramestoDrop = -1;
5946 }
5947
Mathias Agopian65ab4712010-07-14 17:59:35 -07005948 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08005949 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005950 if (mActiveTrack != 0) {
5951 if (recordTrack != mActiveTrack.get()) {
5952 status = -EBUSY;
5953 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5954 mActiveTrack->mState = TrackBase::ACTIVE;
5955 }
5956 return status;
5957 }
5958
5959 recordTrack->mState = TrackBase::IDLE;
5960 mActiveTrack = recordTrack;
5961 mLock.unlock();
5962 status_t status = AudioSystem::startInput(mId);
5963 mLock.lock();
5964 if (status != NO_ERROR) {
5965 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07005966 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005967 return status;
5968 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005969 mRsmpInIndex = mFrameCount;
5970 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005971 if (mResampler != NULL) {
5972 mResampler->reset();
5973 }
5974 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005975 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01005976 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005977 mWaitWorkCV.signal();
5978 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08005979 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005980 mActiveTrack.clear();
5981 status = INVALID_OPERATION;
5982 goto startError;
5983 }
5984 mStartStopCond.wait(mLock);
5985 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01005986 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005987 status = BAD_VALUE;
5988 goto startError;
5989 }
Steve Block3856b092011-10-20 11:56:00 +01005990 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005991 return status;
5992 }
5993startError:
5994 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07005995 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005996 return status;
5997}
5998
Eric Laurenta011e352012-03-29 15:51:43 -07005999void AudioFlinger::RecordThread::clearSyncStartEvent()
6000{
6001 if (mSyncStartEvent != 0) {
6002 mSyncStartEvent->cancel();
6003 }
6004 mSyncStartEvent.clear();
6005}
6006
6007void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6008{
6009 sp<SyncEvent> strongEvent = event.promote();
6010
6011 if (strongEvent != 0) {
6012 RecordThread *me = (RecordThread *)strongEvent->cookie();
6013 me->handleSyncStartEvent(strongEvent);
6014 }
6015}
6016
6017void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6018{
6019 ALOGV("handleSyncStartEvent() mActiveTrack %p session %d event->listenerSession() %d",
6020 mActiveTrack.get(),
6021 mActiveTrack.get() ? mActiveTrack->sessionId() : 0,
6022 event->listenerSession());
6023
6024 if (mActiveTrack != 0 &&
6025 event == mSyncStartEvent) {
6026 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6027 // from audio HAL
6028 mFramestoDrop = mFrameCount * 2;
6029 mSyncStartEvent.clear();
6030 }
6031}
6032
Mathias Agopian65ab4712010-07-14 17:59:35 -07006033void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006034 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006035 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006036 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006037 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006038 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6039 mActiveTrack->mState = TrackBase::PAUSING;
6040 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006041 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006042 return;
6043 }
6044 mStartStopCond.wait(mLock);
6045 // if we have been restarted, recordTrack == mActiveTrack.get() here
6046 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6047 mLock.unlock();
6048 AudioSystem::stopInput(mId);
6049 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006050 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006051 }
6052 }
6053 }
6054}
6055
Eric Laurenta011e352012-03-29 15:51:43 -07006056bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6057{
6058 return false;
6059}
6060
6061status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6062{
6063 if (!isValidSyncEvent(event)) {
6064 return BAD_VALUE;
6065 }
6066
6067 Mutex::Autolock _l(mLock);
6068
6069 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6070 mTrack->setSyncEvent(event);
6071 return NO_ERROR;
6072 }
6073 return NAME_NOT_FOUND;
6074}
6075
Mathias Agopian65ab4712010-07-14 17:59:35 -07006076status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6077{
6078 const size_t SIZE = 256;
6079 char buffer[SIZE];
6080 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006081
6082 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6083 result.append(buffer);
6084
6085 if (mActiveTrack != 0) {
6086 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006087 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006088 mActiveTrack->dump(buffer, SIZE);
6089 result.append(buffer);
6090
6091 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6092 result.append(buffer);
6093 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6094 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006095 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006096 result.append(buffer);
6097 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6098 result.append(buffer);
6099 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6100 result.append(buffer);
6101
6102
6103 } else {
6104 result.append("No record client\n");
6105 }
6106 write(fd, result.string(), result.size());
6107
6108 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006109 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006110
6111 return NO_ERROR;
6112}
6113
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006114// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006115status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006116{
6117 size_t framesReq = buffer->frameCount;
6118 size_t framesReady = mFrameCount - mRsmpInIndex;
6119 int channelCount;
6120
6121 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006122 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006123 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006124 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006125 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6126 // Force input into standby so that it tries to
6127 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006128 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006129 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006130 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006131 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006132 buffer->frameCount = 0;
6133 return NOT_ENOUGH_DATA;
6134 }
6135 mRsmpInIndex = 0;
6136 framesReady = mFrameCount;
6137 }
6138
6139 if (framesReq > framesReady) {
6140 framesReq = framesReady;
6141 }
6142
6143 if (mChannelCount == 1 && mReqChannelCount == 2) {
6144 channelCount = 1;
6145 } else {
6146 channelCount = 2;
6147 }
6148 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6149 buffer->frameCount = framesReq;
6150 return NO_ERROR;
6151}
6152
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006153// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006154void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6155{
6156 mRsmpInIndex += buffer->frameCount;
6157 buffer->frameCount = 0;
6158}
6159
6160bool AudioFlinger::RecordThread::checkForNewParameters_l()
6161{
6162 bool reconfig = false;
6163
6164 while (!mNewParameters.isEmpty()) {
6165 status_t status = NO_ERROR;
6166 String8 keyValuePair = mNewParameters[0];
6167 AudioParameter param = AudioParameter(keyValuePair);
6168 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006169 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006170 int reqSamplingRate = mReqSampleRate;
6171 int reqChannelCount = mReqChannelCount;
6172
6173 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6174 reqSamplingRate = value;
6175 reconfig = true;
6176 }
6177 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006178 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006179 reconfig = true;
6180 }
6181 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006182 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006183 reconfig = true;
6184 }
6185 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6186 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006187 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006188 // if frame count is changed after track creation
6189 if (mActiveTrack != 0) {
6190 status = INVALID_OPERATION;
6191 } else {
6192 reconfig = true;
6193 }
6194 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006195 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6196 // forward device change to effects that have requested to be
6197 // aware of attached audio device.
6198 for (size_t i = 0; i < mEffectChains.size(); i++) {
6199 mEffectChains[i]->setDevice_l(value);
6200 }
6201 // store input device and output device but do not forward output device to audio HAL.
6202 // Note that status is ignored by the caller for output device
6203 // (see AudioFlinger::setParameters()
6204 if (value & AUDIO_DEVICE_OUT_ALL) {
6205 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6206 status = BAD_VALUE;
6207 } else {
6208 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006209 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6210 if (mTrack != NULL) {
6211 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006212 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006213 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6214 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6215 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006216 }
6217 mDevice |= (uint32_t)value;
6218 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006219 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006220 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006221 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006222 mInput->stream->common.standby(&mInput->stream->common);
6223 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6224 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006225 }
6226 if (reconfig) {
6227 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006228 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006229 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006230 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006231 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6232 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006233 status = NO_ERROR;
6234 }
6235 if (status == NO_ERROR) {
6236 readInputParameters();
6237 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6238 }
6239 }
6240 }
6241
6242 mNewParameters.removeAt(0);
6243
6244 mParamStatus = status;
6245 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006246 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6247 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006248 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006249 }
6250 return reconfig;
6251}
6252
6253String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6254{
Dima Zavinfce7a472011-04-19 22:30:36 -07006255 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006256 String8 out_s8 = String8();
6257
6258 Mutex::Autolock _l(mLock);
6259 if (initCheck() != NO_ERROR) {
6260 return out_s8;
6261 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006262
Dima Zavin799a70e2011-04-18 16:57:27 -07006263 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006264 out_s8 = String8(s);
6265 free(s);
6266 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006267}
6268
6269void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6270 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006271 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006272
6273 switch (event) {
6274 case AudioSystem::INPUT_OPENED:
6275 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006276 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006277 desc.samplingRate = mSampleRate;
6278 desc.format = mFormat;
6279 desc.frameCount = mFrameCount;
6280 desc.latency = 0;
6281 param2 = &desc;
6282 break;
6283
6284 case AudioSystem::INPUT_CLOSED:
6285 default:
6286 break;
6287 }
6288 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6289}
6290
6291void AudioFlinger::RecordThread::readInputParameters()
6292{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006293 delete mRsmpInBuffer;
6294 // mRsmpInBuffer is always assigned a new[] below
6295 delete mRsmpOutBuffer;
6296 mRsmpOutBuffer = NULL;
6297 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006298 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006299
Dima Zavin799a70e2011-04-18 16:57:27 -07006300 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006301 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6302 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006303 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006304 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006305 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006306 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006307 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006308 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6309
Glenn Kasten53d76db2012-03-08 12:32:47 -08006310 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006311 {
6312 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006313 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6314 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006315 if (mChannelCount == 1 && mReqChannelCount == 2) {
6316 channelCount = 1;
6317 } else {
6318 channelCount = 2;
6319 }
6320 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6321 mResampler->setSampleRate(mSampleRate);
6322 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6323 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6324
6325 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6326 if (mChannelCount == 1 && mReqChannelCount == 1) {
6327 mFrameCount >>= 1;
6328 }
6329
6330 }
6331 mRsmpInIndex = mFrameCount;
6332}
6333
6334unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6335{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006336 Mutex::Autolock _l(mLock);
6337 if (initCheck() != NO_ERROR) {
6338 return 0;
6339 }
6340
Dima Zavin799a70e2011-04-18 16:57:27 -07006341 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006342}
6343
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006344uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6345{
6346 Mutex::Autolock _l(mLock);
6347 uint32_t result = 0;
6348 if (getEffectChain_l(sessionId) != 0) {
6349 result = EFFECT_SESSION;
6350 }
6351
6352 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6353 result |= TRACK_SESSION;
6354 }
6355
6356 return result;
6357}
6358
Eric Laurent59bd0da2011-08-01 09:52:20 -07006359AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6360{
6361 Mutex::Autolock _l(mLock);
6362 return mTrack;
6363}
6364
Glenn Kastenaed850d2012-01-26 09:46:34 -08006365AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006366{
6367 Mutex::Autolock _l(mLock);
6368 return mInput;
6369}
6370
6371AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6372{
6373 Mutex::Autolock _l(mLock);
6374 AudioStreamIn *input = mInput;
6375 mInput = NULL;
6376 return input;
6377}
6378
6379// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006380audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006381{
6382 if (mInput == NULL) {
6383 return NULL;
6384 }
6385 return &mInput->stream->common;
6386}
6387
6388
Mathias Agopian65ab4712010-07-14 17:59:35 -07006389// ----------------------------------------------------------------------------
6390
Eric Laurenta4c5a552012-03-29 10:12:40 -07006391audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6392{
6393 if (!settingsAllowed()) {
6394 return 0;
6395 }
6396 Mutex::Autolock _l(mLock);
6397 return loadHwModule_l(name);
6398}
6399
6400// loadHwModule_l() must be called with AudioFlinger::mLock held
6401audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6402{
6403 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6404 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6405 ALOGW("loadHwModule() module %s already loaded", name);
6406 return mAudioHwDevs.keyAt(i);
6407 }
6408 }
6409
Eric Laurenta4c5a552012-03-29 10:12:40 -07006410 audio_hw_device_t *dev;
6411
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006412 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006413 if (rc) {
6414 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6415 return 0;
6416 }
6417
6418 mHardwareStatus = AUDIO_HW_INIT;
6419 rc = dev->init_check(dev);
6420 mHardwareStatus = AUDIO_HW_IDLE;
6421 if (rc) {
6422 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6423 return 0;
6424 }
6425
6426 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6427 (NULL != dev->set_master_volume)) {
6428 AutoMutex lock(mHardwareLock);
6429 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6430 dev->set_master_volume(dev, mMasterVolume);
6431 mHardwareStatus = AUDIO_HW_IDLE;
6432 }
6433
6434 audio_module_handle_t handle = nextUniqueId();
6435 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6436
6437 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006438 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006439
6440 return handle;
6441
6442}
6443
6444audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6445 audio_devices_t *pDevices,
6446 uint32_t *pSamplingRate,
6447 audio_format_t *pFormat,
6448 audio_channel_mask_t *pChannelMask,
6449 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006450 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006451{
6452 status_t status;
6453 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006454 struct audio_config config = {
6455 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6456 channel_mask: pChannelMask ? *pChannelMask : 0,
6457 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6458 };
6459 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006460 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006461
Eric Laurenta4c5a552012-03-29 10:12:40 -07006462 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6463 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006464 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006465 config.sample_rate,
6466 config.format,
6467 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006468 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006469
6470 if (pDevices == NULL || *pDevices == 0) {
6471 return 0;
6472 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006473
Mathias Agopian65ab4712010-07-14 17:59:35 -07006474 Mutex::Autolock _l(mLock);
6475
Eric Laurenta4c5a552012-03-29 10:12:40 -07006476 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006477 if (outHwDev == NULL)
6478 return 0;
6479
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006480 audio_io_handle_t id = nextUniqueId();
6481
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006482 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006483
6484 status = outHwDev->open_output_stream(outHwDev,
6485 id,
6486 *pDevices,
6487 (audio_output_flags_t)flags,
6488 &config,
6489 &outStream);
6490
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006491 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006492 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006493 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006494 config.sample_rate,
6495 config.format,
6496 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006497 status);
6498
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006499 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006500 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006501
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006502 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006503 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6504 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006505 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006506 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006507 } else {
6508 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006509 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006510 }
6511 mPlaybackThreads.add(id, thread);
6512
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006513 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6514 if (pFormat != NULL) *pFormat = config.format;
6515 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006516 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006517
6518 // notify client processes of the new output creation
6519 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006520
6521 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006522 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006523 ALOGI("Using module %d has the primary audio interface", module);
6524 mPrimaryHardwareDev = outHwDev;
6525
6526 AutoMutex lock(mHardwareLock);
6527 mHardwareStatus = AUDIO_HW_SET_MODE;
6528 outHwDev->set_mode(outHwDev, mMode);
6529
6530 // Determine the level of master volume support the primary audio HAL has,
6531 // and set the initial master volume at the same time.
6532 float initialVolume = 1.0;
6533 mMasterVolumeSupportLvl = MVS_NONE;
6534
6535 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6536 if ((NULL != outHwDev->get_master_volume) &&
6537 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6538 mMasterVolumeSupportLvl = MVS_FULL;
6539 } else {
6540 mMasterVolumeSupportLvl = MVS_SETONLY;
6541 initialVolume = 1.0;
6542 }
6543
6544 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6545 if ((NULL == outHwDev->set_master_volume) ||
6546 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6547 mMasterVolumeSupportLvl = MVS_NONE;
6548 }
6549 // now that we have a primary device, initialize master volume on other devices
6550 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6551 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6552
6553 if ((dev != mPrimaryHardwareDev) &&
6554 (NULL != dev->set_master_volume)) {
6555 dev->set_master_volume(dev, initialVolume);
6556 }
6557 }
6558 mHardwareStatus = AUDIO_HW_IDLE;
6559 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6560 ? initialVolume
6561 : 1.0;
6562 mMasterVolume = initialVolume;
6563 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006564 return id;
6565 }
6566
6567 return 0;
6568}
6569
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006570audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6571 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006572{
6573 Mutex::Autolock _l(mLock);
6574 MixerThread *thread1 = checkMixerThread_l(output1);
6575 MixerThread *thread2 = checkMixerThread_l(output2);
6576
6577 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006578 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006579 return 0;
6580 }
6581
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006582 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006583 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6584 thread->addOutputTrack(thread2);
6585 mPlaybackThreads.add(id, thread);
6586 // notify client processes of the new output creation
6587 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6588 return id;
6589}
6590
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006591status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006592{
6593 // keep strong reference on the playback thread so that
6594 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006595 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006596 {
6597 Mutex::Autolock _l(mLock);
6598 thread = checkPlaybackThread_l(output);
6599 if (thread == NULL) {
6600 return BAD_VALUE;
6601 }
6602
Steve Block3856b092011-10-20 11:56:00 +01006603 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006604
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006605 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006606 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006607 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006608 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6609 dupThread->removeOutputTrack((MixerThread *)thread.get());
6610 }
6611 }
6612 }
Glenn Kastena1117922012-01-26 10:53:32 -08006613 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006614 mPlaybackThreads.removeItem(output);
6615 }
6616 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006617 // The thread entity (active unit of execution) is no longer running here,
6618 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006619
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006620 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006621 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006622 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006623 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006624 out->hwDev->close_output_stream(out->hwDev, out->stream);
6625 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006626 }
6627 return NO_ERROR;
6628}
6629
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006630status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006631{
6632 Mutex::Autolock _l(mLock);
6633 PlaybackThread *thread = checkPlaybackThread_l(output);
6634
6635 if (thread == NULL) {
6636 return BAD_VALUE;
6637 }
6638
Steve Block3856b092011-10-20 11:56:00 +01006639 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006640 thread->suspend();
6641
6642 return NO_ERROR;
6643}
6644
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006645status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006646{
6647 Mutex::Autolock _l(mLock);
6648 PlaybackThread *thread = checkPlaybackThread_l(output);
6649
6650 if (thread == NULL) {
6651 return BAD_VALUE;
6652 }
6653
Steve Block3856b092011-10-20 11:56:00 +01006654 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006655
6656 thread->restore();
6657
6658 return NO_ERROR;
6659}
6660
Eric Laurenta4c5a552012-03-29 10:12:40 -07006661audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6662 audio_devices_t *pDevices,
6663 uint32_t *pSamplingRate,
6664 audio_format_t *pFormat,
6665 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006666{
6667 status_t status;
6668 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006669 struct audio_config config = {
6670 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6671 channel_mask: pChannelMask ? *pChannelMask : 0,
6672 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6673 };
6674 uint32_t reqSamplingRate = config.sample_rate;
6675 audio_format_t reqFormat = config.format;
6676 audio_channel_mask_t reqChannels = config.channel_mask;
6677 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006678 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006679
6680 if (pDevices == NULL || *pDevices == 0) {
6681 return 0;
6682 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006683
Mathias Agopian65ab4712010-07-14 17:59:35 -07006684 Mutex::Autolock _l(mLock);
6685
Eric Laurenta4c5a552012-03-29 10:12:40 -07006686 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006687 if (inHwDev == NULL)
6688 return 0;
6689
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006690 audio_io_handle_t id = nextUniqueId();
6691
6692 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006693 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006694 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006695 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006696 config.sample_rate,
6697 config.format,
6698 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006699 status);
6700
6701 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6702 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6703 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006704 if (status == BAD_VALUE &&
6705 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6706 (config.sample_rate <= 2 * reqSamplingRate) &&
6707 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006708 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006709 inStream = NULL;
6710 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006711 }
6712
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006713 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006714 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6715
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006716 // Start record thread
6717 // RecorThread require both input and output device indication to forward to audio
6718 // pre processing modules
6719 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6720 thread = new RecordThread(this,
6721 input,
6722 reqSamplingRate,
6723 reqChannels,
6724 id,
6725 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006726 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006727 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006728 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006729 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006730 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006731
Dima Zavin799a70e2011-04-18 16:57:27 -07006732 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006733
6734 // notify client processes of the new input creation
6735 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6736 return id;
6737 }
6738
6739 return 0;
6740}
6741
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006742status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006743{
6744 // keep strong reference on the record thread so that
6745 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006746 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006747 {
6748 Mutex::Autolock _l(mLock);
6749 thread = checkRecordThread_l(input);
6750 if (thread == NULL) {
6751 return BAD_VALUE;
6752 }
6753
Steve Block3856b092011-10-20 11:56:00 +01006754 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08006755 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006756 mRecordThreads.removeItem(input);
6757 }
6758 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006759 // The thread entity (active unit of execution) is no longer running here,
6760 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006761
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006762 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006763 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006764 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006765 in->hwDev->close_input_stream(in->hwDev, in->stream);
6766 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006767
6768 return NO_ERROR;
6769}
6770
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006771status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006772{
6773 Mutex::Autolock _l(mLock);
6774 MixerThread *dstThread = checkMixerThread_l(output);
6775 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006776 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006777 return BAD_VALUE;
6778 }
6779
Steve Block3856b092011-10-20 11:56:00 +01006780 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006781 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
6782
6783 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6784 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08006785 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006786 MixerThread *srcThread = (MixerThread *)thread;
6787 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006788 }
Eric Laurentde070132010-07-13 04:45:46 -07006789 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006790
6791 return NO_ERROR;
6792}
6793
6794
6795int AudioFlinger::newAudioSessionId()
6796{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006797 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006798}
6799
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006800void AudioFlinger::acquireAudioSessionId(int audioSession)
6801{
6802 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006803 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006804 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006805 size_t num = mAudioSessionRefs.size();
6806 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006807 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006808 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6809 ref->mCnt++;
6810 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006811 return;
6812 }
6813 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006814 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6815 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006816}
6817
6818void AudioFlinger::releaseAudioSessionId(int audioSession)
6819{
6820 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006821 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006822 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006823 size_t num = mAudioSessionRefs.size();
6824 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006825 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006826 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6827 ref->mCnt--;
6828 ALOGV(" decremented refcount to %d", ref->mCnt);
6829 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006830 mAudioSessionRefs.removeAt(i);
6831 delete ref;
6832 purgeStaleEffects_l();
6833 }
6834 return;
6835 }
6836 }
Steve Block5ff1dd52012-01-05 23:22:43 +00006837 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006838}
6839
6840void AudioFlinger::purgeStaleEffects_l() {
6841
Steve Block3856b092011-10-20 11:56:00 +01006842 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006843
6844 Vector< sp<EffectChain> > chains;
6845
6846 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6847 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6848 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6849 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07006850 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6851 chains.push(ec);
6852 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006853 }
6854 }
6855 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6856 sp<RecordThread> t = mRecordThreads.valueAt(i);
6857 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6858 sp<EffectChain> ec = t->mEffectChains[j];
6859 chains.push(ec);
6860 }
6861 }
6862
6863 for (size_t i = 0; i < chains.size(); i++) {
6864 sp<EffectChain> ec = chains[i];
6865 int sessionid = ec->sessionId();
6866 sp<ThreadBase> t = ec->mThread.promote();
6867 if (t == 0) {
6868 continue;
6869 }
6870 size_t numsessionrefs = mAudioSessionRefs.size();
6871 bool found = false;
6872 for (size_t k = 0; k < numsessionrefs; k++) {
6873 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006874 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01006875 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006876 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006877 found = true;
6878 break;
6879 }
6880 }
6881 if (!found) {
6882 // remove all effects from the chain
6883 while (ec->mEffects.size()) {
6884 sp<EffectModule> effect = ec->mEffects[0];
6885 effect->unPin();
6886 Mutex::Autolock _l (t->mLock);
6887 t->removeEffect_l(effect);
6888 for (size_t j = 0; j < effect->mHandles.size(); j++) {
6889 sp<EffectHandle> handle = effect->mHandles[j].promote();
6890 if (handle != 0) {
6891 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07006892 if (handle->mHasControl && handle->mEnabled) {
6893 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
6894 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006895 }
6896 }
6897 AudioSystem::unregisterEffect(effect->id());
6898 }
6899 }
6900 }
6901 return;
6902}
6903
Mathias Agopian65ab4712010-07-14 17:59:35 -07006904// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006905AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006906{
Glenn Kastena1117922012-01-26 10:53:32 -08006907 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006908}
6909
6910// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006911AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006912{
6913 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08006914 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006915}
6916
6917// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006918AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006919{
Glenn Kastena1117922012-01-26 10:53:32 -08006920 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006921}
6922
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006923uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07006924{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006925 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006926}
6927
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006928AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006929{
6930 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6931 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006932 AudioStreamOut *output = thread->getOutput();
6933 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006934 return thread;
6935 }
6936 }
6937 return NULL;
6938}
6939
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08006940uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006941{
6942 PlaybackThread *thread = primaryPlaybackThread_l();
6943
6944 if (thread == NULL) {
6945 return 0;
6946 }
6947
6948 return thread->device();
6949}
6950
Eric Laurenta011e352012-03-29 15:51:43 -07006951sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
6952 int triggerSession,
6953 int listenerSession,
6954 sync_event_callback_t callBack,
6955 void *cookie)
6956{
6957 Mutex::Autolock _l(mLock);
6958
6959 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
6960 status_t playStatus = NAME_NOT_FOUND;
6961 status_t recStatus = NAME_NOT_FOUND;
6962 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6963 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
6964 if (playStatus == NO_ERROR) {
6965 return event;
6966 }
6967 }
6968 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6969 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
6970 if (recStatus == NO_ERROR) {
6971 return event;
6972 }
6973 }
6974 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
6975 mPendingSyncEvents.add(event);
6976 } else {
6977 ALOGV("createSyncEvent() invalid event %d", event->type());
6978 event.clear();
6979 }
6980 return event;
6981}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006982
Mathias Agopian65ab4712010-07-14 17:59:35 -07006983// ----------------------------------------------------------------------------
6984// Effect management
6985// ----------------------------------------------------------------------------
6986
6987
Glenn Kastenf587ba52012-01-26 16:25:10 -08006988status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006989{
6990 Mutex::Autolock _l(mLock);
6991 return EffectQueryNumberEffects(numEffects);
6992}
6993
Glenn Kastenf587ba52012-01-26 16:25:10 -08006994status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006995{
6996 Mutex::Autolock _l(mLock);
6997 return EffectQueryEffect(index, descriptor);
6998}
6999
Glenn Kasten5e92a782012-01-30 07:40:52 -08007000status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007001 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007002{
7003 Mutex::Autolock _l(mLock);
7004 return EffectGetDescriptor(pUuid, descriptor);
7005}
7006
7007
Mathias Agopian65ab4712010-07-14 17:59:35 -07007008sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7009 effect_descriptor_t *pDesc,
7010 const sp<IEffectClient>& effectClient,
7011 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007012 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007013 int sessionId,
7014 status_t *status,
7015 int *id,
7016 int *enabled)
7017{
7018 status_t lStatus = NO_ERROR;
7019 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007020 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007021
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007022 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007023 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007024
7025 if (pDesc == NULL) {
7026 lStatus = BAD_VALUE;
7027 goto Exit;
7028 }
7029
Eric Laurent84e9a102010-09-23 16:10:16 -07007030 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007031 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007032 lStatus = PERMISSION_DENIED;
7033 goto Exit;
7034 }
7035
Dima Zavinfce7a472011-04-19 22:30:36 -07007036 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007037 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007038 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007039 lStatus = PERMISSION_DENIED;
7040 goto Exit;
7041 }
7042
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007043 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007044 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007045 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007046 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007047 lStatus = BAD_VALUE;
7048 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007049 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007050 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007051 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007052 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007053 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007054 }
7055 }
7056
Mathias Agopian65ab4712010-07-14 17:59:35 -07007057 {
7058 Mutex::Autolock _l(mLock);
7059
Mathias Agopian65ab4712010-07-14 17:59:35 -07007060
7061 if (!EffectIsNullUuid(&pDesc->uuid)) {
7062 // if uuid is specified, request effect descriptor
7063 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7064 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007065 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007066 goto Exit;
7067 }
7068 } else {
7069 // if uuid is not specified, look for an available implementation
7070 // of the required type in effect factory
7071 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007072 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007073 lStatus = BAD_VALUE;
7074 goto Exit;
7075 }
7076 uint32_t numEffects = 0;
7077 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007078 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007079 bool found = false;
7080
7081 lStatus = EffectQueryNumberEffects(&numEffects);
7082 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007083 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007084 goto Exit;
7085 }
7086 for (uint32_t i = 0; i < numEffects; i++) {
7087 lStatus = EffectQueryEffect(i, &desc);
7088 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007089 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007090 continue;
7091 }
7092 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7093 // If matching type found save effect descriptor. If the session is
7094 // 0 and the effect is not auxiliary, continue enumeration in case
7095 // an auxiliary version of this effect type is available
7096 found = true;
7097 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007098 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007099 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7100 break;
7101 }
7102 }
7103 }
7104 if (!found) {
7105 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007106 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007107 goto Exit;
7108 }
7109 // For same effect type, chose auxiliary version over insert version if
7110 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007111 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007112 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7113 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7114 }
7115 }
7116
7117 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007118 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007119 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7120 lStatus = INVALID_OPERATION;
7121 goto Exit;
7122 }
7123
Eric Laurent59255e42011-07-27 19:49:51 -07007124 // check recording permission for visualizer
7125 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7126 !recordingAllowed()) {
7127 lStatus = PERMISSION_DENIED;
7128 goto Exit;
7129 }
7130
Mathias Agopian65ab4712010-07-14 17:59:35 -07007131 // return effect descriptor
7132 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7133
7134 // If output is not specified try to find a matching audio session ID in one of the
7135 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007136 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7137 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007138 // Note: io is never 0 when creating an effect on an input
7139 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007140 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007141 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7142 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007143 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007144 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007145 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007146 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007147 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007148 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7149 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7150 io = mRecordThreads.keyAt(i);
7151 break;
7152 }
7153 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007154 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007155 // If no output thread contains the requested session ID, default to
7156 // first output. The effect chain will be moved to the correct output
7157 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007158 if (io == 0 && mPlaybackThreads.size()) {
7159 io = mPlaybackThreads.keyAt(0);
7160 }
Steve Block3856b092011-10-20 11:56:00 +01007161 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007162 }
7163 ThreadBase *thread = checkRecordThread_l(io);
7164 if (thread == NULL) {
7165 thread = checkPlaybackThread_l(io);
7166 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007167 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007168 lStatus = BAD_VALUE;
7169 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007170 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007171 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007172
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007173 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007174
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007175 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007176 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7177 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007178 if (handle != 0 && id != NULL) {
7179 *id = handle->id();
7180 }
7181 }
7182
7183Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007184 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007185 *status = lStatus;
7186 }
7187 return handle;
7188}
7189
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007190status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7191 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007192{
Steve Block3856b092011-10-20 11:56:00 +01007193 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007194 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007195 Mutex::Autolock _l(mLock);
7196 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007197 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007198 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007199 }
Eric Laurentde070132010-07-13 04:45:46 -07007200 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7201 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007202 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007203 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007204 }
Eric Laurentde070132010-07-13 04:45:46 -07007205 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7206 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007207 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007208 return BAD_VALUE;
7209 }
7210
7211 Mutex::Autolock _dl(dstThread->mLock);
7212 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007213 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007214
Mathias Agopian65ab4712010-07-14 17:59:35 -07007215 return NO_ERROR;
7216}
7217
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007218// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007219status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007220 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007221 AudioFlinger::PlaybackThread *dstThread,
7222 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007223{
Steve Block3856b092011-10-20 11:56:00 +01007224 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007225 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007226
Eric Laurent59255e42011-07-27 19:49:51 -07007227 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007228 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007229 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007230 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007231 return INVALID_OPERATION;
7232 }
7233
Eric Laurent39e94f82010-07-28 01:32:47 -07007234 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007235 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007236 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007237 // removed.
7238 srcThread->removeEffectChain_l(chain);
7239
7240 // transfer all effects one by one so that new effect chain is created on new thread with
7241 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007242 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007243 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007244 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007245 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7246 while (effect != 0) {
7247 srcThread->removeEffect_l(effect);
7248 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007249 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7250 if (effect->state() == EffectModule::ACTIVE ||
7251 effect->state() == EffectModule::STOPPING) {
7252 effect->start();
7253 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007254 // if the move request is not received from audio policy manager, the effect must be
7255 // re-registered with the new strategy and output
7256 if (dstChain == 0) {
7257 dstChain = effect->chain().promote();
7258 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007259 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007260 srcThread->addEffect_l(effect);
7261 return NO_INIT;
7262 }
7263 strategy = dstChain->strategy();
7264 }
7265 if (reRegister) {
7266 AudioSystem::unregisterEffect(effect->id());
7267 AudioSystem::registerEffect(&effect->desc(),
7268 dstOutput,
7269 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007270 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007271 effect->id());
7272 }
Eric Laurentde070132010-07-13 04:45:46 -07007273 effect = chain->getEffectFromId_l(0);
7274 }
7275
7276 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007277}
7278
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007279
Mathias Agopian65ab4712010-07-14 17:59:35 -07007280// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007281sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007282 const sp<AudioFlinger::Client>& client,
7283 const sp<IEffectClient>& effectClient,
7284 int32_t priority,
7285 int sessionId,
7286 effect_descriptor_t *desc,
7287 int *enabled,
7288 status_t *status
7289 )
7290{
7291 sp<EffectModule> effect;
7292 sp<EffectHandle> handle;
7293 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007294 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007295 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007296 bool effectCreated = false;
7297 bool effectRegistered = false;
7298
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007299 lStatus = initCheck();
7300 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007301 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007302 goto Exit;
7303 }
7304
7305 // Do not allow effects with session ID 0 on direct output or duplicating threads
7306 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007307 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007308 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007309 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007310 lStatus = BAD_VALUE;
7311 goto Exit;
7312 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007313 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007314 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007315 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007316 desc->name, desc->flags, mType);
7317 lStatus = BAD_VALUE;
7318 goto Exit;
7319 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007320
Steve Block3856b092011-10-20 11:56:00 +01007321 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007322
7323 { // scope for mLock
7324 Mutex::Autolock _l(mLock);
7325
7326 // check for existing effect chain with the requested audio session
7327 chain = getEffectChain_l(sessionId);
7328 if (chain == 0) {
7329 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007330 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007331 chain = new EffectChain(this, sessionId);
7332 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007333 chain->setStrategy(getStrategyForSession_l(sessionId));
7334 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007335 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007336 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007337 }
7338
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007339 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007340
7341 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007342 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007343 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007344 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007345 if (lStatus != NO_ERROR) {
7346 goto Exit;
7347 }
7348 effectRegistered = true;
7349 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007350 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007351 lStatus = effect->status();
7352 if (lStatus != NO_ERROR) {
7353 goto Exit;
7354 }
Eric Laurentcab11242010-07-15 12:50:15 -07007355 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007356 if (lStatus != NO_ERROR) {
7357 goto Exit;
7358 }
7359 effectCreated = true;
7360
7361 effect->setDevice(mDevice);
7362 effect->setMode(mAudioFlinger->getMode());
7363 }
7364 // create effect handle and connect it to effect module
7365 handle = new EffectHandle(effect, client, effectClient, priority);
7366 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08007367 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007368 *enabled = (int)effect->isEnabled();
7369 }
7370 }
7371
7372Exit:
7373 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007374 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007375 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007376 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007377 }
7378 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007379 AudioSystem::unregisterEffect(effect->id());
7380 }
7381 if (chainCreated) {
7382 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007383 }
7384 handle.clear();
7385 }
7386
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007387 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007388 *status = lStatus;
7389 }
7390 return handle;
7391}
7392
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007393sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7394{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007395 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007396 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007397}
7398
Eric Laurentde070132010-07-13 04:45:46 -07007399// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7400// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007401status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007402{
7403 // check for existing effect chain with the requested audio session
7404 int sessionId = effect->sessionId();
7405 sp<EffectChain> chain = getEffectChain_l(sessionId);
7406 bool chainCreated = false;
7407
7408 if (chain == 0) {
7409 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007410 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007411 chain = new EffectChain(this, sessionId);
7412 addEffectChain_l(chain);
7413 chain->setStrategy(getStrategyForSession_l(sessionId));
7414 chainCreated = true;
7415 }
Steve Block3856b092011-10-20 11:56:00 +01007416 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007417
7418 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007419 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007420 this, effect->desc().name, chain.get());
7421 return BAD_VALUE;
7422 }
7423
7424 status_t status = chain->addEffect_l(effect);
7425 if (status != NO_ERROR) {
7426 if (chainCreated) {
7427 removeEffectChain_l(chain);
7428 }
7429 return status;
7430 }
7431
7432 effect->setDevice(mDevice);
7433 effect->setMode(mAudioFlinger->getMode());
7434 return NO_ERROR;
7435}
7436
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007437void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007438
Steve Block3856b092011-10-20 11:56:00 +01007439 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007440 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007441 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7442 detachAuxEffect_l(effect->id());
7443 }
7444
7445 sp<EffectChain> chain = effect->chain().promote();
7446 if (chain != 0) {
7447 // remove effect chain if removing last effect
7448 if (chain->removeEffect_l(effect) == 0) {
7449 removeEffectChain_l(chain);
7450 }
7451 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007452 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007453 }
7454}
7455
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007456void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007457 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007458{
7459 effectChains = mEffectChains;
7460 for (size_t i = 0; i < mEffectChains.size(); i++) {
7461 mEffectChains[i]->lock();
7462 }
7463}
7464
7465void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007466 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007467{
7468 for (size_t i = 0; i < effectChains.size(); i++) {
7469 effectChains[i]->unlock();
7470 }
7471}
7472
7473sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7474{
7475 Mutex::Autolock _l(mLock);
7476 return getEffectChain_l(sessionId);
7477}
7478
7479sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7480{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007481 size_t size = mEffectChains.size();
7482 for (size_t i = 0; i < size; i++) {
7483 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007484 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007485 }
7486 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007487 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007488}
7489
Glenn Kastenf78aee72012-01-04 11:00:47 -08007490void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007491{
7492 Mutex::Autolock _l(mLock);
7493 size_t size = mEffectChains.size();
7494 for (size_t i = 0; i < size; i++) {
7495 mEffectChains[i]->setMode_l(mode);
7496 }
7497}
7498
7499void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007500 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007501 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007502
Mathias Agopian65ab4712010-07-14 17:59:35 -07007503 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007504 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007505 // delete the effect module if removing last handle on it
7506 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007507 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007508 removeEffect_l(effect);
7509 AudioSystem::unregisterEffect(effect->id());
7510 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007511 }
7512}
7513
7514status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7515{
7516 int session = chain->sessionId();
7517 int16_t *buffer = mMixBuffer;
7518 bool ownsBuffer = false;
7519
Steve Block3856b092011-10-20 11:56:00 +01007520 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007521 if (session > 0) {
7522 // Only one effect chain can be present in direct output thread and it uses
7523 // the mix buffer as input
7524 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007525 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007526 buffer = new int16_t[numSamples];
7527 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007528 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007529 ownsBuffer = true;
7530 }
7531
7532 // Attach all tracks with same session ID to this chain.
7533 for (size_t i = 0; i < mTracks.size(); ++i) {
7534 sp<Track> track = mTracks[i];
7535 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007536 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007537 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007538 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007539 }
7540 }
7541
7542 // indicate all active tracks in the chain
7543 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7544 sp<Track> track = mActiveTracks[i].promote();
7545 if (track == 0) continue;
7546 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007547 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007548 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007549 }
7550 }
7551 }
7552
7553 chain->setInBuffer(buffer, ownsBuffer);
7554 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007555 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007556 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007557 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7558 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007559 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007560 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7561 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007562 // Effect chain for other sessions are inserted at beginning of effect
7563 // chains list to be processed before output mix effects. Relative order between other
7564 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007565 size_t size = mEffectChains.size();
7566 size_t i = 0;
7567 for (i = 0; i < size; i++) {
7568 if (mEffectChains[i]->sessionId() < session) break;
7569 }
7570 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007571 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007572
7573 return NO_ERROR;
7574}
7575
7576size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7577{
7578 int session = chain->sessionId();
7579
Steve Block3856b092011-10-20 11:56:00 +01007580 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007581
7582 for (size_t i = 0; i < mEffectChains.size(); i++) {
7583 if (chain == mEffectChains[i]) {
7584 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007585 // detach all active tracks from the chain
7586 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7587 sp<Track> track = mActiveTracks[i].promote();
7588 if (track == 0) continue;
7589 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007590 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007591 chain.get(), session);
7592 chain->decActiveTrackCnt();
7593 }
7594 }
7595
Mathias Agopian65ab4712010-07-14 17:59:35 -07007596 // detach all tracks with same session ID from this chain
7597 for (size_t i = 0; i < mTracks.size(); ++i) {
7598 sp<Track> track = mTracks[i];
7599 if (session == track->sessionId()) {
7600 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007601 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007602 }
7603 }
Eric Laurentde070132010-07-13 04:45:46 -07007604 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007605 }
7606 }
7607 return mEffectChains.size();
7608}
7609
Eric Laurentde070132010-07-13 04:45:46 -07007610status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7611 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007612{
7613 Mutex::Autolock _l(mLock);
7614 return attachAuxEffect_l(track, EffectId);
7615}
7616
Eric Laurentde070132010-07-13 04:45:46 -07007617status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7618 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007619{
7620 status_t status = NO_ERROR;
7621
7622 if (EffectId == 0) {
7623 track->setAuxBuffer(0, NULL);
7624 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007625 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7626 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007627 if (effect != 0) {
7628 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7629 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7630 } else {
7631 status = INVALID_OPERATION;
7632 }
7633 } else {
7634 status = BAD_VALUE;
7635 }
7636 }
7637 return status;
7638}
7639
7640void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7641{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007642 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007643 sp<Track> track = mTracks[i];
7644 if (track->auxEffectId() == effectId) {
7645 attachAuxEffect_l(track, 0);
7646 }
7647 }
7648}
7649
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007650status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7651{
7652 // only one chain per input thread
7653 if (mEffectChains.size() != 0) {
7654 return INVALID_OPERATION;
7655 }
Steve Block3856b092011-10-20 11:56:00 +01007656 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007657
7658 chain->setInBuffer(NULL);
7659 chain->setOutBuffer(NULL);
7660
Eric Laurent59255e42011-07-27 19:49:51 -07007661 checkSuspendOnAddEffectChain_l(chain);
7662
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007663 mEffectChains.add(chain);
7664
7665 return NO_ERROR;
7666}
7667
7668size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7669{
Steve Block3856b092011-10-20 11:56:00 +01007670 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007671 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007672 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7673 chain.get(), mEffectChains.size(), this);
7674 if (mEffectChains.size() == 1) {
7675 mEffectChains.removeAt(0);
7676 }
7677 return 0;
7678}
7679
Mathias Agopian65ab4712010-07-14 17:59:35 -07007680// ----------------------------------------------------------------------------
7681// EffectModule implementation
7682// ----------------------------------------------------------------------------
7683
7684#undef LOG_TAG
7685#define LOG_TAG "AudioFlinger::EffectModule"
7686
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007687AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007688 const wp<AudioFlinger::EffectChain>& chain,
7689 effect_descriptor_t *desc,
7690 int id,
7691 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007692 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007693 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007694{
Steve Block3856b092011-10-20 11:56:00 +01007695 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007696 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007697 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007698 return;
7699 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007700
7701 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7702
7703 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007704 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007705
7706 if (mStatus != NO_ERROR) {
7707 return;
7708 }
7709 lStatus = init();
7710 if (lStatus < 0) {
7711 mStatus = lStatus;
7712 goto Error;
7713 }
7714
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007715 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
7716 mPinned = true;
7717 }
Steve Block3856b092011-10-20 11:56:00 +01007718 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007719 return;
7720Error:
7721 EffectRelease(mEffectInterface);
7722 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007723 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007724}
7725
7726AudioFlinger::EffectModule::~EffectModule()
7727{
Steve Block3856b092011-10-20 11:56:00 +01007728 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007729 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007730 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7731 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7732 sp<ThreadBase> thread = mThread.promote();
7733 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007734 audio_stream_t *stream = thread->stream();
7735 if (stream != NULL) {
7736 stream->remove_audio_effect(stream, mEffectInterface);
7737 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007738 }
7739 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007740 // release effect engine
7741 EffectRelease(mEffectInterface);
7742 }
7743}
7744
Glenn Kasten435dbe62012-01-30 10:15:48 -08007745status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007746{
7747 status_t status;
7748
7749 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007750 int priority = handle->priority();
7751 size_t size = mHandles.size();
7752 sp<EffectHandle> h;
7753 size_t i;
7754 for (i = 0; i < size; i++) {
7755 h = mHandles[i].promote();
7756 if (h == 0) continue;
7757 if (h->priority() <= priority) break;
7758 }
7759 // if inserted in first place, move effect control from previous owner to this handle
7760 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007761 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007762 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007763 enabled = h->enabled();
7764 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007765 }
Eric Laurent59255e42011-07-27 19:49:51 -07007766 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007767 status = NO_ERROR;
7768 } else {
7769 status = ALREADY_EXISTS;
7770 }
Steve Block3856b092011-10-20 11:56:00 +01007771 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007772 mHandles.insertAt(handle, i);
7773 return status;
7774}
7775
7776size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
7777{
7778 Mutex::Autolock _l(mLock);
7779 size_t size = mHandles.size();
7780 size_t i;
7781 for (i = 0; i < size; i++) {
7782 if (mHandles[i] == handle) break;
7783 }
7784 if (i == size) {
7785 return size;
7786 }
Steve Block3856b092011-10-20 11:56:00 +01007787 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07007788
7789 bool enabled = false;
7790 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08007791 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01007792 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07007793 enabled = hdl->enabled();
7794 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007795 mHandles.removeAt(i);
7796 size = mHandles.size();
7797 // if removed from first place, move effect control from this handle to next in line
7798 if (i == 0 && size != 0) {
7799 sp<EffectHandle> h = mHandles[0].promote();
7800 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007801 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007802 }
7803 }
7804
Eric Laurentec437d82011-07-26 20:54:46 -07007805 // Prevent calls to process() and other functions on effect interface from now on.
7806 // The effect engine will be released by the destructor when the last strong reference on
7807 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007808 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07007809 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07007810 }
7811
Mathias Agopian65ab4712010-07-14 17:59:35 -07007812 return size;
7813}
7814
Eric Laurent59255e42011-07-27 19:49:51 -07007815sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7816{
7817 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08007818 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007819}
7820
Glenn Kasten58123c32012-02-03 10:32:24 -08007821void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007822{
Glenn Kasten90bebef2012-01-27 15:24:38 -08007823 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007824 // keep a strong reference on this EffectModule to avoid calling the
7825 // destructor before we exit
7826 sp<EffectModule> keep(this);
7827 {
7828 sp<ThreadBase> thread = mThread.promote();
7829 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007830 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007831 }
7832 }
7833}
7834
7835void AudioFlinger::EffectModule::updateState() {
7836 Mutex::Autolock _l(mLock);
7837
7838 switch (mState) {
7839 case RESTART:
7840 reset_l();
7841 // FALL THROUGH
7842
7843 case STARTING:
7844 // clear auxiliary effect input buffer for next accumulation
7845 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7846 memset(mConfig.inputCfg.buffer.raw,
7847 0,
7848 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7849 }
7850 start_l();
7851 mState = ACTIVE;
7852 break;
7853 case STOPPING:
7854 stop_l();
7855 mDisableWaitCnt = mMaxDisableWaitCnt;
7856 mState = STOPPED;
7857 break;
7858 case STOPPED:
7859 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
7860 // turn off sequence.
7861 if (--mDisableWaitCnt == 0) {
7862 reset_l();
7863 mState = IDLE;
7864 }
7865 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007866 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07007867 break;
7868 }
7869}
7870
7871void AudioFlinger::EffectModule::process()
7872{
7873 Mutex::Autolock _l(mLock);
7874
Eric Laurentec437d82011-07-26 20:54:46 -07007875 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007876 mConfig.inputCfg.buffer.raw == NULL ||
7877 mConfig.outputCfg.buffer.raw == NULL) {
7878 return;
7879 }
7880
Eric Laurent8f45bd72010-08-31 13:50:07 -07007881 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007882 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
7883 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08007884 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007885 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07007886 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007887 }
7888
7889 // do the actual processing in the effect engine
7890 int ret = (*mEffectInterface)->process(mEffectInterface,
7891 &mConfig.inputCfg.buffer,
7892 &mConfig.outputCfg.buffer);
7893
7894 // force transition to IDLE state when engine is ready
7895 if (mState == STOPPED && ret == -ENODATA) {
7896 mDisableWaitCnt = 1;
7897 }
7898
7899 // clear auxiliary effect input buffer for next accumulation
7900 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08007901 memset(mConfig.inputCfg.buffer.raw, 0,
7902 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007903 }
7904 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08007905 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7906 // If an insert effect is idle and input buffer is different from output buffer,
7907 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07007908 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07007909 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08007910 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
7911 int16_t *in = mConfig.inputCfg.buffer.s16;
7912 int16_t *out = mConfig.outputCfg.buffer.s16;
7913 for (size_t i = 0; i < frameCnt; i++) {
7914 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007915 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007916 }
7917 }
7918}
7919
7920void AudioFlinger::EffectModule::reset_l()
7921{
7922 if (mEffectInterface == NULL) {
7923 return;
7924 }
7925 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
7926}
7927
7928status_t AudioFlinger::EffectModule::configure()
7929{
7930 uint32_t channels;
7931 if (mEffectInterface == NULL) {
7932 return NO_INIT;
7933 }
7934
7935 sp<ThreadBase> thread = mThread.promote();
7936 if (thread == 0) {
7937 return DEAD_OBJECT;
7938 }
7939
7940 // TODO: handle configuration of effects replacing track process
7941 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007942 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007943 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07007944 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007945 }
7946
7947 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07007948 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007949 } else {
7950 mConfig.inputCfg.channels = channels;
7951 }
7952 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07007953 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
7954 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007955 mConfig.inputCfg.samplingRate = thread->sampleRate();
7956 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
7957 mConfig.inputCfg.bufferProvider.cookie = NULL;
7958 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
7959 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
7960 mConfig.outputCfg.bufferProvider.cookie = NULL;
7961 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
7962 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
7963 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
7964 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07007965 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07007966 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07007967 // - in other sessions:
7968 // last effect in the chain accumulates in output buffer: input buffer != output buffer
7969 // other effect: overwrites output buffer: input buffer == output buffer
7970 // Auxiliary effect:
7971 // accumulates in output buffer: input buffer != output buffer
7972 // Therefore: accumulate <=> input buffer != output buffer
7973 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7974 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
7975 } else {
7976 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
7977 }
7978 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
7979 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
7980 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
7981 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
7982
Steve Block3856b092011-10-20 11:56:00 +01007983 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07007984 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
7985
Mathias Agopian65ab4712010-07-14 17:59:35 -07007986 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007987 uint32_t size = sizeof(int);
7988 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08007989 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07007990 sizeof(effect_config_t),
7991 &mConfig,
7992 &size,
7993 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007994 if (status == 0) {
7995 status = cmdStatus;
7996 }
7997
7998 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
7999 (1000 * mConfig.outputCfg.buffer.frameCount);
8000
8001 return status;
8002}
8003
8004status_t AudioFlinger::EffectModule::init()
8005{
8006 Mutex::Autolock _l(mLock);
8007 if (mEffectInterface == NULL) {
8008 return NO_INIT;
8009 }
8010 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008011 uint32_t size = sizeof(status_t);
8012 status_t status = (*mEffectInterface)->command(mEffectInterface,
8013 EFFECT_CMD_INIT,
8014 0,
8015 NULL,
8016 &size,
8017 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008018 if (status == 0) {
8019 status = cmdStatus;
8020 }
8021 return status;
8022}
8023
Eric Laurentec35a142011-10-05 17:42:25 -07008024status_t AudioFlinger::EffectModule::start()
8025{
8026 Mutex::Autolock _l(mLock);
8027 return start_l();
8028}
8029
Mathias Agopian65ab4712010-07-14 17:59:35 -07008030status_t AudioFlinger::EffectModule::start_l()
8031{
8032 if (mEffectInterface == NULL) {
8033 return NO_INIT;
8034 }
8035 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008036 uint32_t size = sizeof(status_t);
8037 status_t status = (*mEffectInterface)->command(mEffectInterface,
8038 EFFECT_CMD_ENABLE,
8039 0,
8040 NULL,
8041 &size,
8042 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008043 if (status == 0) {
8044 status = cmdStatus;
8045 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008046 if (status == 0 &&
8047 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8048 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8049 sp<ThreadBase> thread = mThread.promote();
8050 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008051 audio_stream_t *stream = thread->stream();
8052 if (stream != NULL) {
8053 stream->add_audio_effect(stream, mEffectInterface);
8054 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008055 }
8056 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008057 return status;
8058}
8059
Eric Laurentec437d82011-07-26 20:54:46 -07008060status_t AudioFlinger::EffectModule::stop()
8061{
8062 Mutex::Autolock _l(mLock);
8063 return stop_l();
8064}
8065
Mathias Agopian65ab4712010-07-14 17:59:35 -07008066status_t AudioFlinger::EffectModule::stop_l()
8067{
8068 if (mEffectInterface == NULL) {
8069 return NO_INIT;
8070 }
8071 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008072 uint32_t size = sizeof(status_t);
8073 status_t status = (*mEffectInterface)->command(mEffectInterface,
8074 EFFECT_CMD_DISABLE,
8075 0,
8076 NULL,
8077 &size,
8078 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008079 if (status == 0) {
8080 status = cmdStatus;
8081 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008082 if (status == 0 &&
8083 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8084 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8085 sp<ThreadBase> thread = mThread.promote();
8086 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008087 audio_stream_t *stream = thread->stream();
8088 if (stream != NULL) {
8089 stream->remove_audio_effect(stream, mEffectInterface);
8090 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008091 }
8092 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008093 return status;
8094}
8095
Eric Laurent25f43952010-07-28 05:40:18 -07008096status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8097 uint32_t cmdSize,
8098 void *pCmdData,
8099 uint32_t *replySize,
8100 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008101{
8102 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008103// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008104
Eric Laurentec437d82011-07-26 20:54:46 -07008105 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008106 return NO_INIT;
8107 }
Eric Laurent25f43952010-07-28 05:40:18 -07008108 status_t status = (*mEffectInterface)->command(mEffectInterface,
8109 cmdCode,
8110 cmdSize,
8111 pCmdData,
8112 replySize,
8113 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008114 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008115 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008116 for (size_t i = 1; i < mHandles.size(); i++) {
8117 sp<EffectHandle> h = mHandles[i].promote();
8118 if (h != 0) {
8119 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8120 }
8121 }
8122 }
8123 return status;
8124}
8125
8126status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8127{
Eric Laurentdb7c0792011-08-10 10:37:50 -07008128
Mathias Agopian65ab4712010-07-14 17:59:35 -07008129 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008130 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008131
8132 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008133 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8134 if (enabled && status != NO_ERROR) {
8135 return status;
8136 }
8137
Mathias Agopian65ab4712010-07-14 17:59:35 -07008138 switch (mState) {
8139 // going from disabled to enabled
8140 case IDLE:
8141 mState = STARTING;
8142 break;
8143 case STOPPED:
8144 mState = RESTART;
8145 break;
8146 case STOPPING:
8147 mState = ACTIVE;
8148 break;
8149
8150 // going from enabled to disabled
8151 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008152 mState = STOPPED;
8153 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008154 case STARTING:
8155 mState = IDLE;
8156 break;
8157 case ACTIVE:
8158 mState = STOPPING;
8159 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008160 case DESTROYED:
8161 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008162 }
8163 for (size_t i = 1; i < mHandles.size(); i++) {
8164 sp<EffectHandle> h = mHandles[i].promote();
8165 if (h != 0) {
8166 h->setEnabled(enabled);
8167 }
8168 }
8169 }
8170 return NO_ERROR;
8171}
8172
Glenn Kastenc59c0042012-02-02 14:06:11 -08008173bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008174{
8175 switch (mState) {
8176 case RESTART:
8177 case STARTING:
8178 case ACTIVE:
8179 return true;
8180 case IDLE:
8181 case STOPPING:
8182 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008183 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008184 default:
8185 return false;
8186 }
8187}
8188
Glenn Kastenc59c0042012-02-02 14:06:11 -08008189bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008190{
8191 switch (mState) {
8192 case RESTART:
8193 case ACTIVE:
8194 case STOPPING:
8195 case STOPPED:
8196 return true;
8197 case IDLE:
8198 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008199 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008200 default:
8201 return false;
8202 }
8203}
8204
Mathias Agopian65ab4712010-07-14 17:59:35 -07008205status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8206{
8207 Mutex::Autolock _l(mLock);
8208 status_t status = NO_ERROR;
8209
8210 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8211 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008212 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008213 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8214 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008215 status_t cmdStatus;
8216 uint32_t volume[2];
8217 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008218 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008219 volume[0] = *left;
8220 volume[1] = *right;
8221 if (controller) {
8222 pVolume = volume;
8223 }
Eric Laurent25f43952010-07-28 05:40:18 -07008224 status = (*mEffectInterface)->command(mEffectInterface,
8225 EFFECT_CMD_SET_VOLUME,
8226 size,
8227 volume,
8228 &size,
8229 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008230 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8231 *left = volume[0];
8232 *right = volume[1];
8233 }
8234 }
8235 return status;
8236}
8237
8238status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8239{
8240 Mutex::Autolock _l(mLock);
8241 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008242 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8243 // audio pre processing modules on RecordThread can receive both output and
8244 // input device indication in the same call
8245 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8246 if (dev) {
8247 status_t cmdStatus;
8248 uint32_t size = sizeof(status_t);
8249
8250 status = (*mEffectInterface)->command(mEffectInterface,
8251 EFFECT_CMD_SET_DEVICE,
8252 sizeof(uint32_t),
8253 &dev,
8254 &size,
8255 &cmdStatus);
8256 if (status == NO_ERROR) {
8257 status = cmdStatus;
8258 }
8259 }
8260 dev = device & AUDIO_DEVICE_IN_ALL;
8261 if (dev) {
8262 status_t cmdStatus;
8263 uint32_t size = sizeof(status_t);
8264
8265 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8266 EFFECT_CMD_SET_INPUT_DEVICE,
8267 sizeof(uint32_t),
8268 &dev,
8269 &size,
8270 &cmdStatus);
8271 if (status2 == NO_ERROR) {
8272 status2 = cmdStatus;
8273 }
8274 if (status == NO_ERROR) {
8275 status = status2;
8276 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008277 }
8278 }
8279 return status;
8280}
8281
Glenn Kastenf78aee72012-01-04 11:00:47 -08008282status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008283{
8284 Mutex::Autolock _l(mLock);
8285 status_t status = NO_ERROR;
8286 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008287 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008288 uint32_t size = sizeof(status_t);
8289 status = (*mEffectInterface)->command(mEffectInterface,
8290 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008291 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008292 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008293 &size,
8294 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008295 if (status == NO_ERROR) {
8296 status = cmdStatus;
8297 }
8298 }
8299 return status;
8300}
8301
Eric Laurent59255e42011-07-27 19:49:51 -07008302void AudioFlinger::EffectModule::setSuspended(bool suspended)
8303{
8304 Mutex::Autolock _l(mLock);
8305 mSuspended = suspended;
8306}
Glenn Kastena3a85482012-01-04 11:01:11 -08008307
8308bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008309{
8310 Mutex::Autolock _l(mLock);
8311 return mSuspended;
8312}
8313
Mathias Agopian65ab4712010-07-14 17:59:35 -07008314status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8315{
8316 const size_t SIZE = 256;
8317 char buffer[SIZE];
8318 String8 result;
8319
8320 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8321 result.append(buffer);
8322
8323 bool locked = tryLock(mLock);
8324 // failed to lock - AudioFlinger is probably deadlocked
8325 if (!locked) {
8326 result.append("\t\tCould not lock Fx mutex:\n");
8327 }
8328
8329 result.append("\t\tSession Status State Engine:\n");
8330 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8331 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8332 result.append(buffer);
8333
8334 result.append("\t\tDescriptor:\n");
8335 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8336 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8337 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8338 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8339 result.append(buffer);
8340 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8341 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8342 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8343 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8344 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008345 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008346 mDescriptor.apiVersion,
8347 mDescriptor.flags);
8348 result.append(buffer);
8349 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8350 mDescriptor.name);
8351 result.append(buffer);
8352 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8353 mDescriptor.implementor);
8354 result.append(buffer);
8355
8356 result.append("\t\t- Input configuration:\n");
8357 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8358 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8359 (uint32_t)mConfig.inputCfg.buffer.raw,
8360 mConfig.inputCfg.buffer.frameCount,
8361 mConfig.inputCfg.samplingRate,
8362 mConfig.inputCfg.channels,
8363 mConfig.inputCfg.format);
8364 result.append(buffer);
8365
8366 result.append("\t\t- Output configuration:\n");
8367 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8368 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8369 (uint32_t)mConfig.outputCfg.buffer.raw,
8370 mConfig.outputCfg.buffer.frameCount,
8371 mConfig.outputCfg.samplingRate,
8372 mConfig.outputCfg.channels,
8373 mConfig.outputCfg.format);
8374 result.append(buffer);
8375
8376 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8377 result.append(buffer);
8378 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8379 for (size_t i = 0; i < mHandles.size(); ++i) {
8380 sp<EffectHandle> handle = mHandles[i].promote();
8381 if (handle != 0) {
8382 handle->dump(buffer, SIZE);
8383 result.append(buffer);
8384 }
8385 }
8386
8387 result.append("\n");
8388
8389 write(fd, result.string(), result.length());
8390
8391 if (locked) {
8392 mLock.unlock();
8393 }
8394
8395 return NO_ERROR;
8396}
8397
8398// ----------------------------------------------------------------------------
8399// EffectHandle implementation
8400// ----------------------------------------------------------------------------
8401
8402#undef LOG_TAG
8403#define LOG_TAG "AudioFlinger::EffectHandle"
8404
8405AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8406 const sp<AudioFlinger::Client>& client,
8407 const sp<IEffectClient>& effectClient,
8408 int32_t priority)
8409 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008410 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008411 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008412{
Steve Block3856b092011-10-20 11:56:00 +01008413 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008414
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008415 if (client == 0) {
8416 return;
8417 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008418 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8419 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8420 if (mCblkMemory != 0) {
8421 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8422
Glenn Kastena0d68332012-01-27 16:47:15 -08008423 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008424 new(mCblk) effect_param_cblk_t();
8425 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008426 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008427 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008428 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008429 return;
8430 }
8431}
8432
8433AudioFlinger::EffectHandle::~EffectHandle()
8434{
Steve Block3856b092011-10-20 11:56:00 +01008435 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008436 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01008437 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008438}
8439
8440status_t AudioFlinger::EffectHandle::enable()
8441{
Steve Block3856b092011-10-20 11:56:00 +01008442 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008443 if (!mHasControl) return INVALID_OPERATION;
8444 if (mEffect == 0) return DEAD_OBJECT;
8445
Eric Laurentdb7c0792011-08-10 10:37:50 -07008446 if (mEnabled) {
8447 return NO_ERROR;
8448 }
8449
Eric Laurent59255e42011-07-27 19:49:51 -07008450 mEnabled = true;
8451
8452 sp<ThreadBase> thread = mEffect->thread().promote();
8453 if (thread != 0) {
8454 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8455 }
8456
8457 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8458 if (mEffect->suspended()) {
8459 return NO_ERROR;
8460 }
8461
Eric Laurentdb7c0792011-08-10 10:37:50 -07008462 status_t status = mEffect->setEnabled(true);
8463 if (status != NO_ERROR) {
8464 if (thread != 0) {
8465 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8466 }
8467 mEnabled = false;
8468 }
8469 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008470}
8471
8472status_t AudioFlinger::EffectHandle::disable()
8473{
Steve Block3856b092011-10-20 11:56:00 +01008474 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008475 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008476 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008477
Eric Laurentdb7c0792011-08-10 10:37:50 -07008478 if (!mEnabled) {
8479 return NO_ERROR;
8480 }
Eric Laurent59255e42011-07-27 19:49:51 -07008481 mEnabled = false;
8482
8483 if (mEffect->suspended()) {
8484 return NO_ERROR;
8485 }
8486
8487 status_t status = mEffect->setEnabled(false);
8488
8489 sp<ThreadBase> thread = mEffect->thread().promote();
8490 if (thread != 0) {
8491 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8492 }
8493
8494 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008495}
8496
8497void AudioFlinger::EffectHandle::disconnect()
8498{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008499 disconnect(true);
8500}
8501
Glenn Kasten58123c32012-02-03 10:32:24 -08008502void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008503{
Glenn Kasten58123c32012-02-03 10:32:24 -08008504 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008505 if (mEffect == 0) {
8506 return;
8507 }
Glenn Kasten58123c32012-02-03 10:32:24 -08008508 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07008509
Eric Laurenta85a74a2011-10-19 11:44:54 -07008510 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008511 sp<ThreadBase> thread = mEffect->thread().promote();
8512 if (thread != 0) {
8513 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8514 }
Eric Laurent59255e42011-07-27 19:49:51 -07008515 }
8516
Mathias Agopian65ab4712010-07-14 17:59:35 -07008517 // release sp on module => module destructor can be called now
8518 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008519 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008520 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008521 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008522 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8523 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008524 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008525 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008526 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8527 mClient.clear();
8528 }
8529}
8530
Eric Laurent25f43952010-07-28 05:40:18 -07008531status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8532 uint32_t cmdSize,
8533 void *pCmdData,
8534 uint32_t *replySize,
8535 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008536{
Steve Block3856b092011-10-20 11:56:00 +01008537// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008538// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008539
8540 // only get parameter command is permitted for applications not controlling the effect
8541 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8542 return INVALID_OPERATION;
8543 }
8544 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008545 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008546
8547 // handle commands that are not forwarded transparently to effect engine
8548 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8549 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8550 // no risk to block the whole media server process or mixer threads is we are stuck here
8551 Mutex::Autolock _l(mCblk->lock);
8552 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8553 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8554 mCblk->serverIndex = 0;
8555 mCblk->clientIndex = 0;
8556 return BAD_VALUE;
8557 }
8558 status_t status = NO_ERROR;
8559 while (mCblk->serverIndex < mCblk->clientIndex) {
8560 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008561 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008562 int *p = (int *)(mBuffer + mCblk->serverIndex);
8563 int size = *p++;
8564 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008565 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008566 break;
8567 }
8568 effect_param_t *param = (effect_param_t *)p;
8569 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008570 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008571 mCblk->serverIndex += size;
8572 continue;
8573 }
Eric Laurent25f43952010-07-28 05:40:18 -07008574 uint32_t psize = sizeof(effect_param_t) +
8575 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8576 param->vsize;
8577 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8578 psize,
8579 p,
8580 &rsize,
8581 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008582 // stop at first error encountered
8583 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008584 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008585 *(int *)pReplyData = reply;
8586 break;
8587 } else if (reply != NO_ERROR) {
8588 *(int *)pReplyData = reply;
8589 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008590 }
8591 mCblk->serverIndex += size;
8592 }
8593 mCblk->serverIndex = 0;
8594 mCblk->clientIndex = 0;
8595 return status;
8596 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008597 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008598 return enable();
8599 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008600 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008601 return disable();
8602 }
8603
8604 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8605}
8606
Eric Laurent59255e42011-07-27 19:49:51 -07008607void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008608{
Steve Block3856b092011-10-20 11:56:00 +01008609 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008610
8611 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008612 mEnabled = enabled;
8613
Mathias Agopian65ab4712010-07-14 17:59:35 -07008614 if (signal && mEffectClient != 0) {
8615 mEffectClient->controlStatusChanged(hasControl);
8616 }
8617}
8618
Eric Laurent25f43952010-07-28 05:40:18 -07008619void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8620 uint32_t cmdSize,
8621 void *pCmdData,
8622 uint32_t replySize,
8623 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008624{
8625 if (mEffectClient != 0) {
8626 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8627 }
8628}
8629
8630
8631
8632void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8633{
8634 if (mEffectClient != 0) {
8635 mEffectClient->enableStatusChanged(enabled);
8636 }
8637}
8638
8639status_t AudioFlinger::EffectHandle::onTransact(
8640 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8641{
8642 return BnEffect::onTransact(code, data, reply, flags);
8643}
8644
8645
8646void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8647{
Glenn Kastena0d68332012-01-27 16:47:15 -08008648 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008649
8650 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008651 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008652 mPriority,
8653 mHasControl,
8654 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008655 mCblk ? mCblk->clientIndex : 0,
8656 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008657 );
8658
8659 if (locked) {
8660 mCblk->lock.unlock();
8661 }
8662}
8663
8664#undef LOG_TAG
8665#define LOG_TAG "AudioFlinger::EffectChain"
8666
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008667AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008668 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008669 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008670 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8671 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008672{
Dima Zavinfce7a472011-04-19 22:30:36 -07008673 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008674 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008675 return;
8676 }
8677 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8678 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008679}
8680
8681AudioFlinger::EffectChain::~EffectChain()
8682{
8683 if (mOwnInBuffer) {
8684 delete mInBuffer;
8685 }
8686
8687}
8688
Eric Laurent59255e42011-07-27 19:49:51 -07008689// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008690sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008691{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008692 size_t size = mEffects.size();
8693
8694 for (size_t i = 0; i < size; i++) {
8695 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008696 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008697 }
8698 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008699 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008700}
8701
Eric Laurent59255e42011-07-27 19:49:51 -07008702// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008703sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008704{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008705 size_t size = mEffects.size();
8706
8707 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07008708 // by convention, return first effect if id provided is 0 (0 is never a valid id)
8709 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008710 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008711 }
8712 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008713 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008714}
8715
Eric Laurent59255e42011-07-27 19:49:51 -07008716// getEffectFromType_l() must be called with ThreadBase::mLock held
8717sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
8718 const effect_uuid_t *type)
8719{
Eric Laurent59255e42011-07-27 19:49:51 -07008720 size_t size = mEffects.size();
8721
8722 for (size_t i = 0; i < size; i++) {
8723 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008724 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07008725 }
8726 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008727 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008728}
8729
Mathias Agopian65ab4712010-07-14 17:59:35 -07008730// Must be called with EffectChain::mLock locked
8731void AudioFlinger::EffectChain::process_l()
8732{
Eric Laurentdac69112010-09-28 14:09:57 -07008733 sp<ThreadBase> thread = mThread.promote();
8734 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008735 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07008736 return;
8737 }
Dima Zavinfce7a472011-04-19 22:30:36 -07008738 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
8739 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08008740 // always process effects unless no more tracks are on the session and the effect tail
8741 // has been rendered
8742 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07008743 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008744 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07008745
Eric Laurent544fe9b2011-11-11 15:42:52 -08008746 if (!tracksOnSession && mTailBufferCount == 0) {
8747 doProcess = false;
8748 }
8749
8750 if (activeTrackCnt() == 0) {
8751 // if no track is active and the effect tail has not been rendered,
8752 // the input buffer must be cleared here as the mixer process will not do it
8753 if (tracksOnSession || mTailBufferCount > 0) {
8754 size_t numSamples = thread->frameCount() * thread->channelCount();
8755 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
8756 if (mTailBufferCount > 0) {
8757 mTailBufferCount--;
8758 }
8759 }
8760 }
Eric Laurentdac69112010-09-28 14:09:57 -07008761 }
8762
Mathias Agopian65ab4712010-07-14 17:59:35 -07008763 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08008764 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07008765 for (size_t i = 0; i < size; i++) {
8766 mEffects[i]->process();
8767 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008768 }
8769 for (size_t i = 0; i < size; i++) {
8770 mEffects[i]->updateState();
8771 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008772}
8773
Eric Laurentcab11242010-07-15 12:50:15 -07008774// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07008775status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008776{
8777 effect_descriptor_t desc = effect->desc();
8778 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
8779
8780 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07008781 effect->setChain(this);
8782 sp<ThreadBase> thread = mThread.promote();
8783 if (thread == 0) {
8784 return NO_INIT;
8785 }
8786 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008787
8788 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8789 // Auxiliary effects are inserted at the beginning of mEffects vector as
8790 // they are processed first and accumulated in chain input buffer
8791 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07008792
Mathias Agopian65ab4712010-07-14 17:59:35 -07008793 // the input buffer for auxiliary effect contains mono samples in
8794 // 32 bit format. This is to avoid saturation in AudoMixer
8795 // accumulation stage. Saturation is done in EffectModule::process() before
8796 // calling the process in effect engine
8797 size_t numSamples = thread->frameCount();
8798 int32_t *buffer = new int32_t[numSamples];
8799 memset(buffer, 0, numSamples * sizeof(int32_t));
8800 effect->setInBuffer((int16_t *)buffer);
8801 // auxiliary effects output samples to chain input buffer for further processing
8802 // by insert effects
8803 effect->setOutBuffer(mInBuffer);
8804 } else {
8805 // Insert effects are inserted at the end of mEffects vector as they are processed
8806 // after track and auxiliary effects.
8807 // Insert effect order as a function of indicated preference:
8808 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8809 // another effect is present
8810 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8811 // last effect claiming first position
8812 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8813 // first effect claiming last position
8814 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8815 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8816 // already present
8817
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008818 size_t size = mEffects.size();
8819 size_t idx_insert = size;
8820 ssize_t idx_insert_first = -1;
8821 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008822
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008823 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008824 effect_descriptor_t d = mEffects[i]->desc();
8825 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8826 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8827 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8828 // check invalid effect chaining combinations
8829 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8830 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008831 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008832 return INVALID_OPERATION;
8833 }
8834 // remember position of first insert effect and by default
8835 // select this as insert position for new effect
8836 if (idx_insert == size) {
8837 idx_insert = i;
8838 }
8839 // remember position of last insert effect claiming
8840 // first position
8841 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8842 idx_insert_first = i;
8843 }
8844 // remember position of first insert effect claiming
8845 // last position
8846 if (iPref == EFFECT_FLAG_INSERT_LAST &&
8847 idx_insert_last == -1) {
8848 idx_insert_last = i;
8849 }
8850 }
8851 }
8852
8853 // modify idx_insert from first position if needed
8854 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8855 if (idx_insert_last != -1) {
8856 idx_insert = idx_insert_last;
8857 } else {
8858 idx_insert = size;
8859 }
8860 } else {
8861 if (idx_insert_first != -1) {
8862 idx_insert = idx_insert_first + 1;
8863 }
8864 }
8865
8866 // always read samples from chain input buffer
8867 effect->setInBuffer(mInBuffer);
8868
8869 // if last effect in the chain, output samples to chain
8870 // output buffer, otherwise to chain input buffer
8871 if (idx_insert == size) {
8872 if (idx_insert != 0) {
8873 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
8874 mEffects[idx_insert-1]->configure();
8875 }
8876 effect->setOutBuffer(mOutBuffer);
8877 } else {
8878 effect->setOutBuffer(mInBuffer);
8879 }
8880 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008881
Steve Block3856b092011-10-20 11:56:00 +01008882 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008883 }
8884 effect->configure();
8885 return NO_ERROR;
8886}
8887
Eric Laurentcab11242010-07-15 12:50:15 -07008888// removeEffect_l() must be called with PlaybackThread::mLock held
8889size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008890{
8891 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008892 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008893 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
8894
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008895 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008896 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07008897 // calling stop here will remove pre-processing effect from the audio HAL.
8898 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
8899 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07008900 if (mEffects[i]->state() == EffectModule::ACTIVE ||
8901 mEffects[i]->state() == EffectModule::STOPPING) {
8902 mEffects[i]->stop();
8903 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008904 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
8905 delete[] effect->inBuffer();
8906 } else {
8907 if (i == size - 1 && i != 0) {
8908 mEffects[i - 1]->setOutBuffer(mOutBuffer);
8909 mEffects[i - 1]->configure();
8910 }
8911 }
8912 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01008913 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008914 break;
8915 }
8916 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008917
8918 return mEffects.size();
8919}
8920
Eric Laurentcab11242010-07-15 12:50:15 -07008921// setDevice_l() must be called with PlaybackThread::mLock held
8922void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008923{
8924 size_t size = mEffects.size();
8925 for (size_t i = 0; i < size; i++) {
8926 mEffects[i]->setDevice(device);
8927 }
8928}
8929
Eric Laurentcab11242010-07-15 12:50:15 -07008930// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08008931void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008932{
8933 size_t size = mEffects.size();
8934 for (size_t i = 0; i < size; i++) {
8935 mEffects[i]->setMode(mode);
8936 }
8937}
8938
Eric Laurentcab11242010-07-15 12:50:15 -07008939// setVolume_l() must be called with PlaybackThread::mLock held
8940bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008941{
8942 uint32_t newLeft = *left;
8943 uint32_t newRight = *right;
8944 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07008945 int ctrlIdx = -1;
8946 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008947
Eric Laurentcab11242010-07-15 12:50:15 -07008948 // first update volume controller
8949 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07008950 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07008951 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
8952 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07008953 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07008954 break;
8955 }
8956 }
8957
8958 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07008959 if (hasControl) {
8960 *left = mNewLeftVolume;
8961 *right = mNewRightVolume;
8962 }
8963 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07008964 }
8965
8966 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07008967 mLeftVolume = newLeft;
8968 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008969
8970 // second get volume update from volume controller
8971 if (ctrlIdx >= 0) {
8972 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07008973 mNewLeftVolume = newLeft;
8974 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008975 }
8976 // then indicate volume to all other effects in chain.
8977 // Pass altered volume to effects before volume controller
8978 // and requested volume to effects after controller
8979 uint32_t lVol = newLeft;
8980 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07008981
Mathias Agopian65ab4712010-07-14 17:59:35 -07008982 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07008983 if ((int)i == ctrlIdx) continue;
8984 // this also works for ctrlIdx == -1 when there is no volume controller
8985 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008986 lVol = *left;
8987 rVol = *right;
8988 }
8989 mEffects[i]->setVolume(&lVol, &rVol, false);
8990 }
8991 *left = newLeft;
8992 *right = newRight;
8993
8994 return hasControl;
8995}
8996
Mathias Agopian65ab4712010-07-14 17:59:35 -07008997status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
8998{
8999 const size_t SIZE = 256;
9000 char buffer[SIZE];
9001 String8 result;
9002
9003 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9004 result.append(buffer);
9005
9006 bool locked = tryLock(mLock);
9007 // failed to lock - AudioFlinger is probably deadlocked
9008 if (!locked) {
9009 result.append("\tCould not lock mutex:\n");
9010 }
9011
Eric Laurentcab11242010-07-15 12:50:15 -07009012 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9013 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009014 mEffects.size(),
9015 (uint32_t)mInBuffer,
9016 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009017 mActiveTrackCnt);
9018 result.append(buffer);
9019 write(fd, result.string(), result.size());
9020
9021 for (size_t i = 0; i < mEffects.size(); ++i) {
9022 sp<EffectModule> effect = mEffects[i];
9023 if (effect != 0) {
9024 effect->dump(fd, args);
9025 }
9026 }
9027
9028 if (locked) {
9029 mLock.unlock();
9030 }
9031
9032 return NO_ERROR;
9033}
9034
Eric Laurent59255e42011-07-27 19:49:51 -07009035// must be called with ThreadBase::mLock held
9036void AudioFlinger::EffectChain::setEffectSuspended_l(
9037 const effect_uuid_t *type, bool suspend)
9038{
9039 sp<SuspendedEffectDesc> desc;
9040 // use effect type UUID timelow as key as there is no real risk of identical
9041 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009042 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009043 if (suspend) {
9044 if (index >= 0) {
9045 desc = mSuspendedEffects.valueAt(index);
9046 } else {
9047 desc = new SuspendedEffectDesc();
9048 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9049 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009050 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009051 }
9052 if (desc->mRefCount++ == 0) {
9053 sp<EffectModule> effect = getEffectIfEnabled(type);
9054 if (effect != 0) {
9055 desc->mEffect = effect;
9056 effect->setSuspended(true);
9057 effect->setEnabled(false);
9058 }
9059 }
9060 } else {
9061 if (index < 0) {
9062 return;
9063 }
9064 desc = mSuspendedEffects.valueAt(index);
9065 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009066 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009067 desc->mRefCount = 1;
9068 }
9069 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009070 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009071 if (desc->mEffect != 0) {
9072 sp<EffectModule> effect = desc->mEffect.promote();
9073 if (effect != 0) {
9074 effect->setSuspended(false);
9075 sp<EffectHandle> handle = effect->controlHandle();
9076 if (handle != 0) {
9077 effect->setEnabled(handle->enabled());
9078 }
9079 }
9080 desc->mEffect.clear();
9081 }
9082 mSuspendedEffects.removeItemsAt(index);
9083 }
9084 }
9085}
9086
9087// must be called with ThreadBase::mLock held
9088void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9089{
9090 sp<SuspendedEffectDesc> desc;
9091
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009092 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009093 if (suspend) {
9094 if (index >= 0) {
9095 desc = mSuspendedEffects.valueAt(index);
9096 } else {
9097 desc = new SuspendedEffectDesc();
9098 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009099 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009100 }
9101 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009102 Vector< sp<EffectModule> > effects;
9103 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009104 for (size_t i = 0; i < effects.size(); i++) {
9105 setEffectSuspended_l(&effects[i]->desc().type, true);
9106 }
9107 }
9108 } else {
9109 if (index < 0) {
9110 return;
9111 }
9112 desc = mSuspendedEffects.valueAt(index);
9113 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009114 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009115 desc->mRefCount = 1;
9116 }
9117 if (--desc->mRefCount == 0) {
9118 Vector<const effect_uuid_t *> types;
9119 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9120 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9121 continue;
9122 }
9123 types.add(&mSuspendedEffects.valueAt(i)->mType);
9124 }
9125 for (size_t i = 0; i < types.size(); i++) {
9126 setEffectSuspended_l(types[i], false);
9127 }
Steve Block3856b092011-10-20 11:56:00 +01009128 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009129 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9130 }
9131 }
9132}
9133
Eric Laurent6bffdb82011-09-23 08:40:41 -07009134
9135// The volume effect is used for automated tests only
9136#ifndef OPENSL_ES_H_
9137static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9138 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9139const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9140#endif //OPENSL_ES_H_
9141
Eric Laurentdb7c0792011-08-10 10:37:50 -07009142bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9143{
9144 // auxiliary effects and visualizer are never suspended on output mix
9145 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9146 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009147 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9148 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009149 return false;
9150 }
9151 return true;
9152}
9153
Glenn Kastend0539712012-01-30 12:56:03 -08009154void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009155{
Glenn Kastend0539712012-01-30 12:56:03 -08009156 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009157 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009158 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9159 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009160 }
Eric Laurent59255e42011-07-27 19:49:51 -07009161 }
Eric Laurent59255e42011-07-27 19:49:51 -07009162}
9163
9164sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9165 const effect_uuid_t *type)
9166{
Glenn Kasten090f0192012-01-30 13:00:02 -08009167 sp<EffectModule> effect = getEffectFromType_l(type);
9168 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009169}
9170
9171void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9172 bool enabled)
9173{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009174 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009175 if (enabled) {
9176 if (index < 0) {
9177 // if the effect is not suspend check if all effects are suspended
9178 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9179 if (index < 0) {
9180 return;
9181 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009182 if (!isEffectEligibleForSuspend(effect->desc())) {
9183 return;
9184 }
Eric Laurent59255e42011-07-27 19:49:51 -07009185 setEffectSuspended_l(&effect->desc().type, enabled);
9186 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009187 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009188 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009189 return;
9190 }
Eric Laurent59255e42011-07-27 19:49:51 -07009191 }
Steve Block3856b092011-10-20 11:56:00 +01009192 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009193 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009194 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9195 // if effect is requested to suspended but was not yet enabled, supend it now.
9196 if (desc->mEffect == 0) {
9197 desc->mEffect = effect;
9198 effect->setEnabled(false);
9199 effect->setSuspended(true);
9200 }
9201 } else {
9202 if (index < 0) {
9203 return;
9204 }
Steve Block3856b092011-10-20 11:56:00 +01009205 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009206 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009207 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9208 desc->mEffect.clear();
9209 effect->setSuspended(false);
9210 }
9211}
9212
Mathias Agopian65ab4712010-07-14 17:59:35 -07009213#undef LOG_TAG
9214#define LOG_TAG "AudioFlinger"
9215
9216// ----------------------------------------------------------------------------
9217
9218status_t AudioFlinger::onTransact(
9219 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9220{
9221 return BnAudioFlinger::onTransact(code, data, reply, flags);
9222}
9223
Mathias Agopian65ab4712010-07-14 17:59:35 -07009224}; // namespace android