blob: 51a836751cfb81f8f1a6b8c6ca82e7bb4b053bb7 [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.
Eric Laurent808e7d12012-05-11 19:44:09 -07001468 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1469 // global effects
1470 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001471 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1472 }
1473 }
Eric Laurent59255e42011-07-27 19:49:51 -07001474
1475 sp<EffectChain> chain = getEffectChain_l(sessionId);
1476 if (chain != 0) {
1477 chain->checkSuspendOnEffectEnabled(effect, enabled);
1478 }
1479}
1480
Mathias Agopian65ab4712010-07-14 17:59:35 -07001481// ----------------------------------------------------------------------------
1482
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001483AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1484 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001485 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001486 uint32_t device,
1487 type_t type)
1488 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001489 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1490 // Assumes constructor is called by AudioFlinger with it's mLock held,
1491 // but it would be safer to explicitly pass initial masterMute as parameter
1492 mMasterMute(audioFlinger->masterMute_l()),
1493 // mStreamTypes[] initialized in constructor body
1494 mOutput(output),
1495 // Assumes constructor is called by AudioFlinger with it's mLock held,
1496 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001497 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001498 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001499 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001500 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001501 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten288ed212012-04-25 17:52:27 -07001502 // index 0 is reserved for normal mixer's submix
1503 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001504{
Glenn Kasten480b4682012-02-28 12:30:08 -08001505 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001506
Mathias Agopian65ab4712010-07-14 17:59:35 -07001507 readOutputParameters();
1508
Glenn Kasten263709e2012-01-06 08:40:01 -08001509 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001510 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1511 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1512 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001513 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1514 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001515 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001516 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1517 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001518}
1519
1520AudioFlinger::PlaybackThread::~PlaybackThread()
1521{
1522 delete [] mMixBuffer;
1523}
1524
1525status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1526{
1527 dumpInternals(fd, args);
1528 dumpTracks(fd, args);
1529 dumpEffectChains(fd, args);
1530 return NO_ERROR;
1531}
1532
1533status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1534{
1535 const size_t SIZE = 256;
1536 char buffer[SIZE];
1537 String8 result;
1538
Glenn Kasten58912562012-04-03 10:45:00 -07001539 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1540 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1541 const stream_type_t *st = &mStreamTypes[i];
1542 if (i > 0) {
1543 result.appendFormat(", ");
1544 }
1545 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1546 if (st->mute) {
1547 result.append("M");
1548 }
1549 }
1550 result.append("\n");
1551 write(fd, result.string(), result.length());
1552 result.clear();
1553
Mathias Agopian65ab4712010-07-14 17:59:35 -07001554 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1555 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001556 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001557 for (size_t i = 0; i < mTracks.size(); ++i) {
1558 sp<Track> track = mTracks[i];
1559 if (track != 0) {
1560 track->dump(buffer, SIZE);
1561 result.append(buffer);
1562 }
1563 }
1564
1565 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1566 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001567 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001569 sp<Track> track = mActiveTracks[i].promote();
1570 if (track != 0) {
1571 track->dump(buffer, SIZE);
1572 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001573 }
1574 }
1575 write(fd, result.string(), result.size());
1576 return NO_ERROR;
1577}
1578
Mathias Agopian65ab4712010-07-14 17:59:35 -07001579status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1580{
1581 const size_t SIZE = 256;
1582 char buffer[SIZE];
1583 String8 result;
1584
1585 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1586 result.append(buffer);
1587 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1588 result.append(buffer);
1589 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1590 result.append(buffer);
1591 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1592 result.append(buffer);
1593 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1594 result.append(buffer);
1595 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1596 result.append(buffer);
1597 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1598 result.append(buffer);
1599 write(fd, result.string(), result.size());
1600
1601 dumpBase(fd, args);
1602
1603 return NO_ERROR;
1604}
1605
1606// Thread virtuals
1607status_t AudioFlinger::PlaybackThread::readyToRun()
1608{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001609 status_t status = initCheck();
1610 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001611 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001612 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001613 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001615 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001616}
1617
1618void AudioFlinger::PlaybackThread::onFirstRef()
1619{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001620 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001621}
1622
1623// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001624sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001625 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001626 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001627 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001628 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001629 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001630 int frameCount,
1631 const sp<IMemory>& sharedBuffer,
1632 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001633 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001634 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001635 status_t *status)
1636{
1637 sp<Track> track;
1638 status_t lStatus;
1639
Glenn Kasten73d22752012-03-19 13:38:30 -07001640 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1641
1642 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001643 if (flags & IAudioFlinger::TRACK_FAST) {
1644 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001645 // not timed
1646 (!isTimed) &&
1647 // either of these use cases:
1648 (
1649 // use case 1: shared buffer with any frame count
1650 (
1651 (sharedBuffer != 0)
1652 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001653 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001654 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001655 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001656 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001657 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001658 )
1659 ) &&
1660 // PCM data
1661 audio_is_linear_pcm(format) &&
1662 // mono or stereo
1663 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1664 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001665#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001666 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001667 (sampleRate == mSampleRate) &&
1668#endif
1669 // normal mixer has an associated fast mixer
1670 hasFastMixer() &&
1671 // there are sufficient fast track slots available
1672 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001673 // FIXME test that MixerThread for this fast track has a capable output HAL
1674 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001675 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001676 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1677 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001678 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001679 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001680 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001681 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001682 } else {
1683 ALOGW("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001684 "mFrameCount=%d format=%d isLinear=%d channelMask=%d sampleRate=%d mSampleRate=%d "
1685 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1686 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1687 audio_is_linear_pcm(format),
1688 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001689 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001690 // For compatibility with AudioTrack calculation, buffer depth is forced
1691 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1692 // This is probably too conservative, but legacy application code may depend on it.
1693 // If you change this calculation, also review the start threshold which is related.
1694 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1695 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1696 if (minBufCount < 2) {
1697 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001698 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001699 int minFrameCount = mNormalFrameCount * minBufCount;
1700 if (frameCount < minFrameCount) {
1701 frameCount = minFrameCount;
1702 }
1703 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001704 }
1705
Mathias Agopian65ab4712010-07-14 17:59:35 -07001706 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001707 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1708 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001709 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001710 "for output %p with format %d",
1711 sampleRate, format, channelMask, mOutput, mFormat);
1712 lStatus = BAD_VALUE;
1713 goto Exit;
1714 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715 }
1716 } else {
1717 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1718 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001719 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001720 lStatus = BAD_VALUE;
1721 goto Exit;
1722 }
1723 }
1724
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001725 lStatus = initCheck();
1726 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001727 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728 goto Exit;
1729 }
1730
1731 { // scope for mLock
1732 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001733
1734 // all tracks in same audio session must share the same routing strategy otherwise
1735 // conflicts will happen when tracks are moved from one output to another by audio policy
1736 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001737 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001738 for (size_t i = 0; i < mTracks.size(); ++i) {
1739 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001740 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001741 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001742 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001743 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001744 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001745 lStatus = BAD_VALUE;
1746 goto Exit;
1747 }
1748 }
1749 }
1750
John Grossman4ff14ba2012-02-08 16:37:41 -08001751 if (!isTimed) {
1752 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001753 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001754 } else {
1755 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1756 channelMask, frameCount, sharedBuffer, sessionId);
1757 }
1758 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759 lStatus = NO_MEMORY;
1760 goto Exit;
1761 }
1762 mTracks.add(track);
1763
1764 sp<EffectChain> chain = getEffectChain_l(sessionId);
1765 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001766 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001767 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001768 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001769 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001770 }
1771 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001772
1773#ifdef HAVE_REQUEST_PRIORITY
1774 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1775 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1776 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1777 // so ask activity manager to do this on our behalf
1778 int err = requestPriority(callingPid, tid, 1);
1779 if (err != 0) {
1780 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1781 1, callingPid, tid, err);
1782 }
1783 }
1784#endif
1785
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786 lStatus = NO_ERROR;
1787
1788Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001789 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001790 *status = lStatus;
1791 }
1792 return track;
1793}
1794
1795uint32_t AudioFlinger::PlaybackThread::latency() const
1796{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001797 Mutex::Autolock _l(mLock);
1798 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001799 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001800 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001801 return 0;
1802 }
1803}
1804
Glenn Kasten6637baa2012-01-09 09:40:36 -08001805void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001806{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001807 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001808 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001809}
1810
Glenn Kasten6637baa2012-01-09 09:40:36 -08001811void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001812{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001813 Mutex::Autolock _l(mLock);
1814 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001815}
1816
Glenn Kasten6637baa2012-01-09 09:40:36 -08001817void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001818{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001819 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001820 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001821}
1822
Glenn Kasten6637baa2012-01-09 09:40:36 -08001823void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001824{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001825 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001826 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001827}
1828
Glenn Kastenfff6d712012-01-12 16:38:12 -08001829float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001830{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001831 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001832 return mStreamTypes[stream].volume;
1833}
1834
Mathias Agopian65ab4712010-07-14 17:59:35 -07001835// addTrack_l() must be called with ThreadBase::mLock held
1836status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1837{
1838 status_t status = ALREADY_EXISTS;
1839
1840 // set retry count for buffer fill
1841 track->mRetryCount = kMaxTrackStartupRetries;
1842 if (mActiveTracks.indexOf(track) < 0) {
1843 // the track is newly added, make sure it fills up all its
1844 // buffers before playing. This is to ensure the client will
1845 // effectively get the latency it requested.
1846 track->mFillingUpStatus = Track::FS_FILLING;
1847 track->mResetDone = false;
1848 mActiveTracks.add(track);
1849 if (track->mainBuffer() != mMixBuffer) {
1850 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1851 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001852 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001853 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001854 }
1855 }
1856
1857 status = NO_ERROR;
1858 }
1859
Steve Block3856b092011-10-20 11:56:00 +01001860 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861 mWaitWorkCV.broadcast();
1862
1863 return status;
1864}
1865
1866// destroyTrack_l() must be called with ThreadBase::mLock held
1867void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1868{
1869 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001870 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001871 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001872 removeTrack_l(track);
1873 }
1874}
1875
1876void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1877{
1878 mTracks.remove(track);
1879 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001880 // redundant as track is about to be destroyed, for dumpsys only
1881 track->mName = -1;
1882 if (track->isFastTrack()) {
1883 int index = track->mFastIndex;
1884 ALOG_ASSERT(0 < index && index < FastMixerState::kMaxFastTracks);
1885 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1886 mFastTrackAvailMask |= 1 << index;
1887 // redundant as track is about to be destroyed, for dumpsys only
1888 track->mFastIndex = -1;
1889 }
Eric Laurentb469b942011-05-09 12:09:06 -07001890 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1891 if (chain != 0) {
1892 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001893 }
1894}
1895
1896String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1897{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001898 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001899 char *s;
1900
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001901 Mutex::Autolock _l(mLock);
1902 if (initCheck() != NO_ERROR) {
1903 return out_s8;
1904 }
1905
Dima Zavin799a70e2011-04-18 16:57:27 -07001906 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001907 out_s8 = String8(s);
1908 free(s);
1909 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001910}
1911
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001912// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001913void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1914 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001915 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916
Steve Block3856b092011-10-20 11:56:00 +01001917 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918
1919 switch (event) {
1920 case AudioSystem::OUTPUT_OPENED:
1921 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001922 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001923 desc.samplingRate = mSampleRate;
1924 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001925 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926 desc.latency = latency();
1927 param2 = &desc;
1928 break;
1929
1930 case AudioSystem::STREAM_CONFIG_CHANGED:
1931 param2 = &param;
1932 case AudioSystem::OUTPUT_CLOSED:
1933 default:
1934 break;
1935 }
1936 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1937}
1938
1939void AudioFlinger::PlaybackThread::readOutputParameters()
1940{
Dima Zavin799a70e2011-04-18 16:57:27 -07001941 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001942 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1943 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001944 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001945 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001946 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07001947 if (mFrameCount & 15) {
1948 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
1949 mFrameCount);
1950 }
1951
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001952 // Calculate size of normal mix buffer relative to the HAL output buffer size
1953 uint32_t multiple = 1;
1954 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07001955 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001956 multiple = (minNormalFrameCount + mFrameCount - 1) / mFrameCount;
1957 // force multiple to be even, for compatibility with doubling of fast tracks due to HAL SRC
1958 // (it would be unusual for the normal mix buffer size to not be a multiple of fast track)
1959 // FIXME this rounding up should not be done if no HAL SRC
1960 if ((multiple > 2) && (multiple & 1)) {
1961 ++multiple;
Glenn Kasten58912562012-04-03 10:45:00 -07001962 }
Glenn Kasten58912562012-04-03 10:45:00 -07001963 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001964 mNormalFrameCount = multiple * mFrameCount;
Glenn Kasten58912562012-04-03 10:45:00 -07001965 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001966
1967 // FIXME - Current mixer implementation only supports stereo output: Always
1968 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001969 delete[] mMixBuffer;
Glenn Kasten58912562012-04-03 10:45:00 -07001970 mMixBuffer = new int16_t[mNormalFrameCount * 2];
1971 memset(mMixBuffer, 0, mNormalFrameCount * 2 * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972
Eric Laurentde070132010-07-13 04:45:46 -07001973 // force reconfiguration of effect chains and engines to take new buffer size and audio
1974 // parameters into account
1975 // Note that mLock is not held when readOutputParameters() is called from the constructor
1976 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1977 // matter.
1978 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1979 Vector< sp<EffectChain> > effectChains = mEffectChains;
1980 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001981 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001982 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001983}
1984
1985status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1986{
Glenn Kastena0d68332012-01-27 16:47:15 -08001987 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988 return BAD_VALUE;
1989 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001990 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001991 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992 return INVALID_OPERATION;
1993 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001994 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001995
Dima Zavin799a70e2011-04-18 16:57:27 -07001996 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001997}
1998
Eric Laurent39e94f82010-07-28 01:32:47 -07001999uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002000{
2001 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002002 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002003 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002004 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002005 }
2006
2007 for (size_t i = 0; i < mTracks.size(); ++i) {
2008 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002009 if (sessionId == track->sessionId() &&
2010 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002011 result |= TRACK_SESSION;
2012 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002013 }
2014 }
2015
Eric Laurent39e94f82010-07-28 01:32:47 -07002016 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002017}
2018
Eric Laurentde070132010-07-13 04:45:46 -07002019uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2020{
Dima Zavinfce7a472011-04-19 22:30:36 -07002021 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002022 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002023 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2024 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002025 }
2026 for (size_t i = 0; i < mTracks.size(); i++) {
2027 sp<Track> track = mTracks[i];
2028 if (sessionId == track->sessionId() &&
2029 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002030 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002031 }
2032 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002033 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002034}
2035
Mathias Agopian65ab4712010-07-14 17:59:35 -07002036
Glenn Kastenaed850d2012-01-26 09:46:34 -08002037AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002038{
2039 Mutex::Autolock _l(mLock);
2040 return mOutput;
2041}
2042
2043AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2044{
2045 Mutex::Autolock _l(mLock);
2046 AudioStreamOut *output = mOutput;
2047 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002048 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2049 // must push a NULL and wait for ack
2050 mOutputSink.clear();
2051 mPipeSink.clear();
2052 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002053 return output;
2054}
2055
2056// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002057audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002058{
2059 if (mOutput == NULL) {
2060 return NULL;
2061 }
2062 return &mOutput->stream->common;
2063}
2064
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002065uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002066{
2067 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
2068 // decoding and transfer time. So sleeping for half of the latency would likely cause
2069 // underruns
2070 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002071 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002072 } else {
2073 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
2074 }
2075}
2076
Eric Laurenta011e352012-03-29 15:51:43 -07002077status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2078{
2079 if (!isValidSyncEvent(event)) {
2080 return BAD_VALUE;
2081 }
2082
2083 Mutex::Autolock _l(mLock);
2084
2085 for (size_t i = 0; i < mTracks.size(); ++i) {
2086 sp<Track> track = mTracks[i];
2087 if (event->triggerSession() == track->sessionId()) {
2088 track->setSyncEvent(event);
2089 return NO_ERROR;
2090 }
2091 }
2092
2093 return NAME_NOT_FOUND;
2094}
2095
2096bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2097{
2098 switch (event->type()) {
2099 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2100 return true;
2101 default:
2102 break;
2103 }
2104 return false;
2105}
2106
Mathias Agopian65ab4712010-07-14 17:59:35 -07002107// ----------------------------------------------------------------------------
2108
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002109AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002110 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002111 : PlaybackThread(audioFlinger, output, id, device, type),
2112 // mAudioMixer below
2113#ifdef SOAKER
2114 mSoaker(NULL),
2115#endif
2116 // mFastMixer below
2117 mFastMixerFutex(0)
2118 // mOutputSink below
2119 // mPipeSink below
2120 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002121{
Glenn Kasten58912562012-04-03 10:45:00 -07002122 ALOGV("MixerThread() id=%d device=%d type=%d", id, device, type);
2123 ALOGV("mSampleRate=%d, mChannelMask=%d, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
2124 "mFrameCount=%d, mNormalFrameCount=%d",
2125 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2126 mNormalFrameCount);
2127 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2128
Mathias Agopian65ab4712010-07-14 17:59:35 -07002129 // FIXME - Current mixer implementation only supports stereo output
2130 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00002131 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002132 }
Glenn Kasten58912562012-04-03 10:45:00 -07002133
2134 // create an NBAIO sink for the HAL output stream, and negotiate
2135 mOutputSink = new AudioStreamOutSink(output->stream);
2136 size_t numCounterOffers = 0;
2137 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2138 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2139 ALOG_ASSERT(index == 0);
2140
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002141 // initialize fast mixer depending on configuration
2142 bool initFastMixer;
2143 switch (kUseFastMixer) {
2144 case FastMixer_Never:
2145 initFastMixer = false;
2146 break;
2147 case FastMixer_Always:
2148 initFastMixer = true;
2149 break;
2150 case FastMixer_Static:
2151 case FastMixer_Dynamic:
2152 initFastMixer = mFrameCount < mNormalFrameCount;
2153 break;
2154 }
2155 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002156
2157 // create a MonoPipe to connect our submix to FastMixer
2158 NBAIO_Format format = mOutputSink->format();
2159 // frame count will be rounded up to a power of 2, so this formula should work well
2160 MonoPipe *monoPipe = new MonoPipe((mNormalFrameCount * 3) / 2, format,
2161 true /*writeCanBlock*/);
2162 const NBAIO_Format offers[1] = {format};
2163 size_t numCounterOffers = 0;
2164 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2165 ALOG_ASSERT(index == 0);
2166 mPipeSink = monoPipe;
2167
2168#ifdef SOAKER
2169 // create a soaker as workaround for governor issues
2170 mSoaker = new Soaker();
2171 // FIXME Soaker should only run when needed, i.e. when FastMixer is not in COLD_IDLE
2172 mSoaker->run("Soaker", PRIORITY_LOWEST);
2173#endif
2174
2175 // create fast mixer and configure it initially with just one fast track for our submix
2176 mFastMixer = new FastMixer();
2177 FastMixerStateQueue *sq = mFastMixer->sq();
2178 FastMixerState *state = sq->begin();
2179 FastTrack *fastTrack = &state->mFastTracks[0];
2180 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2181 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2182 fastTrack->mVolumeProvider = NULL;
2183 fastTrack->mGeneration++;
2184 state->mFastTracksGen++;
2185 state->mTrackMask = 1;
2186 // fast mixer will use the HAL output sink
2187 state->mOutputSink = mOutputSink.get();
2188 state->mOutputSinkGen++;
2189 state->mFrameCount = mFrameCount;
2190 state->mCommand = FastMixerState::COLD_IDLE;
2191 // already done in constructor initialization list
2192 //mFastMixerFutex = 0;
2193 state->mColdFutexAddr = &mFastMixerFutex;
2194 state->mColdGen++;
2195 state->mDumpState = &mFastMixerDumpState;
2196 sq->end();
2197 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2198
2199 // start the fast mixer
2200 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
2201#ifdef HAVE_REQUEST_PRIORITY
2202 pid_t tid = mFastMixer->getTid();
2203 int err = requestPriority(getpid_cached, tid, 2);
2204 if (err != 0) {
2205 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
2206 2, getpid_cached, tid, err);
2207 }
2208#endif
2209
2210 } else {
2211 mFastMixer = NULL;
2212 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002213
2214 switch (kUseFastMixer) {
2215 case FastMixer_Never:
2216 case FastMixer_Dynamic:
2217 mNormalSink = mOutputSink;
2218 break;
2219 case FastMixer_Always:
2220 mNormalSink = mPipeSink;
2221 break;
2222 case FastMixer_Static:
2223 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2224 break;
2225 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002226}
2227
2228AudioFlinger::MixerThread::~MixerThread()
2229{
Glenn Kasten58912562012-04-03 10:45:00 -07002230 if (mFastMixer != NULL) {
2231 FastMixerStateQueue *sq = mFastMixer->sq();
2232 FastMixerState *state = sq->begin();
2233 if (state->mCommand == FastMixerState::COLD_IDLE) {
2234 int32_t old = android_atomic_inc(&mFastMixerFutex);
2235 if (old == -1) {
2236 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2237 }
2238 }
2239 state->mCommand = FastMixerState::EXIT;
2240 sq->end();
2241 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2242 mFastMixer->join();
2243 // Though the fast mixer thread has exited, it's state queue is still valid.
2244 // We'll use that extract the final state which contains one remaining fast track
2245 // corresponding to our sub-mix.
2246 state = sq->begin();
2247 ALOG_ASSERT(state->mTrackMask == 1);
2248 FastTrack *fastTrack = &state->mFastTracks[0];
2249 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2250 delete fastTrack->mBufferProvider;
2251 sq->end(false /*didModify*/);
2252 delete mFastMixer;
2253#ifdef SOAKER
2254 if (mSoaker != NULL) {
2255 mSoaker->requestExitAndWait();
2256 }
2257 delete mSoaker;
2258#endif
2259 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002260 delete mAudioMixer;
2261}
2262
Glenn Kasten83efdd02012-02-24 07:21:32 -08002263class CpuStats {
2264public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002265 CpuStats();
2266 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002267#ifdef DEBUG_CPU_USAGE
2268private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002269 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2270 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2271
2272 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2273
2274 int mCpuNum; // thread's current CPU number
2275 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002276#endif
2277};
2278
Glenn Kasten190a46f2012-03-06 11:27:10 -08002279CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002280#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002281 : mCpuNum(-1), mCpukHz(-1)
2282#endif
2283{
2284}
2285
2286void CpuStats::sample(const String8 &title) {
2287#ifdef DEBUG_CPU_USAGE
2288 // get current thread's delta CPU time in wall clock ns
2289 double wcNs;
2290 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2291
2292 // record sample for wall clock statistics
2293 if (valid) {
2294 mWcStats.sample(wcNs);
2295 }
2296
2297 // get the current CPU number
2298 int cpuNum = sched_getcpu();
2299
2300 // get the current CPU frequency in kHz
2301 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2302
2303 // check if either CPU number or frequency changed
2304 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2305 mCpuNum = cpuNum;
2306 mCpukHz = cpukHz;
2307 // ignore sample for purposes of cycles
2308 valid = false;
2309 }
2310
2311 // if no change in CPU number or frequency, then record sample for cycle statistics
2312 if (valid && mCpukHz > 0) {
2313 double cycles = wcNs * cpukHz * 0.000001;
2314 mHzStats.sample(cycles);
2315 }
2316
2317 unsigned n = mWcStats.n();
2318 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002319 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002320 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002321 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2322 double perLoop = elapsed / (double) n;
2323 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002324 double perLoop1k = perLoop * 0.001;
2325 double mean = mWcStats.mean();
2326 double stddev = mWcStats.stddev();
2327 double minimum = mWcStats.minimum();
2328 double maximum = mWcStats.maximum();
2329 double meanCycles = mHzStats.mean();
2330 double stddevCycles = mHzStats.stddev();
2331 double minCycles = mHzStats.minimum();
2332 double maxCycles = mHzStats.maximum();
2333 mCpuUsage.resetElapsed();
2334 mWcStats.reset();
2335 mHzStats.reset();
2336 ALOGD("CPU usage for %s over past %.1f secs\n"
2337 " (%u mixer loops at %.1f mean ms per loop):\n"
2338 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2339 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2340 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2341 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002342 elapsed * .000000001, n, perLoop * .000001,
2343 mean * .001,
2344 stddev * .001,
2345 minimum * .001,
2346 maximum * .001,
2347 mean / perLoop100,
2348 stddev / perLoop100,
2349 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002350 maximum / perLoop100,
2351 meanCycles / perLoop1k,
2352 stddevCycles / perLoop1k,
2353 minCycles / perLoop1k,
2354 maxCycles / perLoop1k);
2355
Glenn Kasten83efdd02012-02-24 07:21:32 -08002356 }
2357 }
2358#endif
2359};
2360
Glenn Kasten37d825e2012-02-24 07:21:48 -08002361void AudioFlinger::PlaybackThread::checkSilentMode_l()
2362{
2363 if (!mMasterMute) {
2364 char value[PROPERTY_VALUE_MAX];
2365 if (property_get("ro.audio.silent", value, "0") > 0) {
2366 char *endptr;
2367 unsigned long ul = strtoul(value, &endptr, 0);
2368 if (*endptr == '\0' && ul != 0) {
2369 ALOGD("Silence is golden");
2370 // The setprop command will not allow a property to be changed after
2371 // the first time it is set, so we don't have to worry about un-muting.
2372 setMasterMute_l(true);
2373 }
2374 }
2375 }
2376}
2377
Glenn Kasten000f0e32012-03-01 17:10:56 -08002378bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002379{
2380 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002381
Glenn Kasten000f0e32012-03-01 17:10:56 -08002382 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002383
2384 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002385 nsecs_t lastWarning = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002386if (mType == MIXER) {
2387 longStandbyExit = false;
2388}
Glenn Kasten688a6402012-02-29 07:57:06 -08002389
Glenn Kasten000f0e32012-03-01 17:10:56 -08002390 // DUPLICATING
2391 // FIXME could this be made local to while loop?
2392 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002393
Glenn Kasten66fcab92012-02-24 14:59:21 -08002394 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002395 sleepTime = idleSleepTime;
2396
2397if (mType == MIXER) {
2398 sleepTimeShift = 0;
2399}
2400
Glenn Kasten83efdd02012-02-24 07:21:32 -08002401 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002402 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002403
Eric Laurentfeb0db62011-07-22 09:04:31 -07002404 acquireWakeLock();
2405
Mathias Agopian65ab4712010-07-14 17:59:35 -07002406 while (!exitPending())
2407 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002408 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002409
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002410 Vector< sp<EffectChain> > effectChains;
2411
Mathias Agopian65ab4712010-07-14 17:59:35 -07002412 processConfigEvents();
2413
Mathias Agopian65ab4712010-07-14 17:59:35 -07002414 { // scope for mLock
2415
2416 Mutex::Autolock _l(mLock);
2417
2418 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002419 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002420 }
2421
Glenn Kastenfa26a852012-03-06 11:28:04 -08002422 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002423
Mathias Agopian65ab4712010-07-14 17:59:35 -07002424 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002425 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kastenc455fe92012-02-29 07:07:30 -08002426 mSuspended > 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002427 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002428
2429 threadLoop_standby();
2430
Mathias Agopian65ab4712010-07-14 17:59:35 -07002431 mStandby = true;
2432 mBytesWritten = 0;
2433 }
2434
Glenn Kasten3e074702012-02-28 18:40:35 -08002435 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002436 // we're about to wait, flush the binder command buffer
2437 IPCThreadState::self()->flushCommands();
2438
Glenn Kastenfa26a852012-03-06 11:28:04 -08002439 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002440
Mathias Agopian65ab4712010-07-14 17:59:35 -07002441 if (exitPending()) break;
2442
Eric Laurentfeb0db62011-07-22 09:04:31 -07002443 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002444 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002445 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002446 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002447 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002448 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002449
Eric Laurentda747442012-04-25 18:53:13 -07002450 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002451 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002452
Glenn Kasten37d825e2012-02-24 07:21:48 -08002453 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002454
Glenn Kasten000f0e32012-03-01 17:10:56 -08002455 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002456 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002457 if (mType == MIXER) {
2458 sleepTimeShift = 0;
2459 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002460
Mathias Agopian65ab4712010-07-14 17:59:35 -07002461 continue;
2462 }
2463 }
2464
Glenn Kasten81028042012-04-30 18:15:12 -07002465 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002466 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002467
2468 // prevent any changes in effect chain list and in each effect chain
2469 // during mixing and effect process as the audio buffers could be deleted
2470 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002471 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002472 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002473
Glenn Kastenfec279f2012-03-08 07:47:15 -08002474 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002475 threadLoop_mix();
2476 } else {
2477 threadLoop_sleepTime();
2478 }
2479
2480 if (mSuspended > 0) {
2481 sleepTime = suspendSleepTimeUs();
2482 }
2483
2484 // only process effects if we're going to write
2485 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002486 for (size_t i = 0; i < effectChains.size(); i ++) {
2487 effectChains[i]->process_l();
2488 }
2489 }
2490
2491 // enable changes in effect chain
2492 unlockEffectChains(effectChains);
2493
2494 // sleepTime == 0 means we must write to audio hardware
2495 if (sleepTime == 0) {
2496
2497 threadLoop_write();
2498
2499if (mType == MIXER) {
2500 // write blocked detection
2501 nsecs_t now = systemTime();
2502 nsecs_t delta = now - mLastWriteTime;
2503 if (!mStandby && delta > maxPeriod) {
2504 mNumDelayedWrites++;
2505 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002506 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten000f0e32012-03-01 17:10:56 -08002507 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2508 ns2ms(delta), mNumDelayedWrites, this);
2509 lastWarning = now;
2510 }
2511 // FIXME this is broken: longStandbyExit should be handled out of the if() and with
2512 // a different threshold. Or completely removed for what it is worth anyway...
2513 if (mStandby) {
2514 longStandbyExit = true;
2515 }
2516 }
2517}
2518
2519 mStandby = false;
2520 } else {
2521 usleep(sleepTime);
2522 }
2523
Glenn Kasten58912562012-04-03 10:45:00 -07002524 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002525 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002526 // same lock. This will also mutate and push a new fast mixer state.
2527 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002528 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002529
Glenn Kastenfa26a852012-03-06 11:28:04 -08002530 // FIXME I don't understand the need for this here;
2531 // it was in the original code but maybe the
2532 // assignment in saveOutputTracks() makes this unnecessary?
2533 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002534
2535 // Effect chains will be actually deleted here if they were removed from
2536 // mEffectChains list during mixing or effects processing
2537 effectChains.clear();
2538
2539 // FIXME Note that the above .clear() is no longer necessary since effectChains
2540 // is now local to this block, but will keep it for now (at least until merge done).
2541 }
2542
2543if (mType == MIXER || mType == DIRECT) {
2544 // put output stream into standby mode
2545 if (!mStandby) {
2546 mOutput->stream->common.standby(&mOutput->stream->common);
2547 }
2548}
2549if (mType == DUPLICATING) {
2550 // for DuplicatingThread, standby mode is handled by the outputTracks
2551}
2552
2553 releaseWakeLock();
2554
2555 ALOGV("Thread %p type %d exiting", this, mType);
2556 return false;
2557}
2558
Glenn Kasten288ed212012-04-25 17:52:27 -07002559// returns (via tracksToRemove) a set of tracks to remove.
Glenn Kasten58912562012-04-03 10:45:00 -07002560void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2561{
Glenn Kasten58912562012-04-03 10:45:00 -07002562 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2563}
2564
2565void AudioFlinger::MixerThread::threadLoop_write()
2566{
2567 // FIXME we should only do one push per cycle; confirm this is true
2568 // Start the fast mixer if it's not already running
2569 if (mFastMixer != NULL) {
2570 FastMixerStateQueue *sq = mFastMixer->sq();
2571 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002572 if (state->mCommand != FastMixerState::MIX_WRITE &&
2573 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002574 if (state->mCommand == FastMixerState::COLD_IDLE) {
2575 int32_t old = android_atomic_inc(&mFastMixerFutex);
2576 if (old == -1) {
2577 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2578 }
2579 }
2580 state->mCommand = FastMixerState::MIX_WRITE;
2581 sq->end();
2582 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002583 if (kUseFastMixer == FastMixer_Dynamic) {
2584 mNormalSink = mPipeSink;
2585 }
Glenn Kasten58912562012-04-03 10:45:00 -07002586 } else {
2587 sq->end(false /*didModify*/);
2588 }
2589 }
2590 PlaybackThread::threadLoop_write();
2591}
2592
Glenn Kasten000f0e32012-03-01 17:10:56 -08002593// shared by MIXER and DIRECT, overridden by DUPLICATING
2594void AudioFlinger::PlaybackThread::threadLoop_write()
2595{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002596 // FIXME rewrite to reduce number of system calls
2597 mLastWriteTime = systemTime();
2598 mInWrite = true;
Glenn Kasten58912562012-04-03 10:45:00 -07002599
Glenn Kasten58912562012-04-03 10:45:00 -07002600#define mBitShift 2 // FIXME
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002601 size_t count = mixBufferSize >> mBitShift;
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002602 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002603 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002604 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002605 if (framesWritten > 0) {
2606 size_t bytesWritten = framesWritten << mBitShift;
2607 mBytesWritten += bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002608 }
2609
Glenn Kasten952eeb22012-03-06 11:30:57 -08002610 mNumWrites++;
2611 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002612}
2613
Glenn Kasten58912562012-04-03 10:45:00 -07002614void AudioFlinger::MixerThread::threadLoop_standby()
2615{
2616 // Idle the fast mixer if it's currently running
2617 if (mFastMixer != NULL) {
2618 FastMixerStateQueue *sq = mFastMixer->sq();
2619 FastMixerState *state = sq->begin();
2620 if (!(state->mCommand & FastMixerState::IDLE)) {
2621 state->mCommand = FastMixerState::COLD_IDLE;
2622 state->mColdFutexAddr = &mFastMixerFutex;
2623 state->mColdGen++;
2624 mFastMixerFutex = 0;
2625 sq->end();
2626 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2627 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002628 if (kUseFastMixer == FastMixer_Dynamic) {
2629 mNormalSink = mOutputSink;
2630 }
Glenn Kasten58912562012-04-03 10:45:00 -07002631 } else {
2632 sq->end(false /*didModify*/);
2633 }
2634 }
2635 PlaybackThread::threadLoop_standby();
2636}
2637
Glenn Kasten000f0e32012-03-01 17:10:56 -08002638// shared by MIXER and DIRECT, overridden by DUPLICATING
2639void AudioFlinger::PlaybackThread::threadLoop_standby()
2640{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002641 ALOGV("Audio hardware entering standby, mixer %p, suspend count %u", this, mSuspended);
2642 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002643}
2644
2645void AudioFlinger::MixerThread::threadLoop_mix()
2646{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002647 // obtain the presentation timestamp of the next output buffer
2648 int64_t pts;
2649 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002650
Glenn Kasten952eeb22012-03-06 11:30:57 -08002651 if (NULL != mOutput->stream->get_next_write_timestamp) {
2652 status = mOutput->stream->get_next_write_timestamp(
2653 mOutput->stream, &pts);
2654 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002655
Glenn Kasten952eeb22012-03-06 11:30:57 -08002656 if (status != NO_ERROR) {
2657 pts = AudioBufferProvider::kInvalidPTS;
2658 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002659
Glenn Kasten952eeb22012-03-06 11:30:57 -08002660 // mix buffers...
2661 mAudioMixer->process(pts);
2662 // increase sleep time progressively when application underrun condition clears.
2663 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2664 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2665 // such that we would underrun the audio HAL.
2666 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2667 sleepTimeShift--;
2668 }
2669 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002670 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002671 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002672}
2673
2674void AudioFlinger::MixerThread::threadLoop_sleepTime()
2675{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002676 // If no tracks are ready, sleep once for the duration of an output
2677 // buffer size, then write 0s to the output
2678 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002679 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002680 sleepTime = activeSleepTime >> sleepTimeShift;
2681 if (sleepTime < kMinThreadSleepTimeUs) {
2682 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002683 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002684 // reduce sleep time in case of consecutive application underruns to avoid
2685 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2686 // duration we would end up writing less data than needed by the audio HAL if
2687 // the condition persists.
2688 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2689 sleepTimeShift++;
2690 }
2691 } else {
2692 sleepTime = idleSleepTime;
2693 }
2694 } else if (mBytesWritten != 0 ||
Glenn Kastenfec279f2012-03-08 07:47:15 -08002695 (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002696 memset (mMixBuffer, 0, mixBufferSize);
2697 sleepTime = 0;
Glenn Kastenfec279f2012-03-08 07:47:15 -08002698 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002699 }
2700 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002701}
2702
2703// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002704AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002705 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002706{
2707
Glenn Kasten29c23c32012-01-26 13:37:52 -08002708 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002709 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002710 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002711 size_t mixedTracks = 0;
2712 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002713 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002714 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002715 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002716
2717 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002718 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002719
Eric Laurent571d49c2010-08-11 05:20:11 -07002720 if (masterMute) {
2721 masterVolume = 0;
2722 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002723 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002724 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002725 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002726 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002727 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002728 masterVolume = (float)((v + (1 << 23)) >> 24);
2729 chain.clear();
2730 }
2731
Glenn Kasten288ed212012-04-25 17:52:27 -07002732 // prepare a new state to push
2733 FastMixerStateQueue *sq = NULL;
2734 FastMixerState *state = NULL;
2735 bool didModify = false;
2736 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2737 if (mFastMixer != NULL) {
2738 sq = mFastMixer->sq();
2739 state = sq->begin();
2740 }
2741
Mathias Agopian65ab4712010-07-14 17:59:35 -07002742 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002743 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002744 if (t == 0) continue;
2745
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002746 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002747 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002748
Glenn Kasten288ed212012-04-25 17:52:27 -07002749 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002750 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002751
2752 // It's theoretically possible (though unlikely) for a fast track to be created
2753 // and then removed within the same normal mix cycle. This is not a problem, as
2754 // the track never becomes active so it's fast mixer slot is never touched.
2755 // The converse, of removing an (active) track and then creating a new track
2756 // at the identical fast mixer slot within the same normal mix cycle,
2757 // is impossible because the slot isn't marked available until the end of each cycle.
2758 int j = track->mFastIndex;
2759 FastTrack *fastTrack = &state->mFastTracks[j];
2760
2761 // Determine whether the track is currently in underrun condition,
2762 // and whether it had a recent underrun.
Glenn Kasten09474df2012-05-10 14:48:07 -07002763 FastTrackUnderruns underruns = mFastMixerDumpState.mTracks[j].mUnderruns;
2764 uint32_t recentFull = (underruns.mBitFields.mFull -
2765 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2766 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2767 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2768 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2769 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2770 uint32_t recentUnderruns = recentPartial + recentEmpty;
2771 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002772 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002773 // or stopped which can occur when flush() is called while active
2774 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002775 track->mUnderrunCount += recentUnderruns;
2776 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002777
Glenn Kastend08f48c2012-05-01 18:14:02 -07002778 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002779 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002780 bool isActive = true;
2781 switch (track->mState) {
2782 case TrackBase::STOPPING_1:
2783 // track stays active in STOPPING_1 state until first underrun
2784 if (recentUnderruns > 0) {
2785 track->mState = TrackBase::STOPPING_2;
2786 }
2787 break;
2788 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002789 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002790 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002791 break;
2792 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002793 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002794 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002795 break;
2796 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002797 if (recentFull > 0 || recentPartial > 0) {
2798 // track has provided at least some frames recently: reset retry count
2799 track->mRetryCount = kMaxTrackRetries;
2800 }
2801 if (recentUnderruns == 0) {
2802 // no recent underruns: stay active
2803 break;
2804 }
2805 // there has recently been an underrun of some kind
2806 if (track->sharedBuffer() == 0) {
2807 // were any of the recent underruns "empty" (no frames available)?
2808 if (recentEmpty == 0) {
2809 // no, then ignore the partial underruns as they are allowed indefinitely
2810 break;
2811 }
2812 // there has recently been an "empty" underrun: decrement the retry counter
2813 if (--(track->mRetryCount) > 0) {
2814 break;
2815 }
2816 // indicate to client process that the track was disabled because of underrun;
2817 // it will then automatically call start() when data is available
2818 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2819 // remove from active list, but state remains ACTIVE [confusing but true]
2820 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002821 break;
2822 }
2823 // fall through
2824 case TrackBase::STOPPING_2:
2825 case TrackBase::PAUSED:
2826 case TrackBase::TERMINATED:
2827 case TrackBase::STOPPED: // flush() while active
2828 // Check for presentation complete if track is inactive
2829 // We have consumed all the buffers of this track.
2830 // This would be incomplete if we auto-paused on underrun
2831 {
2832 size_t audioHALFrames =
2833 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2834 size_t framesWritten =
2835 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2836 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2837 // track stays in active list until presentation is complete
2838 break;
2839 }
2840 }
2841 if (track->isStopping_2()) {
2842 track->mState = TrackBase::STOPPED;
2843 }
2844 if (track->isStopped()) {
2845 // Can't reset directly, as fast mixer is still polling this track
2846 // track->reset();
2847 // So instead mark this track as needing to be reset after push with ack
2848 resetMask |= 1 << i;
2849 }
2850 isActive = false;
2851 break;
2852 case TrackBase::IDLE:
2853 default:
2854 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07002855 }
2856
2857 if (isActive) {
2858 // was it previously inactive?
2859 if (!(state->mTrackMask & (1 << j))) {
2860 ExtendedAudioBufferProvider *eabp = track;
2861 VolumeProvider *vp = track;
2862 fastTrack->mBufferProvider = eabp;
2863 fastTrack->mVolumeProvider = vp;
2864 fastTrack->mSampleRate = track->mSampleRate;
2865 fastTrack->mChannelMask = track->mChannelMask;
2866 fastTrack->mGeneration++;
2867 state->mTrackMask |= 1 << j;
2868 didModify = true;
2869 // no acknowledgement required for newly active tracks
2870 }
2871 // cache the combined master volume and stream type volume for fast mixer; this
2872 // lacks any synchronization or barrier so VolumeProvider may read a stale value
2873 track->mCachedVolume = track->isMuted() ?
2874 0 : masterVolume * mStreamTypes[track->streamType()].volume;
2875 ++fastTracks;
2876 } else {
2877 // was it previously active?
2878 if (state->mTrackMask & (1 << j)) {
2879 fastTrack->mBufferProvider = NULL;
2880 fastTrack->mGeneration++;
2881 state->mTrackMask &= ~(1 << j);
2882 didModify = true;
2883 // If any fast tracks were removed, we must wait for acknowledgement
2884 // because we're about to decrement the last sp<> on those tracks.
2885 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002886 } else {
2887 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07002888 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07002889 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07002890 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07002891 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002892 }
2893 continue;
2894 }
2895
2896 { // local variable scope to avoid goto warning
2897
Mathias Agopian65ab4712010-07-14 17:59:35 -07002898 audio_track_cblk_t* cblk = track->cblk();
2899
2900 // The first time a track is added we wait
2901 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002902 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002903 // make sure that we have enough frames to mix one full buffer.
2904 // enforce this condition only once to enable draining the buffer in case the client
2905 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07002906 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002907 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002908 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07002909 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07002910 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002911 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07002912 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07002913 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002914 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07002915 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08002916 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07002917 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08002918 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2919 // the minimum track buffer size is normally twice the number of frames necessary
2920 // to fill one buffer and the resampler should not leave more than one buffer worth
2921 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002922 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002923 }
2924 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002925 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002926 !track->isPaused() && !track->isTerminated())
2927 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002928 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002929
2930 mixedTracks++;
2931
2932 // track->mainBuffer() != mMixBuffer means there is an effect chain
2933 // connected to the track
2934 chain.clear();
2935 if (track->mainBuffer() != mMixBuffer) {
2936 chain = getEffectChain_l(track->sessionId());
2937 // Delegate volume control to effect in track effect chain if needed
2938 if (chain != 0) {
2939 tracksWithEffect++;
2940 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002941 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002942 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002943 }
2944 }
2945
2946
2947 int param = AudioMixer::VOLUME;
2948 if (track->mFillingUpStatus == Track::FS_FILLED) {
2949 // no ramp for the first volume setting
2950 track->mFillingUpStatus = Track::FS_ACTIVE;
2951 if (track->mState == TrackBase::RESUMING) {
2952 track->mState = TrackBase::ACTIVE;
2953 param = AudioMixer::RAMP_VOLUME;
2954 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002955 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002956 } else if (cblk->server != 0) {
2957 // If the track is stopped before the first frame was mixed,
2958 // do not apply ramp
2959 param = AudioMixer::RAMP_VOLUME;
2960 }
2961
2962 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002963 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002964 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002965 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002966 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002967 if (track->isPausing()) {
2968 track->setPaused();
2969 }
2970 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002971
Mathias Agopian65ab4712010-07-14 17:59:35 -07002972 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002973 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002974 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002975 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002976 vl = vlr & 0xFFFF;
2977 vr = vlr >> 16;
2978 // track volumes come from shared memory, so can't be trusted and must be clamped
2979 if (vl > MAX_GAIN_INT) {
2980 ALOGV("Track left volume out of range: %04X", vl);
2981 vl = MAX_GAIN_INT;
2982 }
2983 if (vr > MAX_GAIN_INT) {
2984 ALOGV("Track right volume out of range: %04X", vr);
2985 vr = MAX_GAIN_INT;
2986 }
2987 // now apply the master volume and stream type volume
2988 vl = (uint32_t)(v * vl) << 12;
2989 vr = (uint32_t)(v * vr) << 12;
2990 // assuming master volume and stream type volume each go up to 1.0,
2991 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002992
Glenn Kasten05632a52012-01-03 14:22:33 -08002993 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2994 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08002995 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002996 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002997 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002998 }
2999 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003000 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003001 // Delegate volume control to effect in track effect chain if needed
3002 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3003 // Do not ramp volume if volume is controlled by effect
3004 param = AudioMixer::VOLUME;
3005 track->mHasVolumeController = true;
3006 } else {
3007 // force no volume ramp when volume controller was just disabled or removed
3008 // from effect chain to avoid volume spike
3009 if (track->mHasVolumeController) {
3010 param = AudioMixer::VOLUME;
3011 }
3012 track->mHasVolumeController = false;
3013 }
3014
3015 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003016 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003017 vl = (vl + (1 << 11)) >> 12;
3018 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3019 vr = (vr + (1 << 11)) >> 12;
3020 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003021
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003022 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 -07003023
Mathias Agopian65ab4712010-07-14 17:59:35 -07003024 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003025 mAudioMixer->setBufferProvider(name, track);
3026 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003027
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003028 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3029 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3030 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003031 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003032 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003033 AudioMixer::TRACK,
3034 AudioMixer::FORMAT, (void *)track->format());
3035 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003036 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003037 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003038 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003039 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003040 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003041 AudioMixer::RESAMPLE,
3042 AudioMixer::SAMPLE_RATE,
3043 (void *)(cblk->sampleRate));
3044 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003045 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003046 AudioMixer::TRACK,
3047 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3048 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003049 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003050 AudioMixer::TRACK,
3051 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3052
3053 // reset retry count
3054 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003055
Eric Laurent27741442012-01-17 19:20:12 -08003056 // If one track is ready, set the mixer ready if:
3057 // - the mixer was not ready during previous round OR
3058 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003059 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003060 mixerStatus != MIXER_TRACKS_ENABLED) {
3061 mixerStatus = MIXER_TRACKS_READY;
3062 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003063 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003064 //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 -07003065 if (track->isStopped()) {
3066 track->reset();
3067 }
Eric Laurent83faee02012-04-27 18:24:29 -07003068 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3069 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003070 // We have consumed all the buffers of this track.
3071 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003072 // TODO: use actual buffer filling status instead of latency when available from
3073 // audio HAL
3074 size_t audioHALFrames =
3075 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3076 size_t framesWritten =
3077 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3078 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3079 tracksToRemove->add(track);
3080 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003081 } else {
3082 // No buffers for this track. Give it a few chances to
3083 // fill a buffer, then remove it from active list.
3084 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003085 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003086 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003087 // indicate to client process that the track was disabled because of underrun;
3088 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003089 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003090 // If one track is not ready, mark the mixer also not ready if:
3091 // - the mixer was ready during previous round OR
3092 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003093 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003094 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003095 mixerStatus = MIXER_TRACKS_ENABLED;
3096 }
3097 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003098 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003099 }
Glenn Kasten58912562012-04-03 10:45:00 -07003100
3101 } // local variable scope to avoid goto warning
3102track_is_ready: ;
3103
Mathias Agopian65ab4712010-07-14 17:59:35 -07003104 }
3105
Glenn Kasten288ed212012-04-25 17:52:27 -07003106 // Push the new FastMixer state if necessary
3107 if (didModify) {
3108 state->mFastTracksGen++;
3109 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3110 if (kUseFastMixer == FastMixer_Dynamic &&
3111 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3112 state->mCommand = FastMixerState::COLD_IDLE;
3113 state->mColdFutexAddr = &mFastMixerFutex;
3114 state->mColdGen++;
3115 mFastMixerFutex = 0;
3116 if (kUseFastMixer == FastMixer_Dynamic) {
3117 mNormalSink = mOutputSink;
3118 }
3119 // If we go into cold idle, need to wait for acknowledgement
3120 // so that fast mixer stops doing I/O.
3121 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
3122 }
3123 sq->end();
3124 }
3125 if (sq != NULL) {
3126 sq->end(didModify);
3127 sq->push(block);
3128 }
3129
3130 // Now perform the deferred reset on fast tracks that have stopped
3131 while (resetMask != 0) {
3132 size_t i = __builtin_ctz(resetMask);
3133 ALOG_ASSERT(i < count);
3134 resetMask &= ~(1 << i);
3135 sp<Track> t = mActiveTracks[i].promote();
3136 if (t == 0) continue;
3137 Track* track = t.get();
3138 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3139 track->reset();
3140 }
Glenn Kasten58912562012-04-03 10:45:00 -07003141
Mathias Agopian65ab4712010-07-14 17:59:35 -07003142 // remove all the tracks that need to be...
3143 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003144 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003145 for (size_t i=0 ; i<count ; i++) {
3146 const sp<Track>& track = tracksToRemove->itemAt(i);
3147 mActiveTracks.remove(track);
3148 if (track->mainBuffer() != mMixBuffer) {
3149 chain = getEffectChain_l(track->sessionId());
3150 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003151 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003152 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153 }
3154 }
3155 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003156 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003157 }
3158 }
3159 }
3160
3161 // mix buffer must be cleared if all tracks are connected to an
3162 // effect chain as in this case the mixer will not write to
3163 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003164 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3165 // FIXME as a performance optimization, should remember previous zero status
3166 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003167 }
3168
Glenn Kasten58912562012-04-03 10:45:00 -07003169 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003170 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003171 if (fastTracks > 0) {
3172 mixerStatus = MIXER_TRACKS_READY;
3173 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003174 return mixerStatus;
3175}
3176
Glenn Kasten66fcab92012-02-24 14:59:21 -08003177/*
3178The derived values that are cached:
3179 - mixBufferSize from frame count * frame size
3180 - activeSleepTime from activeSleepTimeUs()
3181 - idleSleepTime from idleSleepTimeUs()
3182 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3183 - maxPeriod from frame count and sample rate (MIXER only)
3184
3185The parameters that affect these derived values are:
3186 - frame count
3187 - frame size
3188 - sample rate
3189 - device type: A2DP or not
3190 - device latency
3191 - format: PCM or not
3192 - active sleep time
3193 - idle sleep time
3194*/
3195
3196void AudioFlinger::PlaybackThread::cacheParameters_l()
3197{
Glenn Kasten58912562012-04-03 10:45:00 -07003198 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003199 activeSleepTime = activeSleepTimeUs();
3200 idleSleepTime = idleSleepTimeUs();
3201}
3202
Glenn Kastenfff6d712012-01-12 16:38:12 -08003203void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003204{
Steve Block3856b092011-10-20 11:56:00 +01003205 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003206 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003207 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003208
Mathias Agopian65ab4712010-07-14 17:59:35 -07003209 size_t size = mTracks.size();
3210 for (size_t i = 0; i < size; i++) {
3211 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003212 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003213 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003214 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003215 }
3216 }
3217}
3218
Mathias Agopian65ab4712010-07-14 17:59:35 -07003219// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003220int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003221{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003222 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003223}
3224
3225// deleteTrackName_l() must be called with ThreadBase::mLock held
3226void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3227{
Steve Block3856b092011-10-20 11:56:00 +01003228 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003229 mAudioMixer->deleteTrackName(name);
3230}
3231
3232// checkForNewParameters_l() must be called with ThreadBase::mLock held
3233bool AudioFlinger::MixerThread::checkForNewParameters_l()
3234{
Glenn Kasten58912562012-04-03 10:45:00 -07003235 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3236 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003237 bool reconfig = false;
3238
3239 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003240
3241 if (mFastMixer != NULL) {
3242 FastMixerStateQueue *sq = mFastMixer->sq();
3243 FastMixerState *state = sq->begin();
3244 if (!(state->mCommand & FastMixerState::IDLE)) {
3245 previousCommand = state->mCommand;
3246 state->mCommand = FastMixerState::HOT_IDLE;
3247 sq->end();
3248 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3249 } else {
3250 sq->end(false /*didModify*/);
3251 }
3252 }
3253
Mathias Agopian65ab4712010-07-14 17:59:35 -07003254 status_t status = NO_ERROR;
3255 String8 keyValuePair = mNewParameters[0];
3256 AudioParameter param = AudioParameter(keyValuePair);
3257 int value;
3258
3259 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3260 reconfig = true;
3261 }
3262 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003263 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003264 status = BAD_VALUE;
3265 } else {
3266 reconfig = true;
3267 }
3268 }
3269 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003270 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003271 status = BAD_VALUE;
3272 } else {
3273 reconfig = true;
3274 }
3275 }
3276 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3277 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003278 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003279 // if frame count is changed after track creation
3280 if (!mTracks.isEmpty()) {
3281 status = INVALID_OPERATION;
3282 } else {
3283 reconfig = true;
3284 }
3285 }
3286 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003287#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003288 // when changing the audio output device, call addBatteryData to notify
3289 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07003290 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003291 uint32_t params = 0;
3292 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003293 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003294 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3295 }
3296
3297 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003298 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003299 // check if any other device (except speaker) is on
3300 if (value & deviceWithoutSpeaker ) {
3301 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3302 }
3303
3304 if (params != 0) {
3305 addBatteryData(params);
3306 }
3307 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003308#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003309
Mathias Agopian65ab4712010-07-14 17:59:35 -07003310 // forward device change to effects that have requested to be
3311 // aware of attached audio device.
3312 mDevice = (uint32_t)value;
3313 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003314 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003315 }
3316 }
3317
3318 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003319 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003320 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003321 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003322 mOutput->stream->common.standby(&mOutput->stream->common);
3323 mStandby = true;
3324 mBytesWritten = 0;
3325 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003326 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003327 }
3328 if (status == NO_ERROR && reconfig) {
3329 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003330 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3331 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003333 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003334 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003335 int name = getTrackName_l((audio_channel_mask_t)mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003336 if (name < 0) break;
3337 mTracks[i]->mName = name;
3338 // limit track sample rate to 2 x new output sample rate
3339 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3340 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3341 }
3342 }
3343 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3344 }
3345 }
3346
3347 mNewParameters.removeAt(0);
3348
3349 mParamStatus = status;
3350 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003351 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3352 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003353 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003354 }
Glenn Kasten58912562012-04-03 10:45:00 -07003355
3356 if (!(previousCommand & FastMixerState::IDLE)) {
3357 ALOG_ASSERT(mFastMixer != NULL);
3358 FastMixerStateQueue *sq = mFastMixer->sq();
3359 FastMixerState *state = sq->begin();
3360 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3361 state->mCommand = previousCommand;
3362 sq->end();
3363 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3364 }
3365
Mathias Agopian65ab4712010-07-14 17:59:35 -07003366 return reconfig;
3367}
3368
3369status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3370{
3371 const size_t SIZE = 256;
3372 char buffer[SIZE];
3373 String8 result;
3374
3375 PlaybackThread::dumpInternals(fd, args);
3376
3377 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3378 result.append(buffer);
3379 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003380
3381 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3382 FastMixerDumpState copy = mFastMixerDumpState;
3383 copy.dump(fd);
3384
Mathias Agopian65ab4712010-07-14 17:59:35 -07003385 return NO_ERROR;
3386}
3387
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003388uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003389{
Glenn Kasten58912562012-04-03 10:45:00 -07003390 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003391}
3392
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003393uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003394{
Glenn Kasten58912562012-04-03 10:45:00 -07003395 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003396}
3397
Glenn Kasten66fcab92012-02-24 14:59:21 -08003398void AudioFlinger::MixerThread::cacheParameters_l()
3399{
3400 PlaybackThread::cacheParameters_l();
3401
3402 // FIXME: Relaxed timing because of a certain device that can't meet latency
3403 // Should be reduced to 2x after the vendor fixes the driver issue
3404 // increase threshold again due to low power audio mode. The way this warning
3405 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003406 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003407}
3408
Mathias Agopian65ab4712010-07-14 17:59:35 -07003409// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003410AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
3411 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003412 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003413 // mLeftVolFloat, mRightVolFloat
3414 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07003415{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003416}
3417
3418AudioFlinger::DirectOutputThread::~DirectOutputThread()
3419{
3420}
3421
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003422AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3423 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003424)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003425{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003426 sp<Track> trackToRemove;
3427
Glenn Kastenfec279f2012-03-08 07:47:15 -08003428 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003429
Glenn Kasten952eeb22012-03-06 11:30:57 -08003430 // find out which tracks need to be processed
3431 if (mActiveTracks.size() != 0) {
3432 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003433 // The track died recently
3434 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003435
Glenn Kasten952eeb22012-03-06 11:30:57 -08003436 Track* const track = t.get();
3437 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003438
Glenn Kasten952eeb22012-03-06 11:30:57 -08003439 // The first time a track is added we wait
3440 // for all its buffers to be filled before processing it
3441 if (cblk->framesReady() && track->isReady() &&
3442 !track->isPaused() && !track->isTerminated())
3443 {
3444 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003445
Glenn Kasten952eeb22012-03-06 11:30:57 -08003446 if (track->mFillingUpStatus == Track::FS_FILLED) {
3447 track->mFillingUpStatus = Track::FS_ACTIVE;
3448 mLeftVolFloat = mRightVolFloat = 0;
3449 mLeftVolShort = mRightVolShort = 0;
3450 if (track->mState == TrackBase::RESUMING) {
3451 track->mState = TrackBase::ACTIVE;
3452 rampVolume = true;
3453 }
3454 } else if (cblk->server != 0) {
3455 // If the track is stopped before the first frame was mixed,
3456 // do not apply ramp
3457 rampVolume = true;
3458 }
3459 // compute volume for this track
3460 float left, right;
3461 if (track->isMuted() || mMasterMute || track->isPausing() ||
3462 mStreamTypes[track->streamType()].mute) {
3463 left = right = 0;
3464 if (track->isPausing()) {
3465 track->setPaused();
3466 }
3467 } else {
3468 float typeVolume = mStreamTypes[track->streamType()].volume;
3469 float v = mMasterVolume * typeVolume;
3470 uint32_t vlr = cblk->getVolumeLR();
3471 float v_clamped = v * (vlr & 0xFFFF);
3472 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3473 left = v_clamped/MAX_GAIN;
3474 v_clamped = v * (vlr >> 16);
3475 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3476 right = v_clamped/MAX_GAIN;
3477 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003478
Glenn Kasten952eeb22012-03-06 11:30:57 -08003479 if (left != mLeftVolFloat || right != mRightVolFloat) {
3480 mLeftVolFloat = left;
3481 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003482
Glenn Kasten952eeb22012-03-06 11:30:57 -08003483 // If audio HAL implements volume control,
3484 // force software volume to nominal value
3485 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
3486 left = 1.0f;
3487 right = 1.0f;
3488 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003489
Glenn Kasten952eeb22012-03-06 11:30:57 -08003490 // Convert volumes from float to 8.24
3491 uint32_t vl = (uint32_t)(left * (1 << 24));
3492 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493
Glenn Kasten952eeb22012-03-06 11:30:57 -08003494 // Delegate volume control to effect in track effect chain if needed
3495 // only one effect chain can be present on DirectOutputThread, so if
3496 // there is one, the track is connected to it
3497 if (!mEffectChains.isEmpty()) {
3498 // Do not ramp volume if volume is controlled by effect
3499 if (mEffectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003500 rampVolume = false;
3501 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003502 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003503
Glenn Kasten952eeb22012-03-06 11:30:57 -08003504 // Convert volumes from 8.24 to 4.12 format
3505 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
3506 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3507 leftVol = (uint16_t)v_clamped;
3508 v_clamped = (vr + (1 << 11)) >> 12;
3509 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
3510 rightVol = (uint16_t)v_clamped;
3511 } else {
3512 leftVol = mLeftVolShort;
3513 rightVol = mRightVolShort;
3514 rampVolume = false;
3515 }
3516
3517 // reset retry count
3518 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003519 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003520 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003521 } else {
3522 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
3523 if (track->isStopped()) {
3524 track->reset();
3525 }
3526 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
3527 // We have consumed all the buffers of this track.
3528 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003529 // TODO: implement behavior for compressed audio
3530 size_t audioHALFrames =
3531 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3532 size_t framesWritten =
3533 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3534 if (track->presentationComplete(framesWritten, audioHALFrames)) {
3535 trackToRemove = track;
3536 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003537 } else {
3538 // No buffers for this track. Give it a few chances to
3539 // fill a buffer, then remove it from active list.
3540 if (--(track->mRetryCount) <= 0) {
3541 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3542 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003543 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003544 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003545 }
3546 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003547 }
3548 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003549
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003550 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003551 // remove all the tracks that need to be...
3552 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003553 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003554 mActiveTracks.remove(trackToRemove);
3555 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003556 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003557 trackToRemove->sessionId());
3558 mEffectChains[0]->decActiveTrackCnt();
3559 }
3560 if (trackToRemove->isTerminated()) {
3561 removeTrack_l(trackToRemove);
3562 }
3563 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003564
Glenn Kastenfec279f2012-03-08 07:47:15 -08003565 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003566}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003567
Glenn Kasten000f0e32012-03-01 17:10:56 -08003568void AudioFlinger::DirectOutputThread::threadLoop_mix()
3569{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003570 AudioBufferProvider::Buffer buffer;
3571 size_t frameCount = mFrameCount;
3572 int8_t *curBuf = (int8_t *)mMixBuffer;
3573 // output audio to hardware
3574 while (frameCount) {
3575 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003576 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003577 if (CC_UNLIKELY(buffer.raw == NULL)) {
3578 memset(curBuf, 0, frameCount * mFrameSize);
3579 break;
3580 }
3581 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3582 frameCount -= buffer.frameCount;
3583 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003584 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003585 }
3586 sleepTime = 0;
3587 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003588 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003589
3590 // apply volume
3591
3592 // Do not apply volume on compressed audio
3593 if (!audio_is_linear_pcm(mFormat)) {
3594 return;
3595 }
3596
3597 // convert to signed 16 bit before volume calculation
3598 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3599 size_t count = mFrameCount * mChannelCount;
3600 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
3601 int16_t *dst = mMixBuffer + count-1;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003602 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003603 *dst-- = (int16_t)(*src--^0x80) << 8;
3604 }
3605 }
3606
3607 frameCount = mFrameCount;
3608 int16_t *out = mMixBuffer;
3609 if (rampVolume) {
3610 if (mChannelCount == 1) {
3611 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3612 int32_t vlInc = d / (int32_t)frameCount;
3613 int32_t vl = ((int32_t)mLeftVolShort << 16);
3614 do {
3615 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3616 out++;
3617 vl += vlInc;
3618 } while (--frameCount);
3619
3620 } else {
3621 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
3622 int32_t vlInc = d / (int32_t)frameCount;
3623 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
3624 int32_t vrInc = d / (int32_t)frameCount;
3625 int32_t vl = ((int32_t)mLeftVolShort << 16);
3626 int32_t vr = ((int32_t)mRightVolShort << 16);
3627 do {
3628 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
3629 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
3630 out += 2;
3631 vl += vlInc;
3632 vr += vrInc;
3633 } while (--frameCount);
3634 }
3635 } else {
3636 if (mChannelCount == 1) {
3637 do {
3638 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3639 out++;
3640 } while (--frameCount);
3641 } else {
3642 do {
3643 out[0] = clamp16(mul(out[0], leftVol) >> 12);
3644 out[1] = clamp16(mul(out[1], rightVol) >> 12);
3645 out += 2;
3646 } while (--frameCount);
3647 }
3648 }
3649
3650 // convert back to unsigned 8 bit after volume calculation
3651 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
3652 size_t count = mFrameCount * mChannelCount;
3653 int16_t *src = mMixBuffer;
3654 uint8_t *dst = (uint8_t *)mMixBuffer;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003655 while (count--) {
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003656 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
3657 }
3658 }
3659
3660 mLeftVolShort = leftVol;
3661 mRightVolShort = rightVol;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003662}
3663
3664void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3665{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003666 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003667 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003668 sleepTime = activeSleepTime;
3669 } else {
3670 sleepTime = idleSleepTime;
3671 }
3672 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003673 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003674 sleepTime = 0;
3675 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003676}
3677
3678// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003679int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003680{
3681 return 0;
3682}
3683
3684// deleteTrackName_l() must be called with ThreadBase::mLock held
3685void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3686{
3687}
3688
3689// checkForNewParameters_l() must be called with ThreadBase::mLock held
3690bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3691{
3692 bool reconfig = false;
3693
3694 while (!mNewParameters.isEmpty()) {
3695 status_t status = NO_ERROR;
3696 String8 keyValuePair = mNewParameters[0];
3697 AudioParameter param = AudioParameter(keyValuePair);
3698 int value;
3699
3700 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3701 // do not accept frame count changes if tracks are open as the track buffer
3702 // size depends on frame count and correct behavior would not be garantied
3703 // if frame count is changed after track creation
3704 if (!mTracks.isEmpty()) {
3705 status = INVALID_OPERATION;
3706 } else {
3707 reconfig = true;
3708 }
3709 }
3710 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003711 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003712 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003713 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003714 mOutput->stream->common.standby(&mOutput->stream->common);
3715 mStandby = true;
3716 mBytesWritten = 0;
3717 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003718 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003719 }
3720 if (status == NO_ERROR && reconfig) {
3721 readOutputParameters();
3722 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3723 }
3724 }
3725
3726 mNewParameters.removeAt(0);
3727
3728 mParamStatus = status;
3729 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003730 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3731 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003732 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003733 }
3734 return reconfig;
3735}
3736
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003737uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003738{
3739 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003740 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003741 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003742 } else {
3743 time = 10000;
3744 }
3745 return time;
3746}
3747
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003748uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003749{
3750 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003751 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003752 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003753 } else {
3754 time = 10000;
3755 }
3756 return time;
3757}
3758
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003759uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003760{
3761 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003762 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003763 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3764 } else {
3765 time = 10000;
3766 }
3767 return time;
3768}
3769
Glenn Kasten66fcab92012-02-24 14:59:21 -08003770void AudioFlinger::DirectOutputThread::cacheParameters_l()
3771{
3772 PlaybackThread::cacheParameters_l();
3773
3774 // use shorter standby delay as on normal output to release
3775 // hardware resources as soon as possible
3776 standbyDelay = microseconds(activeSleepTime*2);
3777}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003778
Mathias Agopian65ab4712010-07-14 17:59:35 -07003779// ----------------------------------------------------------------------------
3780
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003781AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003782 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003783 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3784 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003785{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003786 addOutputTrack(mainThread);
3787}
3788
3789AudioFlinger::DuplicatingThread::~DuplicatingThread()
3790{
3791 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3792 mOutputTracks[i]->destroy();
3793 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003794}
3795
Glenn Kasten000f0e32012-03-01 17:10:56 -08003796void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003797{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003798 // mix buffers...
3799 if (outputsReady(outputTracks)) {
3800 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3801 } else {
3802 memset(mMixBuffer, 0, mixBufferSize);
3803 }
3804 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003805 writeFrames = mNormalFrameCount;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003806}
3807
3808void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3809{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003810 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003811 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003812 sleepTime = activeSleepTime;
3813 } else {
3814 sleepTime = idleSleepTime;
3815 }
3816 } else if (mBytesWritten != 0) {
3817 // flush remaining overflow buffers in output tracks
3818 for (size_t i = 0; i < outputTracks.size(); i++) {
3819 if (outputTracks[i]->isActive()) {
3820 sleepTime = 0;
3821 writeFrames = 0;
3822 memset(mMixBuffer, 0, mixBufferSize);
3823 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003824 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003825 }
3826 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003827}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003828
Glenn Kasten000f0e32012-03-01 17:10:56 -08003829void AudioFlinger::DuplicatingThread::threadLoop_write()
3830{
Glenn Kasten66fcab92012-02-24 14:59:21 -08003831 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003832 for (size_t i = 0; i < outputTracks.size(); i++) {
3833 outputTracks[i]->write(mMixBuffer, writeFrames);
3834 }
3835 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003836}
Glenn Kasten688a6402012-02-29 07:57:06 -08003837
Glenn Kasten000f0e32012-03-01 17:10:56 -08003838void AudioFlinger::DuplicatingThread::threadLoop_standby()
3839{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003840 // DuplicatingThread implements standby by stopping all tracks
3841 for (size_t i = 0; i < outputTracks.size(); i++) {
3842 outputTracks[i]->stop();
3843 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003844}
3845
Glenn Kastenfa26a852012-03-06 11:28:04 -08003846void AudioFlinger::DuplicatingThread::saveOutputTracks()
3847{
3848 outputTracks = mOutputTracks;
3849}
3850
3851void AudioFlinger::DuplicatingThread::clearOutputTracks()
3852{
3853 outputTracks.clear();
3854}
3855
Mathias Agopian65ab4712010-07-14 17:59:35 -07003856void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3857{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003858 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003859 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07003860 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003861 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003862 this,
3863 mSampleRate,
3864 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003865 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003866 frameCount);
3867 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003868 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003869 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003870 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08003871 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003872 }
3873}
3874
3875void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3876{
3877 Mutex::Autolock _l(mLock);
3878 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08003879 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003880 mOutputTracks[i]->destroy();
3881 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08003882 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003883 return;
3884 }
3885 }
Steve Block3856b092011-10-20 11:56:00 +01003886 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003887}
3888
Glenn Kasten438b0362012-03-06 11:24:48 -08003889// caller must hold mLock
3890void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003891{
3892 mWaitTimeMs = UINT_MAX;
3893 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3894 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003895 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003896 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3897 if (waitTimeMs < mWaitTimeMs) {
3898 mWaitTimeMs = waitTimeMs;
3899 }
3900 }
3901 }
3902}
3903
3904
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08003905bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003906{
3907 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003908 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003909 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003910 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003911 return false;
3912 }
3913 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3914 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003915 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003916 return false;
3917 }
3918 }
3919 return true;
3920}
3921
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003922uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003923{
3924 return (mWaitTimeMs * 1000) / 2;
3925}
3926
Glenn Kasten66fcab92012-02-24 14:59:21 -08003927void AudioFlinger::DuplicatingThread::cacheParameters_l()
3928{
3929 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
3930 updateWaitTime_l();
3931
3932 MixerThread::cacheParameters_l();
3933}
3934
Mathias Agopian65ab4712010-07-14 17:59:35 -07003935// ----------------------------------------------------------------------------
3936
3937// TrackBase constructor must be called with AudioFlinger::mLock held
3938AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08003939 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003940 const sp<Client>& client,
3941 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003942 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003943 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003944 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003945 const sp<IMemory>& sharedBuffer,
3946 int sessionId)
3947 : RefBase(),
3948 mThread(thread),
3949 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003950 mCblk(NULL),
3951 // mBuffer
3952 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003953 mFrameCount(0),
3954 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07003955 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003956 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08003957 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003958 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003959 // mChannelCount
3960 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003961{
Steve Block3856b092011-10-20 11:56:00 +01003962 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003963
Steve Blockb8a80522011-12-20 16:23:08 +00003964 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003965 size_t size = sizeof(audio_track_cblk_t);
3966 uint8_t channelCount = popcount(channelMask);
3967 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3968 if (sharedBuffer == 0) {
3969 size += bufferSize;
3970 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003971
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003972 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003973 mCblkMemory = client->heap()->allocate(size);
3974 if (mCblkMemory != 0) {
3975 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003976 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003977 new(mCblk) audio_track_cblk_t();
3978 // clear all buffers
3979 mCblk->frameCount = frameCount;
3980 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07003981// uncomment the following lines to quickly test 32-bit wraparound
3982// mCblk->user = 0xffff0000;
3983// mCblk->server = 0xffff0000;
3984// mCblk->userBase = 0xffff0000;
3985// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003986 mChannelCount = channelCount;
3987 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003988 if (sharedBuffer == 0) {
3989 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3990 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3991 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003992 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003993 mCblk->flags = CBLK_UNDERRUN_ON;
3994 } else {
3995 mBuffer = sharedBuffer->pointer();
3996 }
3997 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3998 }
3999 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004000 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004001 client->heap()->dump("AudioTrack");
4002 return;
4003 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004004 } else {
4005 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004006 // construct the shared structure in-place.
4007 new(mCblk) audio_track_cblk_t();
4008 // clear all buffers
4009 mCblk->frameCount = frameCount;
4010 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004011// uncomment the following lines to quickly test 32-bit wraparound
4012// mCblk->user = 0xffff0000;
4013// mCblk->server = 0xffff0000;
4014// mCblk->userBase = 0xffff0000;
4015// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004016 mChannelCount = channelCount;
4017 mChannelMask = channelMask;
4018 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4019 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4020 // Force underrun condition to avoid false underrun callback until first data is
4021 // written to buffer (other flags are cleared)
4022 mCblk->flags = CBLK_UNDERRUN_ON;
4023 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004024 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004025}
4026
4027AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4028{
Glenn Kastena0d68332012-01-27 16:47:15 -08004029 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004030 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004031 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004032 } else {
4033 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004034 }
4035 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004036 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004037 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004038 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004039 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004040 // If the client's reference count drops to zero, the associated destructor
4041 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4042 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004043 mClient.clear();
4044 }
4045}
4046
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004047// AudioBufferProvider interface
4048// getNextBuffer() = 0;
4049// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004050void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4051{
Glenn Kastene0feee32011-12-13 11:53:26 -08004052 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004053 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004054 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004055 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004056 buffer->frameCount = 0;
4057}
4058
4059bool AudioFlinger::ThreadBase::TrackBase::step() {
4060 bool result;
4061 audio_track_cblk_t* cblk = this->cblk();
4062
4063 result = cblk->stepServer(mFrameCount);
4064 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004065 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004066 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004067 }
4068 return result;
4069}
4070
4071void AudioFlinger::ThreadBase::TrackBase::reset() {
4072 audio_track_cblk_t* cblk = this->cblk();
4073
4074 cblk->user = 0;
4075 cblk->server = 0;
4076 cblk->userBase = 0;
4077 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004078 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004079 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004080}
4081
Mathias Agopian65ab4712010-07-14 17:59:35 -07004082int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4083 return (int)mCblk->sampleRate;
4084}
4085
Mathias Agopian65ab4712010-07-14 17:59:35 -07004086void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4087 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004088 size_t frameSize = cblk->frameSize;
4089 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4090 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004091
4092 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004093 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4094 "TrackBase::getBuffer buffer out of range:\n"
4095 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4096 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004097 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004098 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004099
4100 return bufferStart;
4101}
4102
Eric Laurenta011e352012-03-29 15:51:43 -07004103status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4104{
4105 mSyncEvents.add(event);
4106 return NO_ERROR;
4107}
4108
Mathias Agopian65ab4712010-07-14 17:59:35 -07004109// ----------------------------------------------------------------------------
4110
4111// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4112AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004113 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004114 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004115 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004116 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004117 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004118 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004119 int frameCount,
4120 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004121 int sessionId,
4122 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004123 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004124 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004125 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004126 // mRetryCount initialized later when needed
4127 mSharedBuffer(sharedBuffer),
4128 mStreamType(streamType),
4129 mName(-1), // see note below
4130 mMainBuffer(thread->mixBuffer()),
4131 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004132 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004133 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004134 mFlags(flags),
4135 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004136 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004137 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004138{
4139 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004140 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4141 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004142 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten58912562012-04-03 10:45:00 -07004143 if (flags & IAudioFlinger::TRACK_FAST) {
4144 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4145 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4146 int i = __builtin_ctz(thread->mFastTrackAvailMask);
4147 ALOG_ASSERT(0 < i && i < FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004148 // FIXME This is too eager. We allocate a fast track index before the
4149 // fast track becomes active. Since fast tracks are a scarce resource,
4150 // this means we are potentially denying other more important fast tracks from
4151 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004152 mFastIndex = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004153 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004154 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004155 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004156 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004157 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07004158 mName = thread->getTrackName_l((audio_channel_mask_t)channelMask);
Glenn Kastenf9959012012-03-19 11:14:37 -07004159 if (mName < 0) {
4160 ALOGE("no more track names available");
Glenn Kasten288ed212012-04-25 17:52:27 -07004161 // FIXME bug - if sufficient fast track indices, but insufficient normal mixer names,
4162 // then we leak a fast track index. Should swap these two sections, or better yet
4163 // only allocate a normal mixer name for normal tracks.
Glenn Kastenf9959012012-03-19 11:14:37 -07004164 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004165 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004166 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004167}
4168
4169AudioFlinger::PlaybackThread::Track::~Track()
4170{
Steve Block3856b092011-10-20 11:56:00 +01004171 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004172 sp<ThreadBase> thread = mThread.promote();
4173 if (thread != 0) {
4174 Mutex::Autolock _l(thread->mLock);
4175 mState = TERMINATED;
4176 }
4177}
4178
4179void AudioFlinger::PlaybackThread::Track::destroy()
4180{
4181 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4182 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004183 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004184 // we must acquire a strong reference on this Track before locking mLock
4185 // here so that the destructor is called only when exiting this function.
4186 // On the other hand, as long as Track::destroy() is only called by
4187 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4188 // this Track with its member mTrack.
4189 sp<Track> keep(this);
4190 { // scope for mLock
4191 sp<ThreadBase> thread = mThread.promote();
4192 if (thread != 0) {
4193 if (!isOutputTrack()) {
4194 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004195 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004196
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004197#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004198 // to track the speaker usage
4199 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004200#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004201 }
4202 AudioSystem::releaseOutput(thread->id());
4203 }
4204 Mutex::Autolock _l(thread->mLock);
4205 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4206 playbackThread->destroyTrack_l(this);
4207 }
4208 }
4209}
4210
Glenn Kasten288ed212012-04-25 17:52:27 -07004211/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4212{
Glenn Kastene213c862012-04-25 13:46:15 -07004213 result.append(" Name Client Type Fmt Chn mask Session mFrCnt fCount S M F SRate L dB R dB "
4214 " Server User Main buf Aux Buf Flags FastUnder\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004215}
4216
Mathias Agopian65ab4712010-07-14 17:59:35 -07004217void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4218{
Glenn Kasten83d86532012-01-17 14:39:34 -08004219 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004220 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004221 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004222 } else {
4223 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4224 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004225 track_state state = mState;
4226 char stateChar;
4227 switch (state) {
4228 case IDLE:
4229 stateChar = 'I';
4230 break;
4231 case TERMINATED:
4232 stateChar = 'T';
4233 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004234 case STOPPING_1:
4235 stateChar = 's';
4236 break;
4237 case STOPPING_2:
4238 stateChar = '5';
4239 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004240 case STOPPED:
4241 stateChar = 'S';
4242 break;
4243 case RESUMING:
4244 stateChar = 'R';
4245 break;
4246 case ACTIVE:
4247 stateChar = 'A';
4248 break;
4249 case PAUSING:
4250 stateChar = 'p';
4251 break;
4252 case PAUSED:
4253 stateChar = 'P';
4254 break;
4255 default:
4256 stateChar = '?';
4257 break;
4258 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004259 char nowInUnderrun;
4260 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4261 case UNDERRUN_FULL:
4262 nowInUnderrun = ' ';
4263 break;
4264 case UNDERRUN_PARTIAL:
4265 nowInUnderrun = '<';
4266 break;
4267 case UNDERRUN_EMPTY:
4268 nowInUnderrun = '*';
4269 break;
4270 default:
4271 nowInUnderrun = '?';
4272 break;
4273 }
Glenn Kastene213c862012-04-25 13:46:15 -07004274 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4275 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004276 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004277 mStreamType,
4278 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004279 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004280 mSessionId,
4281 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004282 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004283 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004284 mMute,
4285 mFillingUpStatus,
4286 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004287 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4288 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004289 mCblk->server,
4290 mCblk->user,
4291 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004292 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004293 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004294 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004295 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004296}
4297
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004298// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004299status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004300 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004301{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004302 audio_track_cblk_t* cblk = this->cblk();
4303 uint32_t framesReady;
4304 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004305
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004306 // Check if last stepServer failed, try to step now
4307 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004308 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4309 // Since the fast mixer is higher priority than client callback thread,
4310 // it does not result in priority inversion for client.
4311 // But a non-blocking solution would be preferable to avoid
4312 // fast mixer being unable to tryLock(), and
4313 // to avoid the extra context switches if the client wakes up,
4314 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004315 if (!step()) goto getNextBuffer_exit;
4316 ALOGV("stepServer recovered");
4317 mStepServerFailed = false;
4318 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004319
Glenn Kasten288ed212012-04-25 17:52:27 -07004320 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004321 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004322
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004323 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004324 uint32_t s = cblk->server;
4325 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4326
4327 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4328 if (framesReq > framesReady) {
4329 framesReq = framesReady;
4330 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004331 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004332 framesReq = bufferEnd - s;
4333 }
4334
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004335 buffer->raw = getBuffer(s, framesReq);
4336 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004337
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004338 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004339 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004340 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004341
4342getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004343 buffer->raw = NULL;
4344 buffer->frameCount = 0;
4345 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4346 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004347}
4348
Glenn Kasten288ed212012-04-25 17:52:27 -07004349// Note that framesReady() takes a mutex on the control block using tryLock().
4350// This could result in priority inversion if framesReady() is called by the normal mixer,
4351// as the normal mixer thread runs at lower
4352// priority than the client's callback thread: there is a short window within framesReady()
4353// during which the normal mixer could be preempted, and the client callback would block.
4354// Another problem can occur if framesReady() is called by the fast mixer:
4355// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4356// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4357size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004358 return mCblk->framesReady();
4359}
4360
Glenn Kasten288ed212012-04-25 17:52:27 -07004361// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004362bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004363 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004364
John Grossman4ff14ba2012-02-08 16:37:41 -08004365 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004366 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4367 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004368 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004369 return true;
4370 }
4371 return false;
4372}
4373
Glenn Kasten3acbd052012-02-28 10:39:56 -08004374status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004375 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004376{
4377 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004378 ALOGV("start(%d), calling pid %d session %d",
4379 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004380
Mathias Agopian65ab4712010-07-14 17:59:35 -07004381 sp<ThreadBase> thread = mThread.promote();
4382 if (thread != 0) {
4383 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004384 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004385 // here the track could be either new, or restarted
4386 // in both cases "unstop" the track
4387 if (mState == PAUSED) {
4388 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004389 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004390 } else {
4391 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004392 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004393 }
4394
4395 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4396 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004397 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004398 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004399
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004400#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004401 // to track the speaker usage
4402 if (status == NO_ERROR) {
4403 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4404 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004405#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004406 }
4407 if (status == NO_ERROR) {
4408 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4409 playbackThread->addTrack_l(this);
4410 } else {
4411 mState = state;
4412 }
4413 } else {
4414 status = BAD_VALUE;
4415 }
4416 return status;
4417}
4418
4419void AudioFlinger::PlaybackThread::Track::stop()
4420{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004421 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004422 sp<ThreadBase> thread = mThread.promote();
4423 if (thread != 0) {
4424 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004425 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004426 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004427 // If the track is not active (PAUSED and buffers full), flush buffers
4428 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4429 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4430 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004431 mState = STOPPED;
4432 } else if (!isFastTrack()) {
4433 mState = STOPPED;
4434 } else {
4435 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4436 // and then to STOPPED and reset() when presentation is complete
4437 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004438 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004439 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004440 }
4441 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4442 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004443 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004444 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004445
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004446#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004447 // to track the speaker usage
4448 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004449#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004450 }
4451 }
4452}
4453
4454void AudioFlinger::PlaybackThread::Track::pause()
4455{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004456 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004457 sp<ThreadBase> thread = mThread.promote();
4458 if (thread != 0) {
4459 Mutex::Autolock _l(thread->mLock);
4460 if (mState == ACTIVE || mState == RESUMING) {
4461 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004462 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004463 if (!isOutputTrack()) {
4464 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004465 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004466 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004467
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004468#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004469 // to track the speaker usage
4470 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004471#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004472 }
4473 }
4474 }
4475}
4476
4477void AudioFlinger::PlaybackThread::Track::flush()
4478{
Steve Block3856b092011-10-20 11:56:00 +01004479 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004480 sp<ThreadBase> thread = mThread.promote();
4481 if (thread != 0) {
4482 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004483 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4484 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004485 return;
4486 }
4487 // No point remaining in PAUSED state after a flush => go to
4488 // STOPPED state
4489 mState = STOPPED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004490 // do not reset the track if it is still in the process of being stopped or paused.
4491 // this will be done by prepareTracks_l() when the track is stopped.
Glenn Kastend08f48c2012-05-01 18:14:02 -07004492 // prepareTracks_l() will see mState == STOPPED, then
4493 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004494 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4495 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4496 reset();
4497 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004498 }
4499}
4500
4501void AudioFlinger::PlaybackThread::Track::reset()
4502{
4503 // Do not reset twice to avoid discarding data written just after a flush and before
4504 // the audioflinger thread detects the track is stopped.
4505 if (!mResetDone) {
4506 TrackBase::reset();
4507 // Force underrun condition to avoid false underrun callback until first data is
4508 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004509 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4510 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004511 mFillingUpStatus = FS_FILLING;
4512 mResetDone = true;
Eric Laurenta011e352012-03-29 15:51:43 -07004513 mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004514 }
4515}
4516
4517void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4518{
4519 mMute = muted;
4520}
4521
Mathias Agopian65ab4712010-07-14 17:59:35 -07004522status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4523{
4524 status_t status = DEAD_OBJECT;
4525 sp<ThreadBase> thread = mThread.promote();
4526 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004527 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4528 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004529 }
4530 return status;
4531}
4532
4533void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4534{
4535 mAuxEffectId = EffectId;
4536 mAuxBuffer = buffer;
4537}
4538
Eric Laurenta011e352012-03-29 15:51:43 -07004539bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4540 size_t audioHalFrames)
4541{
4542 // a track is considered presented when the total number of frames written to audio HAL
4543 // corresponds to the number of frames written when presentationComplete() is called for the
4544 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4545 if (mPresentationCompleteFrames == 0) {
4546 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4547 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4548 mPresentationCompleteFrames, audioHalFrames);
4549 }
4550 if (framesWritten >= mPresentationCompleteFrames) {
4551 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4552 mSessionId, framesWritten);
4553 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
4554 mPresentationCompleteFrames = 0;
4555 return true;
4556 }
4557 return false;
4558}
4559
4560void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4561{
4562 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4563 if (mSyncEvents[i]->type() == type) {
4564 mSyncEvents[i]->trigger();
4565 mSyncEvents.removeAt(i);
4566 i--;
4567 }
4568 }
4569}
4570
Glenn Kasten58912562012-04-03 10:45:00 -07004571// implement VolumeBufferProvider interface
4572
4573uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4574{
4575 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4576 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4577 uint32_t vlr = mCblk->getVolumeLR();
4578 uint32_t vl = vlr & 0xFFFF;
4579 uint32_t vr = vlr >> 16;
4580 // track volumes come from shared memory, so can't be trusted and must be clamped
4581 if (vl > MAX_GAIN_INT) {
4582 vl = MAX_GAIN_INT;
4583 }
4584 if (vr > MAX_GAIN_INT) {
4585 vr = MAX_GAIN_INT;
4586 }
4587 // now apply the cached master volume and stream type volume;
4588 // this is trusted but lacks any synchronization or barrier so may be stale
4589 float v = mCachedVolume;
4590 vl *= v;
4591 vr *= v;
4592 // re-combine into U4.16
4593 vlr = (vr << 16) | (vl & 0xFFFF);
4594 // FIXME look at mute, pause, and stop flags
4595 return vlr;
4596}
Eric Laurenta011e352012-03-29 15:51:43 -07004597
John Grossman4ff14ba2012-02-08 16:37:41 -08004598// timed audio tracks
4599
4600sp<AudioFlinger::PlaybackThread::TimedTrack>
4601AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004602 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004603 const sp<Client>& client,
4604 audio_stream_type_t streamType,
4605 uint32_t sampleRate,
4606 audio_format_t format,
4607 uint32_t channelMask,
4608 int frameCount,
4609 const sp<IMemory>& sharedBuffer,
4610 int sessionId) {
4611 if (!client->reserveTimedTrack())
4612 return NULL;
4613
Glenn Kastena0356762012-03-19 10:38:51 -07004614 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004615 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4616 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004617}
4618
4619AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004620 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004621 const sp<Client>& client,
4622 audio_stream_type_t streamType,
4623 uint32_t sampleRate,
4624 audio_format_t format,
4625 uint32_t channelMask,
4626 int frameCount,
4627 const sp<IMemory>& sharedBuffer,
4628 int sessionId)
4629 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004630 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004631 mQueueHeadInFlight(false),
4632 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004633 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004634 mTimedSilenceBuffer(NULL),
4635 mTimedSilenceBufferSize(0),
4636 mTimedAudioOutputOnTime(false),
4637 mMediaTimeTransformValid(false)
4638{
4639 LocalClock lc;
4640 mLocalTimeFreq = lc.getLocalFreq();
4641
4642 mLocalTimeToSampleTransform.a_zero = 0;
4643 mLocalTimeToSampleTransform.b_zero = 0;
4644 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4645 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4646 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4647 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004648
4649 mMediaTimeToSampleTransform.a_zero = 0;
4650 mMediaTimeToSampleTransform.b_zero = 0;
4651 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4652 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4653 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4654 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004655}
4656
4657AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4658 mClient->releaseTimedTrack();
4659 delete [] mTimedSilenceBuffer;
4660}
4661
4662status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4663 size_t size, sp<IMemory>* buffer) {
4664
4665 Mutex::Autolock _l(mTimedBufferQueueLock);
4666
4667 trimTimedBufferQueue_l();
4668
4669 // lazily initialize the shared memory heap for timed buffers
4670 if (mTimedMemoryDealer == NULL) {
4671 const int kTimedBufferHeapSize = 512 << 10;
4672
4673 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4674 "AudioFlingerTimed");
4675 if (mTimedMemoryDealer == NULL)
4676 return NO_MEMORY;
4677 }
4678
4679 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4680 if (newBuffer == NULL) {
4681 newBuffer = mTimedMemoryDealer->allocate(size);
4682 if (newBuffer == NULL)
4683 return NO_MEMORY;
4684 }
4685
4686 *buffer = newBuffer;
4687 return NO_ERROR;
4688}
4689
4690// caller must hold mTimedBufferQueueLock
4691void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4692 int64_t mediaTimeNow;
4693 {
4694 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4695 if (!mMediaTimeTransformValid)
4696 return;
4697
4698 int64_t targetTimeNow;
4699 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4700 ? mCCHelper.getCommonTime(&targetTimeNow)
4701 : mCCHelper.getLocalTime(&targetTimeNow);
4702
4703 if (OK != res)
4704 return;
4705
4706 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4707 &mediaTimeNow)) {
4708 return;
4709 }
4710 }
4711
John Grossman1c345192012-03-27 14:00:17 -07004712 size_t trimEnd;
4713 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004714 int64_t bufEnd;
4715
John Grossmanc95cfbb2012-04-12 11:53:11 -07004716 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4717 // We have a next buffer. Just use its PTS as the PTS of the frame
4718 // following the last frame in this buffer. If the stream is sparse
4719 // (ie, there are deliberate gaps left in the stream which should be
4720 // filled with silence by the TimedAudioTrack), then this can result
4721 // in one extra buffer being left un-trimmed when it could have
4722 // been. In general, this is not typical, and we would rather
4723 // optimized away the TS calculation below for the more common case
4724 // where PTSes are contiguous.
4725 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4726 } else {
4727 // We have no next buffer. Compute the PTS of the frame following
4728 // the last frame in this buffer by computing the duration of of
4729 // this frame in media time units and adding it to the PTS of the
4730 // buffer.
4731 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4732 / mCblk->frameSize;
4733
4734 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4735 &bufEnd)) {
4736 ALOGE("Failed to convert frame count of %lld to media time"
4737 " duration" " (scale factor %d/%u) in %s",
4738 frameCount,
4739 mMediaTimeToSampleTransform.a_to_b_numer,
4740 mMediaTimeToSampleTransform.a_to_b_denom,
4741 __PRETTY_FUNCTION__);
4742 break;
4743 }
4744 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004745 }
John Grossman9fbdee12012-03-26 17:51:46 -07004746
4747 if (bufEnd > mediaTimeNow)
4748 break;
4749
4750 // Is the buffer we want to use in the middle of a mix operation right
4751 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4752 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004753 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004754 mTrimQueueHeadOnRelease = true;
4755 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004756 }
4757
John Grossman9fbdee12012-03-26 17:51:46 -07004758 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004759 if (trimStart < trimEnd) {
4760 // Update the bookkeeping for framesReady()
4761 for (size_t i = trimStart; i < trimEnd; ++i) {
4762 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4763 }
4764
4765 // Now actually remove the buffers from the queue.
4766 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004767 }
4768}
4769
John Grossman1c345192012-03-27 14:00:17 -07004770void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4771 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004772 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4773 "%s called (reason \"%s\"), but timed buffer queue has no"
4774 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004775
4776 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4777 mTimedBufferQueue.removeAt(0);
4778}
4779
4780void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4781 const TimedBuffer& buf,
4782 const char* logTag) {
4783 uint32_t bufBytes = buf.buffer()->size();
4784 uint32_t consumedAlready = buf.position();
4785
Eric Laurentb388e532012-04-14 13:32:48 -07004786 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004787 "Bad bookkeeping while updating frames pending. Timed buffer is"
4788 " only %u bytes long, but claims to have consumed %u"
4789 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004790 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004791
4792 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004793 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4794 "Bad bookkeeping while updating frames pending. Should have at"
4795 " least %u queued frames, but we think we have only %u. (update"
4796 " reason: \"%s\")",
4797 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004798
4799 mFramesPendingInQueue -= bufFrames;
4800}
4801
John Grossman4ff14ba2012-02-08 16:37:41 -08004802status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4803 const sp<IMemory>& buffer, int64_t pts) {
4804
4805 {
4806 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4807 if (!mMediaTimeTransformValid)
4808 return INVALID_OPERATION;
4809 }
4810
4811 Mutex::Autolock _l(mTimedBufferQueueLock);
4812
John Grossman1c345192012-03-27 14:00:17 -07004813 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
4814 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08004815 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
4816
4817 return NO_ERROR;
4818}
4819
4820status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
4821 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
4822
John Grossman1c345192012-03-27 14:00:17 -07004823 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
4824 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
4825 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08004826
4827 if (!(target == TimedAudioTrack::LOCAL_TIME ||
4828 target == TimedAudioTrack::COMMON_TIME)) {
4829 return BAD_VALUE;
4830 }
4831
4832 Mutex::Autolock lock(mMediaTimeTransformLock);
4833 mMediaTimeTransform = xform;
4834 mMediaTimeTransformTarget = target;
4835 mMediaTimeTransformValid = true;
4836
4837 return NO_ERROR;
4838}
4839
4840#define min(a, b) ((a) < (b) ? (a) : (b))
4841
4842// implementation of getNextBuffer for tracks whose buffers have timestamps
4843status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
4844 AudioBufferProvider::Buffer* buffer, int64_t pts)
4845{
4846 if (pts == AudioBufferProvider::kInvalidPTS) {
4847 buffer->raw = 0;
4848 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07004849 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08004850 return INVALID_OPERATION;
4851 }
4852
John Grossman4ff14ba2012-02-08 16:37:41 -08004853 Mutex::Autolock _l(mTimedBufferQueueLock);
4854
John Grossman9fbdee12012-03-26 17:51:46 -07004855 ALOG_ASSERT(!mQueueHeadInFlight,
4856 "getNextBuffer called without releaseBuffer!");
4857
John Grossman4ff14ba2012-02-08 16:37:41 -08004858 while (true) {
4859
4860 // if we have no timed buffers, then fail
4861 if (mTimedBufferQueue.isEmpty()) {
4862 buffer->raw = 0;
4863 buffer->frameCount = 0;
4864 return NOT_ENOUGH_DATA;
4865 }
4866
4867 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4868
4869 // calculate the PTS of the head of the timed buffer queue expressed in
4870 // local time
4871 int64_t headLocalPTS;
4872 {
4873 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4874
Glenn Kasten5798d4e2012-03-08 12:18:35 -08004875 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08004876
4877 if (mMediaTimeTransform.a_to_b_denom == 0) {
4878 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07004879 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004880 return NO_ERROR;
4881 }
4882
4883 int64_t transformedPTS;
4884 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
4885 &transformedPTS)) {
4886 // the transform failed. this shouldn't happen, but if it does
4887 // then just drop this buffer
4888 ALOGW("timedGetNextBuffer transform failed");
4889 buffer->raw = 0;
4890 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07004891 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08004892 return NO_ERROR;
4893 }
4894
4895 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
4896 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
4897 &headLocalPTS)) {
4898 buffer->raw = 0;
4899 buffer->frameCount = 0;
4900 return INVALID_OPERATION;
4901 }
4902 } else {
4903 headLocalPTS = transformedPTS;
4904 }
4905 }
4906
4907 // adjust the head buffer's PTS to reflect the portion of the head buffer
4908 // that has already been consumed
4909 int64_t effectivePTS = headLocalPTS +
4910 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
4911
4912 // Calculate the delta in samples between the head of the input buffer
4913 // queue and the start of the next output buffer that will be written.
4914 // If the transformation fails because of over or underflow, it means
4915 // that the sample's position in the output stream is so far out of
4916 // whack that it should just be dropped.
4917 int64_t sampleDelta;
4918 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
4919 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004920 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
4921 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08004922 continue;
4923 }
4924 if (!mLocalTimeToSampleTransform.doForwardTransform(
4925 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07004926 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004927 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08004928 continue;
4929 }
4930
John Grossman1c345192012-03-27 14:00:17 -07004931 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
4932 " sampleDelta=[%d.%08x]",
4933 head.pts(), head.position(), pts,
4934 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
4935 + (sampleDelta >> 32)),
4936 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08004937
4938 // if the delta between the ideal placement for the next input sample and
4939 // the current output position is within this threshold, then we will
4940 // concatenate the next input samples to the previous output
4941 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07004942 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08004943
4944 // if this is the first buffer of audio that we're emitting from this track
4945 // then it should be almost exactly on time.
4946 const int64_t kSampleStartupThreshold = 1LL << 32;
4947
4948 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07004949 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004950 // the next input is close enough to being on time, so concatenate it
4951 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07004952 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004953
John Grossman1c345192012-03-27 14:00:17 -07004954 ALOGVV("*** on time: head.pos=%d frameCount=%u",
4955 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08004956 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07004957 }
4958
4959 // Looks like our output is not on time. Reset our on timed status.
4960 // Next time we mix samples from our input queue, then should be within
4961 // the StartupThreshold.
4962 mTimedAudioOutputOnTime = false;
4963 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08004964 // the gap between the current output position and the proper start of
4965 // the next input sample is too big, so fill it with silence
4966 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
4967
John Grossman9fbdee12012-03-26 17:51:46 -07004968 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004969 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
4970 return NO_ERROR;
4971 } else {
4972 // the next input sample is late
4973 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
4974 size_t onTimeSamplePosition =
4975 head.position() + lateFrames * mCblk->frameSize;
4976
4977 if (onTimeSamplePosition > head.buffer()->size()) {
4978 // all the remaining samples in the head are too late, so
4979 // drop it and move on
4980 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07004981 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08004982 continue;
4983 } else {
4984 // skip over the late samples
4985 head.setPosition(onTimeSamplePosition);
4986
4987 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07004988 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08004989
4990 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4991 return NO_ERROR;
4992 }
4993 }
4994 }
4995}
4996
4997// Yield samples from the timed buffer queue head up to the given output
4998// buffer's capacity.
4999//
5000// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005001void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005002 AudioBufferProvider::Buffer* buffer) {
5003
5004 const TimedBuffer& head = mTimedBufferQueue[0];
5005
5006 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5007 head.position());
5008
5009 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5010 mCblk->frameSize);
5011 size_t framesRequested = buffer->frameCount;
5012 buffer->frameCount = min(framesLeftInHead, framesRequested);
5013
John Grossman9fbdee12012-03-26 17:51:46 -07005014 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005015 mTimedAudioOutputOnTime = true;
5016}
5017
5018// Yield samples of silence up to the given output buffer's capacity
5019//
5020// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005021void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005022 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5023
5024 // lazily allocate a buffer filled with silence
5025 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5026 delete [] mTimedSilenceBuffer;
5027 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5028 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5029 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5030 }
5031
5032 buffer->raw = mTimedSilenceBuffer;
5033 size_t framesRequested = buffer->frameCount;
5034 buffer->frameCount = min(numFrames, framesRequested);
5035
5036 mTimedAudioOutputOnTime = false;
5037}
5038
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005039// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005040void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5041 AudioBufferProvider::Buffer* buffer) {
5042
5043 Mutex::Autolock _l(mTimedBufferQueueLock);
5044
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005045 // If the buffer which was just released is part of the buffer at the head
5046 // of the queue, be sure to update the amt of the buffer which has been
5047 // consumed. If the buffer being returned is not part of the head of the
5048 // queue, its either because the buffer is part of the silence buffer, or
5049 // because the head of the timed queue was trimmed after the mixer called
5050 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005051 if (buffer->raw == mTimedSilenceBuffer) {
5052 ALOG_ASSERT(!mQueueHeadInFlight,
5053 "Queue head in flight during release of silence buffer!");
5054 goto done;
5055 }
5056
5057 ALOG_ASSERT(mQueueHeadInFlight,
5058 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5059 " head in flight.");
5060
5061 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005062 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005063
5064 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005065 void* end = reinterpret_cast<void*>(
5066 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5067 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005068
John Grossman9fbdee12012-03-26 17:51:46 -07005069 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5070 "released buffer not within the head of the timed buffer"
5071 " queue; qHead = [%p, %p], released buffer = %p",
5072 start, end, buffer->raw);
5073
5074 head.setPosition(head.position() +
5075 (buffer->frameCount * mCblk->frameSize));
5076 mQueueHeadInFlight = false;
5077
John Grossman1c345192012-03-27 14:00:17 -07005078 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5079 "Bad bookkeeping during releaseBuffer! Should have at"
5080 " least %u queued frames, but we think we have only %u",
5081 buffer->frameCount, mFramesPendingInQueue);
5082
5083 mFramesPendingInQueue -= buffer->frameCount;
5084
John Grossman9fbdee12012-03-26 17:51:46 -07005085 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5086 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005087 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005088 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005089 }
John Grossman9fbdee12012-03-26 17:51:46 -07005090 } else {
5091 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5092 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005093 }
5094
John Grossman9fbdee12012-03-26 17:51:46 -07005095done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005096 buffer->raw = 0;
5097 buffer->frameCount = 0;
5098}
5099
Glenn Kasten288ed212012-04-25 17:52:27 -07005100size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005101 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005102 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005103}
5104
5105AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5106 : mPTS(0), mPosition(0) {}
5107
5108AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5109 const sp<IMemory>& buffer, int64_t pts)
5110 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5111
Mathias Agopian65ab4712010-07-14 17:59:35 -07005112// ----------------------------------------------------------------------------
5113
5114// RecordTrack constructor must be called with AudioFlinger::mLock held
5115AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005116 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005117 const sp<Client>& client,
5118 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005119 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005120 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005121 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005122 int sessionId)
5123 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005124 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005125 mOverflow(false)
5126{
5127 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005128 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5129 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5130 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5131 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5132 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5133 } else {
5134 mCblk->frameSize = sizeof(int8_t);
5135 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005136 }
5137}
5138
5139AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5140{
5141 sp<ThreadBase> thread = mThread.promote();
5142 if (thread != 0) {
5143 AudioSystem::releaseInput(thread->id());
5144 }
5145}
5146
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005147// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005148status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005149{
5150 audio_track_cblk_t* cblk = this->cblk();
5151 uint32_t framesAvail;
5152 uint32_t framesReq = buffer->frameCount;
5153
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005154 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005155 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005156 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005157 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005158 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005159 }
5160
5161 framesAvail = cblk->framesAvailable_l();
5162
Glenn Kastenf6b16782011-12-15 09:51:17 -08005163 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005164 uint32_t s = cblk->server;
5165 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5166
5167 if (framesReq > framesAvail) {
5168 framesReq = framesAvail;
5169 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005170 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005171 framesReq = bufferEnd - s;
5172 }
5173
5174 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08005175 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005176
5177 buffer->frameCount = framesReq;
5178 return NO_ERROR;
5179 }
5180
5181getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005182 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005183 buffer->frameCount = 0;
5184 return NOT_ENOUGH_DATA;
5185}
5186
Glenn Kasten3acbd052012-02-28 10:39:56 -08005187status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005188 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005189{
5190 sp<ThreadBase> thread = mThread.promote();
5191 if (thread != 0) {
5192 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005193 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005194 } else {
5195 return BAD_VALUE;
5196 }
5197}
5198
5199void AudioFlinger::RecordThread::RecordTrack::stop()
5200{
5201 sp<ThreadBase> thread = mThread.promote();
5202 if (thread != 0) {
5203 RecordThread *recordThread = (RecordThread *)thread.get();
5204 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07005205 TrackBase::reset();
Glenn Kasten17a736c2012-02-14 08:52:15 -08005206 // Force overrun condition to avoid false overrun callback until first data is
Eric Laurent38ccae22011-03-28 18:37:07 -07005207 // read from buffer
5208 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005209 }
5210}
5211
5212void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5213{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005214 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005215 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005216 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005217 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005218 mSessionId,
5219 mFrameCount,
5220 mState,
5221 mCblk->sampleRate,
5222 mCblk->server,
5223 mCblk->user);
5224}
5225
5226
5227// ----------------------------------------------------------------------------
5228
5229AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005230 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005231 DuplicatingThread *sourceThread,
5232 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005233 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005234 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005235 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005236 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5237 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005238 mActive(false), mSourceThread(sourceThread)
5239{
5240
Mathias Agopian65ab4712010-07-14 17:59:35 -07005241 if (mCblk != NULL) {
5242 mCblk->flags |= CBLK_DIRECTION_OUT;
5243 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005244 mOutBuffer.frameCount = 0;
5245 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005246 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005247 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5248 mCblk, mBuffer, mCblk->buffers,
5249 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005250 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005251 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005252 }
5253}
5254
5255AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5256{
5257 clearBufferQueue();
5258}
5259
Glenn Kasten3acbd052012-02-28 10:39:56 -08005260status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005261 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005262{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005263 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005264 if (status != NO_ERROR) {
5265 return status;
5266 }
5267
5268 mActive = true;
5269 mRetryCount = 127;
5270 return status;
5271}
5272
5273void AudioFlinger::PlaybackThread::OutputTrack::stop()
5274{
5275 Track::stop();
5276 clearBufferQueue();
5277 mOutBuffer.frameCount = 0;
5278 mActive = false;
5279}
5280
5281bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5282{
5283 Buffer *pInBuffer;
5284 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005285 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005286 bool outputBufferFull = false;
5287 inBuffer.frameCount = frames;
5288 inBuffer.i16 = data;
5289
5290 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5291
5292 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005293 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005294 sp<ThreadBase> thread = mThread.promote();
5295 if (thread != 0) {
5296 MixerThread *mixerThread = (MixerThread *)thread.get();
5297 if (mCblk->frameCount > frames){
5298 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5299 uint32_t startFrames = (mCblk->frameCount - frames);
5300 pInBuffer = new Buffer;
5301 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5302 pInBuffer->frameCount = startFrames;
5303 pInBuffer->i16 = pInBuffer->mBuffer;
5304 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5305 mBufferQueue.add(pInBuffer);
5306 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005307 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005308 }
5309 }
5310 }
5311 }
5312
5313 while (waitTimeLeftMs) {
5314 // First write pending buffers, then new data
5315 if (mBufferQueue.size()) {
5316 pInBuffer = mBufferQueue.itemAt(0);
5317 } else {
5318 pInBuffer = &inBuffer;
5319 }
5320
5321 if (pInBuffer->frameCount == 0) {
5322 break;
5323 }
5324
5325 if (mOutBuffer.frameCount == 0) {
5326 mOutBuffer.frameCount = pInBuffer->frameCount;
5327 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005328 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005329 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005330 outputBufferFull = true;
5331 break;
5332 }
5333 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5334 if (waitTimeLeftMs >= waitTimeMs) {
5335 waitTimeLeftMs -= waitTimeMs;
5336 } else {
5337 waitTimeLeftMs = 0;
5338 }
5339 }
5340
5341 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5342 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5343 mCblk->stepUser(outFrames);
5344 pInBuffer->frameCount -= outFrames;
5345 pInBuffer->i16 += outFrames * channelCount;
5346 mOutBuffer.frameCount -= outFrames;
5347 mOutBuffer.i16 += outFrames * channelCount;
5348
5349 if (pInBuffer->frameCount == 0) {
5350 if (mBufferQueue.size()) {
5351 mBufferQueue.removeAt(0);
5352 delete [] pInBuffer->mBuffer;
5353 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005354 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005355 } else {
5356 break;
5357 }
5358 }
5359 }
5360
5361 // If we could not write all frames, allocate a buffer and queue it for next time.
5362 if (inBuffer.frameCount) {
5363 sp<ThreadBase> thread = mThread.promote();
5364 if (thread != 0 && !thread->standby()) {
5365 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5366 pInBuffer = new Buffer;
5367 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5368 pInBuffer->frameCount = inBuffer.frameCount;
5369 pInBuffer->i16 = pInBuffer->mBuffer;
5370 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5371 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005372 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005373 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005374 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005375 }
5376 }
5377 }
5378
5379 // Calling write() with a 0 length buffer, means that no more data will be written:
5380 // If no more buffers are pending, fill output track buffer to make sure it is started
5381 // by output mixer.
5382 if (frames == 0 && mBufferQueue.size() == 0) {
5383 if (mCblk->user < mCblk->frameCount) {
5384 frames = mCblk->frameCount - mCblk->user;
5385 pInBuffer = new Buffer;
5386 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5387 pInBuffer->frameCount = frames;
5388 pInBuffer->i16 = pInBuffer->mBuffer;
5389 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5390 mBufferQueue.add(pInBuffer);
5391 } else if (mActive) {
5392 stop();
5393 }
5394 }
5395
5396 return outputBufferFull;
5397}
5398
5399status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5400{
5401 int active;
5402 status_t result;
5403 audio_track_cblk_t* cblk = mCblk;
5404 uint32_t framesReq = buffer->frameCount;
5405
Steve Block3856b092011-10-20 11:56:00 +01005406// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005407 buffer->frameCount = 0;
5408
5409 uint32_t framesAvail = cblk->framesAvailable();
5410
5411
5412 if (framesAvail == 0) {
5413 Mutex::Autolock _l(cblk->lock);
5414 goto start_loop_here;
5415 while (framesAvail == 0) {
5416 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005417 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005418 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005419 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005420 }
5421 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5422 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005423 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005424 }
5425 // read the server count again
5426 start_loop_here:
5427 framesAvail = cblk->framesAvailable_l();
5428 }
5429 }
5430
5431// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005432// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005433// }
5434
5435 if (framesReq > framesAvail) {
5436 framesReq = framesAvail;
5437 }
5438
5439 uint32_t u = cblk->user;
5440 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5441
Marco Nelissena1472d92012-03-30 14:36:54 -07005442 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005443 framesReq = bufferEnd - u;
5444 }
5445
5446 buffer->frameCount = framesReq;
5447 buffer->raw = (void *)cblk->buffer(u);
5448 return NO_ERROR;
5449}
5450
5451
5452void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5453{
5454 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005455
5456 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005457 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005458 delete [] pBuffer->mBuffer;
5459 delete pBuffer;
5460 }
5461 mBufferQueue.clear();
5462}
5463
5464// ----------------------------------------------------------------------------
5465
5466AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5467 : RefBase(),
5468 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005469 // 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 -07005470 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005471 mPid(pid),
5472 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005473{
5474 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5475}
5476
5477// Client destructor must be called with AudioFlinger::mLock held
5478AudioFlinger::Client::~Client()
5479{
5480 mAudioFlinger->removeClient_l(mPid);
5481}
5482
Glenn Kasten435dbe62012-01-30 10:15:48 -08005483sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005484{
5485 return mMemoryDealer;
5486}
5487
John Grossman4ff14ba2012-02-08 16:37:41 -08005488// Reserve one of the limited slots for a timed audio track associated
5489// with this client
5490bool AudioFlinger::Client::reserveTimedTrack()
5491{
5492 const int kMaxTimedTracksPerClient = 4;
5493
5494 Mutex::Autolock _l(mTimedTrackLock);
5495
5496 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5497 ALOGW("can not create timed track - pid %d has exceeded the limit",
5498 mPid);
5499 return false;
5500 }
5501
5502 mTimedTrackCount++;
5503 return true;
5504}
5505
5506// Release a slot for a timed audio track
5507void AudioFlinger::Client::releaseTimedTrack()
5508{
5509 Mutex::Autolock _l(mTimedTrackLock);
5510 mTimedTrackCount--;
5511}
5512
Mathias Agopian65ab4712010-07-14 17:59:35 -07005513// ----------------------------------------------------------------------------
5514
5515AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5516 const sp<IAudioFlingerClient>& client,
5517 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005518 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005519{
5520}
5521
5522AudioFlinger::NotificationClient::~NotificationClient()
5523{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005524}
5525
5526void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5527{
5528 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005529 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005530}
5531
5532// ----------------------------------------------------------------------------
5533
5534AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5535 : BnAudioTrack(),
5536 mTrack(track)
5537{
5538}
5539
5540AudioFlinger::TrackHandle::~TrackHandle() {
5541 // just stop the track on deletion, associated resources
5542 // will be freed from the main thread once all pending buffers have
5543 // been played. Unless it's not in the active track list, in which
5544 // case we free everything now...
5545 mTrack->destroy();
5546}
5547
Glenn Kasten90716c52012-01-26 13:40:12 -08005548sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5549 return mTrack->getCblk();
5550}
5551
Glenn Kasten3acbd052012-02-28 10:39:56 -08005552status_t AudioFlinger::TrackHandle::start() {
5553 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005554}
5555
5556void AudioFlinger::TrackHandle::stop() {
5557 mTrack->stop();
5558}
5559
5560void AudioFlinger::TrackHandle::flush() {
5561 mTrack->flush();
5562}
5563
5564void AudioFlinger::TrackHandle::mute(bool e) {
5565 mTrack->mute(e);
5566}
5567
5568void AudioFlinger::TrackHandle::pause() {
5569 mTrack->pause();
5570}
5571
Mathias Agopian65ab4712010-07-14 17:59:35 -07005572status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5573{
5574 return mTrack->attachAuxEffect(EffectId);
5575}
5576
John Grossman4ff14ba2012-02-08 16:37:41 -08005577status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5578 sp<IMemory>* buffer) {
5579 if (!mTrack->isTimedTrack())
5580 return INVALID_OPERATION;
5581
5582 PlaybackThread::TimedTrack* tt =
5583 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5584 return tt->allocateTimedBuffer(size, buffer);
5585}
5586
5587status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5588 int64_t pts) {
5589 if (!mTrack->isTimedTrack())
5590 return INVALID_OPERATION;
5591
5592 PlaybackThread::TimedTrack* tt =
5593 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5594 return tt->queueTimedBuffer(buffer, pts);
5595}
5596
5597status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5598 const LinearTransform& xform, int target) {
5599
5600 if (!mTrack->isTimedTrack())
5601 return INVALID_OPERATION;
5602
5603 PlaybackThread::TimedTrack* tt =
5604 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5605 return tt->setMediaTimeTransform(
5606 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5607}
5608
Mathias Agopian65ab4712010-07-14 17:59:35 -07005609status_t AudioFlinger::TrackHandle::onTransact(
5610 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5611{
5612 return BnAudioTrack::onTransact(code, data, reply, flags);
5613}
5614
5615// ----------------------------------------------------------------------------
5616
5617sp<IAudioRecord> AudioFlinger::openRecord(
5618 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005619 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005620 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005621 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005622 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005623 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005624 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005625 int *sessionId,
5626 status_t *status)
5627{
5628 sp<RecordThread::RecordTrack> recordTrack;
5629 sp<RecordHandle> recordHandle;
5630 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005631 status_t lStatus;
5632 RecordThread *thread;
5633 size_t inFrameCount;
5634 int lSessionId;
5635
5636 // check calling permissions
5637 if (!recordingAllowed()) {
5638 lStatus = PERMISSION_DENIED;
5639 goto Exit;
5640 }
5641
5642 // add client to list
5643 { // scope for mLock
5644 Mutex::Autolock _l(mLock);
5645 thread = checkRecordThread_l(input);
5646 if (thread == NULL) {
5647 lStatus = BAD_VALUE;
5648 goto Exit;
5649 }
5650
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005651 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005652
5653 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005654 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005655 lSessionId = *sessionId;
5656 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005657 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005658 if (sessionId != NULL) {
5659 *sessionId = lSessionId;
5660 }
5661 }
5662 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005663 recordTrack = thread->createRecordTrack_l(client,
5664 sampleRate,
5665 format,
5666 channelMask,
5667 frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005668 lSessionId,
5669 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005670 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005671 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005672 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5673 // destructor is called by the TrackBase destructor with mLock held
5674 client.clear();
5675 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005676 goto Exit;
5677 }
5678
5679 // return to handle to client
5680 recordHandle = new RecordHandle(recordTrack);
5681 lStatus = NO_ERROR;
5682
5683Exit:
5684 if (status) {
5685 *status = lStatus;
5686 }
5687 return recordHandle;
5688}
5689
5690// ----------------------------------------------------------------------------
5691
5692AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5693 : BnAudioRecord(),
5694 mRecordTrack(recordTrack)
5695{
5696}
5697
5698AudioFlinger::RecordHandle::~RecordHandle() {
5699 stop();
5700}
5701
Glenn Kasten90716c52012-01-26 13:40:12 -08005702sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5703 return mRecordTrack->getCblk();
5704}
5705
Glenn Kasten3acbd052012-02-28 10:39:56 -08005706status_t AudioFlinger::RecordHandle::start(int event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005707 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005708 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005709}
5710
5711void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01005712 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005713 mRecordTrack->stop();
5714}
5715
Mathias Agopian65ab4712010-07-14 17:59:35 -07005716status_t AudioFlinger::RecordHandle::onTransact(
5717 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5718{
5719 return BnAudioRecord::onTransact(code, data, reply, flags);
5720}
5721
5722// ----------------------------------------------------------------------------
5723
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005724AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5725 AudioStreamIn *input,
5726 uint32_t sampleRate,
5727 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005728 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005729 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005730 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005731 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5732 // mRsmpInIndex and mInputBytes set by readInputParameters()
5733 mReqChannelCount(popcount(channels)),
5734 mReqSampleRate(sampleRate)
5735 // mBytesRead is only meaningful while active, and so is cleared in start()
5736 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005737{
Glenn Kasten480b4682012-02-28 12:30:08 -08005738 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005739
Mathias Agopian65ab4712010-07-14 17:59:35 -07005740 readInputParameters();
5741}
5742
5743
5744AudioFlinger::RecordThread::~RecordThread()
5745{
5746 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005747 delete mResampler;
5748 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005749}
5750
5751void AudioFlinger::RecordThread::onFirstRef()
5752{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005753 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005754}
5755
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005756status_t AudioFlinger::RecordThread::readyToRun()
5757{
5758 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005759 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005760 return status;
5761}
5762
Mathias Agopian65ab4712010-07-14 17:59:35 -07005763bool AudioFlinger::RecordThread::threadLoop()
5764{
5765 AudioBufferProvider::Buffer buffer;
5766 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005767 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005768
Eric Laurent44d98482010-09-30 16:12:31 -07005769 nsecs_t lastWarning = 0;
5770
Eric Laurentfeb0db62011-07-22 09:04:31 -07005771 acquireWakeLock();
5772
Mathias Agopian65ab4712010-07-14 17:59:35 -07005773 // start recording
5774 while (!exitPending()) {
5775
5776 processConfigEvents();
5777
5778 { // scope for mLock
5779 Mutex::Autolock _l(mLock);
5780 checkForNewParameters_l();
5781 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
5782 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005783 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005784 mStandby = true;
5785 }
5786
5787 if (exitPending()) break;
5788
Eric Laurentfeb0db62011-07-22 09:04:31 -07005789 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005790 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005791 // go to sleep
5792 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005793 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005794 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005795 continue;
5796 }
5797 if (mActiveTrack != 0) {
5798 if (mActiveTrack->mState == TrackBase::PAUSING) {
5799 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005800 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005801 mStandby = true;
5802 }
5803 mActiveTrack.clear();
5804 mStartStopCond.broadcast();
5805 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
5806 if (mReqChannelCount != mActiveTrack->channelCount()) {
5807 mActiveTrack.clear();
5808 mStartStopCond.broadcast();
5809 } else if (mBytesRead != 0) {
5810 // record start succeeds only if first read from audio input
5811 // succeeds
5812 if (mBytesRead > 0) {
5813 mActiveTrack->mState = TrackBase::ACTIVE;
5814 } else {
5815 mActiveTrack.clear();
5816 }
5817 mStartStopCond.broadcast();
5818 }
5819 mStandby = false;
5820 }
5821 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005822 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005823 }
5824
5825 if (mActiveTrack != 0) {
5826 if (mActiveTrack->mState != TrackBase::ACTIVE &&
5827 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005828 unlockEffectChains(effectChains);
5829 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005830 continue;
5831 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005832 for (size_t i = 0; i < effectChains.size(); i ++) {
5833 effectChains[i]->process_l();
5834 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005835
Mathias Agopian65ab4712010-07-14 17:59:35 -07005836 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005837 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005838 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08005839 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005840 // no resampling
5841 while (framesOut) {
5842 size_t framesIn = mFrameCount - mRsmpInIndex;
5843 if (framesIn) {
5844 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
5845 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
5846 if (framesIn > framesOut)
5847 framesIn = framesOut;
5848 mRsmpInIndex += framesIn;
5849 framesOut -= framesIn;
5850 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07005851 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005852 memcpy(dst, src, framesIn * mFrameSize);
5853 } else {
5854 int16_t *src16 = (int16_t *)src;
5855 int16_t *dst16 = (int16_t *)dst;
5856 if (mChannelCount == 1) {
5857 while (framesIn--) {
5858 *dst16++ = *src16;
5859 *dst16++ = *src16++;
5860 }
5861 } else {
5862 while (framesIn--) {
5863 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
5864 src16 += 2;
5865 }
5866 }
5867 }
5868 }
5869 if (framesOut && mFrameCount == mRsmpInIndex) {
5870 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005871 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005872 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005873 framesOut = 0;
5874 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07005875 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005876 mRsmpInIndex = 0;
5877 }
5878 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00005879 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005880 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5881 // Force input into standby so that it tries to
5882 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005883 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005884 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005885 }
5886 mRsmpInIndex = mFrameCount;
5887 framesOut = 0;
5888 buffer.frameCount = 0;
5889 }
5890 }
5891 }
5892 } else {
5893 // resampling
5894
5895 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
5896 // alter output frame count as if we were expecting stereo samples
5897 if (mChannelCount == 1 && mReqChannelCount == 1) {
5898 framesOut >>= 1;
5899 }
5900 mResampler->resample(mRsmpOutBuffer, framesOut, this);
5901 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
5902 // are 32 bit aligned which should be always true.
5903 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005904 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005905 // the resampler always outputs stereo samples: do post stereo to mono conversion
5906 int16_t *src = (int16_t *)mRsmpOutBuffer;
5907 int16_t *dst = buffer.i16;
5908 while (framesOut--) {
5909 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
5910 src += 2;
5911 }
5912 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08005913 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005914 }
5915
5916 }
Eric Laurenta011e352012-03-29 15:51:43 -07005917 if (mFramestoDrop == 0) {
5918 mActiveTrack->releaseBuffer(&buffer);
5919 } else {
5920 if (mFramestoDrop > 0) {
5921 mFramestoDrop -= buffer.frameCount;
5922 if (mFramestoDrop < 0) {
5923 mFramestoDrop = 0;
5924 }
5925 }
5926 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005927 mActiveTrack->overflow();
5928 }
5929 // client isn't retrieving buffers fast enough
5930 else {
Eric Laurent44d98482010-09-30 16:12:31 -07005931 if (!mActiveTrack->setOverflow()) {
5932 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08005933 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005934 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07005935 lastWarning = now;
5936 }
5937 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005938 // Release the processor for a while before asking for a new buffer.
5939 // This will give the application more chance to read from the buffer and
5940 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005941 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005942 }
5943 }
Eric Laurentec437d82011-07-26 20:54:46 -07005944 // enable changes in effect chain
5945 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005946 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005947 }
5948
5949 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005950 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005951 }
5952 mActiveTrack.clear();
5953
5954 mStartStopCond.broadcast();
5955
Eric Laurentfeb0db62011-07-22 09:04:31 -07005956 releaseWakeLock();
5957
Steve Block3856b092011-10-20 11:56:00 +01005958 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005959 return false;
5960}
5961
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005962
5963sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
5964 const sp<AudioFlinger::Client>& client,
5965 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005966 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005967 int channelMask,
5968 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005969 int sessionId,
5970 status_t *status)
5971{
5972 sp<RecordTrack> track;
5973 status_t lStatus;
5974
5975 lStatus = initCheck();
5976 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00005977 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005978 goto Exit;
5979 }
5980
5981 { // scope for mLock
5982 Mutex::Autolock _l(mLock);
5983
5984 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005985 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005986
Glenn Kasten7378ca52012-01-20 13:44:40 -08005987 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005988 lStatus = NO_MEMORY;
5989 goto Exit;
5990 }
5991
5992 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005993 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5994 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005995 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005996 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
5997 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005998 }
5999 lStatus = NO_ERROR;
6000
6001Exit:
6002 if (status) {
6003 *status = lStatus;
6004 }
6005 return track;
6006}
6007
Eric Laurenta011e352012-03-29 15:51:43 -07006008status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006009 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006010 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006011{
Glenn Kasten58912562012-04-03 10:45:00 -07006012 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006013 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006014 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006015
6016 if (event == AudioSystem::SYNC_EVENT_NONE) {
6017 mSyncStartEvent.clear();
6018 mFramestoDrop = 0;
6019 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6020 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6021 triggerSession,
6022 recordTrack->sessionId(),
6023 syncStartEventCallback,
6024 this);
6025 mFramestoDrop = -1;
6026 }
6027
Mathias Agopian65ab4712010-07-14 17:59:35 -07006028 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006029 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006030 if (mActiveTrack != 0) {
6031 if (recordTrack != mActiveTrack.get()) {
6032 status = -EBUSY;
6033 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6034 mActiveTrack->mState = TrackBase::ACTIVE;
6035 }
6036 return status;
6037 }
6038
6039 recordTrack->mState = TrackBase::IDLE;
6040 mActiveTrack = recordTrack;
6041 mLock.unlock();
6042 status_t status = AudioSystem::startInput(mId);
6043 mLock.lock();
6044 if (status != NO_ERROR) {
6045 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006046 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006047 return status;
6048 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006049 mRsmpInIndex = mFrameCount;
6050 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006051 if (mResampler != NULL) {
6052 mResampler->reset();
6053 }
6054 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006055 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006056 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006057 mWaitWorkCV.signal();
6058 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006059 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006060 mActiveTrack.clear();
6061 status = INVALID_OPERATION;
6062 goto startError;
6063 }
6064 mStartStopCond.wait(mLock);
6065 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006066 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006067 status = BAD_VALUE;
6068 goto startError;
6069 }
Steve Block3856b092011-10-20 11:56:00 +01006070 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006071 return status;
6072 }
6073startError:
6074 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006075 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006076 return status;
6077}
6078
Eric Laurenta011e352012-03-29 15:51:43 -07006079void AudioFlinger::RecordThread::clearSyncStartEvent()
6080{
6081 if (mSyncStartEvent != 0) {
6082 mSyncStartEvent->cancel();
6083 }
6084 mSyncStartEvent.clear();
6085}
6086
6087void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6088{
6089 sp<SyncEvent> strongEvent = event.promote();
6090
6091 if (strongEvent != 0) {
6092 RecordThread *me = (RecordThread *)strongEvent->cookie();
6093 me->handleSyncStartEvent(strongEvent);
6094 }
6095}
6096
6097void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6098{
6099 ALOGV("handleSyncStartEvent() mActiveTrack %p session %d event->listenerSession() %d",
6100 mActiveTrack.get(),
6101 mActiveTrack.get() ? mActiveTrack->sessionId() : 0,
6102 event->listenerSession());
6103
6104 if (mActiveTrack != 0 &&
6105 event == mSyncStartEvent) {
6106 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6107 // from audio HAL
6108 mFramestoDrop = mFrameCount * 2;
6109 mSyncStartEvent.clear();
6110 }
6111}
6112
Mathias Agopian65ab4712010-07-14 17:59:35 -07006113void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006114 ALOGV("RecordThread::stop");
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006115 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006116 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006117 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006118 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
6119 mActiveTrack->mState = TrackBase::PAUSING;
6120 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006121 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006122 return;
6123 }
6124 mStartStopCond.wait(mLock);
6125 // if we have been restarted, recordTrack == mActiveTrack.get() here
6126 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
6127 mLock.unlock();
6128 AudioSystem::stopInput(mId);
6129 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01006130 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006131 }
6132 }
6133 }
6134}
6135
Eric Laurenta011e352012-03-29 15:51:43 -07006136bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6137{
6138 return false;
6139}
6140
6141status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6142{
6143 if (!isValidSyncEvent(event)) {
6144 return BAD_VALUE;
6145 }
6146
6147 Mutex::Autolock _l(mLock);
6148
6149 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6150 mTrack->setSyncEvent(event);
6151 return NO_ERROR;
6152 }
6153 return NAME_NOT_FOUND;
6154}
6155
Mathias Agopian65ab4712010-07-14 17:59:35 -07006156status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6157{
6158 const size_t SIZE = 256;
6159 char buffer[SIZE];
6160 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006161
6162 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6163 result.append(buffer);
6164
6165 if (mActiveTrack != 0) {
6166 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006167 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006168 mActiveTrack->dump(buffer, SIZE);
6169 result.append(buffer);
6170
6171 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6172 result.append(buffer);
6173 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6174 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006175 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006176 result.append(buffer);
6177 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6178 result.append(buffer);
6179 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6180 result.append(buffer);
6181
6182
6183 } else {
6184 result.append("No record client\n");
6185 }
6186 write(fd, result.string(), result.size());
6187
6188 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006189 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006190
6191 return NO_ERROR;
6192}
6193
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006194// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006195status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006196{
6197 size_t framesReq = buffer->frameCount;
6198 size_t framesReady = mFrameCount - mRsmpInIndex;
6199 int channelCount;
6200
6201 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006202 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006203 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006204 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006205 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6206 // Force input into standby so that it tries to
6207 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07006208 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006209 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006210 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006211 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006212 buffer->frameCount = 0;
6213 return NOT_ENOUGH_DATA;
6214 }
6215 mRsmpInIndex = 0;
6216 framesReady = mFrameCount;
6217 }
6218
6219 if (framesReq > framesReady) {
6220 framesReq = framesReady;
6221 }
6222
6223 if (mChannelCount == 1 && mReqChannelCount == 2) {
6224 channelCount = 1;
6225 } else {
6226 channelCount = 2;
6227 }
6228 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6229 buffer->frameCount = framesReq;
6230 return NO_ERROR;
6231}
6232
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006233// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006234void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6235{
6236 mRsmpInIndex += buffer->frameCount;
6237 buffer->frameCount = 0;
6238}
6239
6240bool AudioFlinger::RecordThread::checkForNewParameters_l()
6241{
6242 bool reconfig = false;
6243
6244 while (!mNewParameters.isEmpty()) {
6245 status_t status = NO_ERROR;
6246 String8 keyValuePair = mNewParameters[0];
6247 AudioParameter param = AudioParameter(keyValuePair);
6248 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006249 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006250 int reqSamplingRate = mReqSampleRate;
6251 int reqChannelCount = mReqChannelCount;
6252
6253 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6254 reqSamplingRate = value;
6255 reconfig = true;
6256 }
6257 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006258 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006259 reconfig = true;
6260 }
6261 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006262 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006263 reconfig = true;
6264 }
6265 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6266 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006267 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006268 // if frame count is changed after track creation
6269 if (mActiveTrack != 0) {
6270 status = INVALID_OPERATION;
6271 } else {
6272 reconfig = true;
6273 }
6274 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006275 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6276 // forward device change to effects that have requested to be
6277 // aware of attached audio device.
6278 for (size_t i = 0; i < mEffectChains.size(); i++) {
6279 mEffectChains[i]->setDevice_l(value);
6280 }
6281 // store input device and output device but do not forward output device to audio HAL.
6282 // Note that status is ignored by the caller for output device
6283 // (see AudioFlinger::setParameters()
6284 if (value & AUDIO_DEVICE_OUT_ALL) {
6285 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
6286 status = BAD_VALUE;
6287 } else {
6288 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006289 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6290 if (mTrack != NULL) {
6291 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006292 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006293 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6294 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6295 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006296 }
6297 mDevice |= (uint32_t)value;
6298 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006299 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006300 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006301 if (status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006302 mInput->stream->common.standby(&mInput->stream->common);
6303 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6304 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006305 }
6306 if (reconfig) {
6307 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006308 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006309 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006310 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006311 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6312 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006313 status = NO_ERROR;
6314 }
6315 if (status == NO_ERROR) {
6316 readInputParameters();
6317 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6318 }
6319 }
6320 }
6321
6322 mNewParameters.removeAt(0);
6323
6324 mParamStatus = status;
6325 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006326 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6327 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006328 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006329 }
6330 return reconfig;
6331}
6332
6333String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6334{
Dima Zavinfce7a472011-04-19 22:30:36 -07006335 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006336 String8 out_s8 = String8();
6337
6338 Mutex::Autolock _l(mLock);
6339 if (initCheck() != NO_ERROR) {
6340 return out_s8;
6341 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006342
Dima Zavin799a70e2011-04-18 16:57:27 -07006343 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006344 out_s8 = String8(s);
6345 free(s);
6346 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006347}
6348
6349void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6350 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006351 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006352
6353 switch (event) {
6354 case AudioSystem::INPUT_OPENED:
6355 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006356 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006357 desc.samplingRate = mSampleRate;
6358 desc.format = mFormat;
6359 desc.frameCount = mFrameCount;
6360 desc.latency = 0;
6361 param2 = &desc;
6362 break;
6363
6364 case AudioSystem::INPUT_CLOSED:
6365 default:
6366 break;
6367 }
6368 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6369}
6370
6371void AudioFlinger::RecordThread::readInputParameters()
6372{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006373 delete mRsmpInBuffer;
6374 // mRsmpInBuffer is always assigned a new[] below
6375 delete mRsmpOutBuffer;
6376 mRsmpOutBuffer = NULL;
6377 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006378 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006379
Dima Zavin799a70e2011-04-18 16:57:27 -07006380 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006381 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6382 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006383 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006384 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006385 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006386 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006387 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006388 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6389
Glenn Kasten53d76db2012-03-08 12:32:47 -08006390 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006391 {
6392 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006393 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6394 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006395 if (mChannelCount == 1 && mReqChannelCount == 2) {
6396 channelCount = 1;
6397 } else {
6398 channelCount = 2;
6399 }
6400 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6401 mResampler->setSampleRate(mSampleRate);
6402 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6403 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6404
6405 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6406 if (mChannelCount == 1 && mReqChannelCount == 1) {
6407 mFrameCount >>= 1;
6408 }
6409
6410 }
6411 mRsmpInIndex = mFrameCount;
6412}
6413
6414unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6415{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006416 Mutex::Autolock _l(mLock);
6417 if (initCheck() != NO_ERROR) {
6418 return 0;
6419 }
6420
Dima Zavin799a70e2011-04-18 16:57:27 -07006421 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006422}
6423
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006424uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6425{
6426 Mutex::Autolock _l(mLock);
6427 uint32_t result = 0;
6428 if (getEffectChain_l(sessionId) != 0) {
6429 result = EFFECT_SESSION;
6430 }
6431
6432 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6433 result |= TRACK_SESSION;
6434 }
6435
6436 return result;
6437}
6438
Eric Laurent59bd0da2011-08-01 09:52:20 -07006439AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6440{
6441 Mutex::Autolock _l(mLock);
6442 return mTrack;
6443}
6444
Glenn Kastenaed850d2012-01-26 09:46:34 -08006445AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006446{
6447 Mutex::Autolock _l(mLock);
6448 return mInput;
6449}
6450
6451AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6452{
6453 Mutex::Autolock _l(mLock);
6454 AudioStreamIn *input = mInput;
6455 mInput = NULL;
6456 return input;
6457}
6458
6459// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006460audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006461{
6462 if (mInput == NULL) {
6463 return NULL;
6464 }
6465 return &mInput->stream->common;
6466}
6467
6468
Mathias Agopian65ab4712010-07-14 17:59:35 -07006469// ----------------------------------------------------------------------------
6470
Eric Laurenta4c5a552012-03-29 10:12:40 -07006471audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6472{
6473 if (!settingsAllowed()) {
6474 return 0;
6475 }
6476 Mutex::Autolock _l(mLock);
6477 return loadHwModule_l(name);
6478}
6479
6480// loadHwModule_l() must be called with AudioFlinger::mLock held
6481audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6482{
6483 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6484 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6485 ALOGW("loadHwModule() module %s already loaded", name);
6486 return mAudioHwDevs.keyAt(i);
6487 }
6488 }
6489
Eric Laurenta4c5a552012-03-29 10:12:40 -07006490 audio_hw_device_t *dev;
6491
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006492 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006493 if (rc) {
6494 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6495 return 0;
6496 }
6497
6498 mHardwareStatus = AUDIO_HW_INIT;
6499 rc = dev->init_check(dev);
6500 mHardwareStatus = AUDIO_HW_IDLE;
6501 if (rc) {
6502 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6503 return 0;
6504 }
6505
6506 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6507 (NULL != dev->set_master_volume)) {
6508 AutoMutex lock(mHardwareLock);
6509 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6510 dev->set_master_volume(dev, mMasterVolume);
6511 mHardwareStatus = AUDIO_HW_IDLE;
6512 }
6513
6514 audio_module_handle_t handle = nextUniqueId();
6515 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6516
6517 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006518 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006519
6520 return handle;
6521
6522}
6523
6524audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6525 audio_devices_t *pDevices,
6526 uint32_t *pSamplingRate,
6527 audio_format_t *pFormat,
6528 audio_channel_mask_t *pChannelMask,
6529 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006530 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006531{
6532 status_t status;
6533 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006534 struct audio_config config = {
6535 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6536 channel_mask: pChannelMask ? *pChannelMask : 0,
6537 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6538 };
6539 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006540 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006541
Eric Laurenta4c5a552012-03-29 10:12:40 -07006542 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6543 module,
Eric Laurent3f9c84c2012-04-03 15:36:53 -07006544 (pDevices != NULL) ? (int)*pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006545 config.sample_rate,
6546 config.format,
6547 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006548 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006549
6550 if (pDevices == NULL || *pDevices == 0) {
6551 return 0;
6552 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006553
Mathias Agopian65ab4712010-07-14 17:59:35 -07006554 Mutex::Autolock _l(mLock);
6555
Eric Laurenta4c5a552012-03-29 10:12:40 -07006556 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006557 if (outHwDev == NULL)
6558 return 0;
6559
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006560 audio_io_handle_t id = nextUniqueId();
6561
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006562 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006563
6564 status = outHwDev->open_output_stream(outHwDev,
6565 id,
6566 *pDevices,
6567 (audio_output_flags_t)flags,
6568 &config,
6569 &outStream);
6570
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006571 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006572 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006573 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006574 config.sample_rate,
6575 config.format,
6576 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006577 status);
6578
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006579 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006580 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006581
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006582 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006583 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6584 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006585 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006586 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006587 } else {
6588 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006589 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006590 }
6591 mPlaybackThreads.add(id, thread);
6592
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006593 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6594 if (pFormat != NULL) *pFormat = config.format;
6595 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006596 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006597
6598 // notify client processes of the new output creation
6599 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006600
6601 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006602 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006603 ALOGI("Using module %d has the primary audio interface", module);
6604 mPrimaryHardwareDev = outHwDev;
6605
6606 AutoMutex lock(mHardwareLock);
6607 mHardwareStatus = AUDIO_HW_SET_MODE;
6608 outHwDev->set_mode(outHwDev, mMode);
6609
6610 // Determine the level of master volume support the primary audio HAL has,
6611 // and set the initial master volume at the same time.
6612 float initialVolume = 1.0;
6613 mMasterVolumeSupportLvl = MVS_NONE;
6614
6615 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6616 if ((NULL != outHwDev->get_master_volume) &&
6617 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6618 mMasterVolumeSupportLvl = MVS_FULL;
6619 } else {
6620 mMasterVolumeSupportLvl = MVS_SETONLY;
6621 initialVolume = 1.0;
6622 }
6623
6624 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6625 if ((NULL == outHwDev->set_master_volume) ||
6626 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6627 mMasterVolumeSupportLvl = MVS_NONE;
6628 }
6629 // now that we have a primary device, initialize master volume on other devices
6630 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6631 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6632
6633 if ((dev != mPrimaryHardwareDev) &&
6634 (NULL != dev->set_master_volume)) {
6635 dev->set_master_volume(dev, initialVolume);
6636 }
6637 }
6638 mHardwareStatus = AUDIO_HW_IDLE;
6639 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
6640 ? initialVolume
6641 : 1.0;
6642 mMasterVolume = initialVolume;
6643 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006644 return id;
6645 }
6646
6647 return 0;
6648}
6649
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006650audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6651 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006652{
6653 Mutex::Autolock _l(mLock);
6654 MixerThread *thread1 = checkMixerThread_l(output1);
6655 MixerThread *thread2 = checkMixerThread_l(output2);
6656
6657 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006658 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006659 return 0;
6660 }
6661
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006662 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006663 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6664 thread->addOutputTrack(thread2);
6665 mPlaybackThreads.add(id, thread);
6666 // notify client processes of the new output creation
6667 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6668 return id;
6669}
6670
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006671status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006672{
6673 // keep strong reference on the playback thread so that
6674 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006675 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006676 {
6677 Mutex::Autolock _l(mLock);
6678 thread = checkPlaybackThread_l(output);
6679 if (thread == NULL) {
6680 return BAD_VALUE;
6681 }
6682
Steve Block3856b092011-10-20 11:56:00 +01006683 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006684
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006685 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006686 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006687 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006688 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6689 dupThread->removeOutputTrack((MixerThread *)thread.get());
6690 }
6691 }
6692 }
Glenn Kastena1117922012-01-26 10:53:32 -08006693 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006694 mPlaybackThreads.removeItem(output);
6695 }
6696 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006697 // The thread entity (active unit of execution) is no longer running here,
6698 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006699
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006700 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006701 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006702 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006703 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006704 out->hwDev->close_output_stream(out->hwDev, out->stream);
6705 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006706 }
6707 return NO_ERROR;
6708}
6709
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006710status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006711{
6712 Mutex::Autolock _l(mLock);
6713 PlaybackThread *thread = checkPlaybackThread_l(output);
6714
6715 if (thread == NULL) {
6716 return BAD_VALUE;
6717 }
6718
Steve Block3856b092011-10-20 11:56:00 +01006719 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006720 thread->suspend();
6721
6722 return NO_ERROR;
6723}
6724
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006725status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006726{
6727 Mutex::Autolock _l(mLock);
6728 PlaybackThread *thread = checkPlaybackThread_l(output);
6729
6730 if (thread == NULL) {
6731 return BAD_VALUE;
6732 }
6733
Steve Block3856b092011-10-20 11:56:00 +01006734 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006735
6736 thread->restore();
6737
6738 return NO_ERROR;
6739}
6740
Eric Laurenta4c5a552012-03-29 10:12:40 -07006741audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6742 audio_devices_t *pDevices,
6743 uint32_t *pSamplingRate,
6744 audio_format_t *pFormat,
6745 uint32_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006746{
6747 status_t status;
6748 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006749 struct audio_config config = {
6750 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6751 channel_mask: pChannelMask ? *pChannelMask : 0,
6752 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6753 };
6754 uint32_t reqSamplingRate = config.sample_rate;
6755 audio_format_t reqFormat = config.format;
6756 audio_channel_mask_t reqChannels = config.channel_mask;
6757 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006758 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006759
6760 if (pDevices == NULL || *pDevices == 0) {
6761 return 0;
6762 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006763
Mathias Agopian65ab4712010-07-14 17:59:35 -07006764 Mutex::Autolock _l(mLock);
6765
Eric Laurenta4c5a552012-03-29 10:12:40 -07006766 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006767 if (inHwDev == NULL)
6768 return 0;
6769
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006770 audio_io_handle_t id = nextUniqueId();
6771
6772 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006773 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006774 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006775 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006776 config.sample_rate,
6777 config.format,
6778 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006779 status);
6780
6781 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6782 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6783 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006784 if (status == BAD_VALUE &&
6785 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
6786 (config.sample_rate <= 2 * reqSamplingRate) &&
6787 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Steve Block3856b092011-10-20 11:56:00 +01006788 ALOGV("openInput() reopening with proposed sampling rate and channels");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006789 inStream = NULL;
6790 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006791 }
6792
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006793 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006794 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
6795
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006796 // Start record thread
6797 // RecorThread require both input and output device indication to forward to audio
6798 // pre processing modules
6799 uint32_t device = (*pDevices) | primaryOutputDevice_l();
6800 thread = new RecordThread(this,
6801 input,
6802 reqSamplingRate,
6803 reqChannels,
6804 id,
6805 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006806 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01006807 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08006808 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006809 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006810 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006811
Dima Zavin799a70e2011-04-18 16:57:27 -07006812 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006813
6814 // notify client processes of the new input creation
6815 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
6816 return id;
6817 }
6818
6819 return 0;
6820}
6821
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006822status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006823{
6824 // keep strong reference on the record thread so that
6825 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006826 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006827 {
6828 Mutex::Autolock _l(mLock);
6829 thread = checkRecordThread_l(input);
6830 if (thread == NULL) {
6831 return BAD_VALUE;
6832 }
6833
Steve Block3856b092011-10-20 11:56:00 +01006834 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08006835 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006836 mRecordThreads.removeItem(input);
6837 }
6838 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006839 // The thread entity (active unit of execution) is no longer running here,
6840 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006841
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006842 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006843 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006844 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07006845 in->hwDev->close_input_stream(in->hwDev, in->stream);
6846 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006847
6848 return NO_ERROR;
6849}
6850
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006851status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006852{
6853 Mutex::Autolock _l(mLock);
6854 MixerThread *dstThread = checkMixerThread_l(output);
6855 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006856 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006857 return BAD_VALUE;
6858 }
6859
Steve Block3856b092011-10-20 11:56:00 +01006860 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006861 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
6862
6863 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6864 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Glenn Kastena1117922012-01-26 10:53:32 -08006865 if (thread != dstThread && thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006866 MixerThread *srcThread = (MixerThread *)thread;
6867 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006868 }
Eric Laurentde070132010-07-13 04:45:46 -07006869 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006870
6871 return NO_ERROR;
6872}
6873
6874
6875int AudioFlinger::newAudioSessionId()
6876{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006877 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006878}
6879
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006880void AudioFlinger::acquireAudioSessionId(int audioSession)
6881{
6882 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006883 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006884 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006885 size_t num = mAudioSessionRefs.size();
6886 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006887 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006888 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6889 ref->mCnt++;
6890 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006891 return;
6892 }
6893 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006894 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
6895 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006896}
6897
6898void AudioFlinger::releaseAudioSessionId(int audioSession)
6899{
6900 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08006901 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01006902 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08006903 size_t num = mAudioSessionRefs.size();
6904 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006905 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006906 if (ref->mSessionid == audioSession && ref->mPid == caller) {
6907 ref->mCnt--;
6908 ALOGV(" decremented refcount to %d", ref->mCnt);
6909 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006910 mAudioSessionRefs.removeAt(i);
6911 delete ref;
6912 purgeStaleEffects_l();
6913 }
6914 return;
6915 }
6916 }
Steve Block5ff1dd52012-01-05 23:22:43 +00006917 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006918}
6919
6920void AudioFlinger::purgeStaleEffects_l() {
6921
Steve Block3856b092011-10-20 11:56:00 +01006922 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006923
6924 Vector< sp<EffectChain> > chains;
6925
6926 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6927 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
6928 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6929 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07006930 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
6931 chains.push(ec);
6932 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006933 }
6934 }
6935 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6936 sp<RecordThread> t = mRecordThreads.valueAt(i);
6937 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
6938 sp<EffectChain> ec = t->mEffectChains[j];
6939 chains.push(ec);
6940 }
6941 }
6942
6943 for (size_t i = 0; i < chains.size(); i++) {
6944 sp<EffectChain> ec = chains[i];
6945 int sessionid = ec->sessionId();
6946 sp<ThreadBase> t = ec->mThread.promote();
6947 if (t == 0) {
6948 continue;
6949 }
6950 size_t numsessionrefs = mAudioSessionRefs.size();
6951 bool found = false;
6952 for (size_t k = 0; k < numsessionrefs; k++) {
6953 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08006954 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01006955 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006956 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006957 found = true;
6958 break;
6959 }
6960 }
6961 if (!found) {
6962 // remove all effects from the chain
6963 while (ec->mEffects.size()) {
6964 sp<EffectModule> effect = ec->mEffects[0];
6965 effect->unPin();
6966 Mutex::Autolock _l (t->mLock);
6967 t->removeEffect_l(effect);
6968 for (size_t j = 0; j < effect->mHandles.size(); j++) {
6969 sp<EffectHandle> handle = effect->mHandles[j].promote();
6970 if (handle != 0) {
6971 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07006972 if (handle->mHasControl && handle->mEnabled) {
6973 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
6974 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006975 }
6976 }
6977 AudioSystem::unregisterEffect(effect->id());
6978 }
6979 }
6980 }
6981 return;
6982}
6983
Mathias Agopian65ab4712010-07-14 17:59:35 -07006984// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006985AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006986{
Glenn Kastena1117922012-01-26 10:53:32 -08006987 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006988}
6989
6990// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006991AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006992{
6993 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08006994 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006995}
6996
6997// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006998AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006999{
Glenn Kastena1117922012-01-26 10:53:32 -08007000 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007001}
7002
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007003uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007004{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007005 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007006}
7007
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007008AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007009{
7010 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7011 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007012 AudioStreamOut *output = thread->getOutput();
7013 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007014 return thread;
7015 }
7016 }
7017 return NULL;
7018}
7019
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007020uint32_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007021{
7022 PlaybackThread *thread = primaryPlaybackThread_l();
7023
7024 if (thread == NULL) {
7025 return 0;
7026 }
7027
7028 return thread->device();
7029}
7030
Eric Laurenta011e352012-03-29 15:51:43 -07007031sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7032 int triggerSession,
7033 int listenerSession,
7034 sync_event_callback_t callBack,
7035 void *cookie)
7036{
7037 Mutex::Autolock _l(mLock);
7038
7039 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7040 status_t playStatus = NAME_NOT_FOUND;
7041 status_t recStatus = NAME_NOT_FOUND;
7042 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7043 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7044 if (playStatus == NO_ERROR) {
7045 return event;
7046 }
7047 }
7048 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7049 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7050 if (recStatus == NO_ERROR) {
7051 return event;
7052 }
7053 }
7054 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7055 mPendingSyncEvents.add(event);
7056 } else {
7057 ALOGV("createSyncEvent() invalid event %d", event->type());
7058 event.clear();
7059 }
7060 return event;
7061}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007062
Mathias Agopian65ab4712010-07-14 17:59:35 -07007063// ----------------------------------------------------------------------------
7064// Effect management
7065// ----------------------------------------------------------------------------
7066
7067
Glenn Kastenf587ba52012-01-26 16:25:10 -08007068status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007069{
7070 Mutex::Autolock _l(mLock);
7071 return EffectQueryNumberEffects(numEffects);
7072}
7073
Glenn Kastenf587ba52012-01-26 16:25:10 -08007074status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007075{
7076 Mutex::Autolock _l(mLock);
7077 return EffectQueryEffect(index, descriptor);
7078}
7079
Glenn Kasten5e92a782012-01-30 07:40:52 -08007080status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007081 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007082{
7083 Mutex::Autolock _l(mLock);
7084 return EffectGetDescriptor(pUuid, descriptor);
7085}
7086
7087
Mathias Agopian65ab4712010-07-14 17:59:35 -07007088sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7089 effect_descriptor_t *pDesc,
7090 const sp<IEffectClient>& effectClient,
7091 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007092 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007093 int sessionId,
7094 status_t *status,
7095 int *id,
7096 int *enabled)
7097{
7098 status_t lStatus = NO_ERROR;
7099 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007100 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007101
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007102 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007103 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007104
7105 if (pDesc == NULL) {
7106 lStatus = BAD_VALUE;
7107 goto Exit;
7108 }
7109
Eric Laurent84e9a102010-09-23 16:10:16 -07007110 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007111 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007112 lStatus = PERMISSION_DENIED;
7113 goto Exit;
7114 }
7115
Dima Zavinfce7a472011-04-19 22:30:36 -07007116 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007117 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007118 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007119 lStatus = PERMISSION_DENIED;
7120 goto Exit;
7121 }
7122
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007123 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007124 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007125 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007126 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007127 lStatus = BAD_VALUE;
7128 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007129 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007130 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007131 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007132 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007133 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007134 }
7135 }
7136
Mathias Agopian65ab4712010-07-14 17:59:35 -07007137 {
7138 Mutex::Autolock _l(mLock);
7139
Mathias Agopian65ab4712010-07-14 17:59:35 -07007140
7141 if (!EffectIsNullUuid(&pDesc->uuid)) {
7142 // if uuid is specified, request effect descriptor
7143 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7144 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007145 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007146 goto Exit;
7147 }
7148 } else {
7149 // if uuid is not specified, look for an available implementation
7150 // of the required type in effect factory
7151 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007152 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007153 lStatus = BAD_VALUE;
7154 goto Exit;
7155 }
7156 uint32_t numEffects = 0;
7157 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007158 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007159 bool found = false;
7160
7161 lStatus = EffectQueryNumberEffects(&numEffects);
7162 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007163 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007164 goto Exit;
7165 }
7166 for (uint32_t i = 0; i < numEffects; i++) {
7167 lStatus = EffectQueryEffect(i, &desc);
7168 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007169 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007170 continue;
7171 }
7172 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7173 // If matching type found save effect descriptor. If the session is
7174 // 0 and the effect is not auxiliary, continue enumeration in case
7175 // an auxiliary version of this effect type is available
7176 found = true;
7177 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07007178 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007179 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7180 break;
7181 }
7182 }
7183 }
7184 if (!found) {
7185 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007186 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007187 goto Exit;
7188 }
7189 // For same effect type, chose auxiliary version over insert version if
7190 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007191 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007192 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
7193 memcpy(&desc, &d, sizeof(effect_descriptor_t));
7194 }
7195 }
7196
7197 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007198 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007199 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7200 lStatus = INVALID_OPERATION;
7201 goto Exit;
7202 }
7203
Eric Laurent59255e42011-07-27 19:49:51 -07007204 // check recording permission for visualizer
7205 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7206 !recordingAllowed()) {
7207 lStatus = PERMISSION_DENIED;
7208 goto Exit;
7209 }
7210
Mathias Agopian65ab4712010-07-14 17:59:35 -07007211 // return effect descriptor
7212 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
7213
7214 // If output is not specified try to find a matching audio session ID in one of the
7215 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007216 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7217 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007218 // Note: io is never 0 when creating an effect on an input
7219 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007220 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007221 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7222 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007223 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007224 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007225 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007226 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007227 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007228 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7229 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7230 io = mRecordThreads.keyAt(i);
7231 break;
7232 }
7233 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007234 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007235 // If no output thread contains the requested session ID, default to
7236 // first output. The effect chain will be moved to the correct output
7237 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007238 if (io == 0 && mPlaybackThreads.size()) {
7239 io = mPlaybackThreads.keyAt(0);
7240 }
Steve Block3856b092011-10-20 11:56:00 +01007241 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007242 }
7243 ThreadBase *thread = checkRecordThread_l(io);
7244 if (thread == NULL) {
7245 thread = checkPlaybackThread_l(io);
7246 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007247 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007248 lStatus = BAD_VALUE;
7249 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007250 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007251 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007252
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007253 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007254
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007255 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007256 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7257 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007258 if (handle != 0 && id != NULL) {
7259 *id = handle->id();
7260 }
7261 }
7262
7263Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007264 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007265 *status = lStatus;
7266 }
7267 return handle;
7268}
7269
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007270status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7271 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007272{
Steve Block3856b092011-10-20 11:56:00 +01007273 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007274 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007275 Mutex::Autolock _l(mLock);
7276 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007277 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007278 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007279 }
Eric Laurentde070132010-07-13 04:45:46 -07007280 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7281 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007282 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007283 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007284 }
Eric Laurentde070132010-07-13 04:45:46 -07007285 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7286 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007287 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007288 return BAD_VALUE;
7289 }
7290
7291 Mutex::Autolock _dl(dstThread->mLock);
7292 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007293 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007294
Mathias Agopian65ab4712010-07-14 17:59:35 -07007295 return NO_ERROR;
7296}
7297
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007298// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007299status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007300 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007301 AudioFlinger::PlaybackThread *dstThread,
7302 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007303{
Steve Block3856b092011-10-20 11:56:00 +01007304 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007305 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007306
Eric Laurent59255e42011-07-27 19:49:51 -07007307 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007308 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007309 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007310 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007311 return INVALID_OPERATION;
7312 }
7313
Eric Laurent39e94f82010-07-28 01:32:47 -07007314 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007315 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007316 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007317 // removed.
7318 srcThread->removeEffectChain_l(chain);
7319
7320 // transfer all effects one by one so that new effect chain is created on new thread with
7321 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007322 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007323 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007324 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007325 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7326 while (effect != 0) {
7327 srcThread->removeEffect_l(effect);
7328 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007329 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7330 if (effect->state() == EffectModule::ACTIVE ||
7331 effect->state() == EffectModule::STOPPING) {
7332 effect->start();
7333 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007334 // if the move request is not received from audio policy manager, the effect must be
7335 // re-registered with the new strategy and output
7336 if (dstChain == 0) {
7337 dstChain = effect->chain().promote();
7338 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007339 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007340 srcThread->addEffect_l(effect);
7341 return NO_INIT;
7342 }
7343 strategy = dstChain->strategy();
7344 }
7345 if (reRegister) {
7346 AudioSystem::unregisterEffect(effect->id());
7347 AudioSystem::registerEffect(&effect->desc(),
7348 dstOutput,
7349 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007350 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007351 effect->id());
7352 }
Eric Laurentde070132010-07-13 04:45:46 -07007353 effect = chain->getEffectFromId_l(0);
7354 }
7355
7356 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007357}
7358
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007359
Mathias Agopian65ab4712010-07-14 17:59:35 -07007360// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007361sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007362 const sp<AudioFlinger::Client>& client,
7363 const sp<IEffectClient>& effectClient,
7364 int32_t priority,
7365 int sessionId,
7366 effect_descriptor_t *desc,
7367 int *enabled,
7368 status_t *status
7369 )
7370{
7371 sp<EffectModule> effect;
7372 sp<EffectHandle> handle;
7373 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007374 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007375 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007376 bool effectCreated = false;
7377 bool effectRegistered = false;
7378
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007379 lStatus = initCheck();
7380 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007381 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007382 goto Exit;
7383 }
7384
7385 // Do not allow effects with session ID 0 on direct output or duplicating threads
7386 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007387 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007388 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007389 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007390 lStatus = BAD_VALUE;
7391 goto Exit;
7392 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007393 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007394 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007395 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007396 desc->name, desc->flags, mType);
7397 lStatus = BAD_VALUE;
7398 goto Exit;
7399 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007400
Steve Block3856b092011-10-20 11:56:00 +01007401 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007402
7403 { // scope for mLock
7404 Mutex::Autolock _l(mLock);
7405
7406 // check for existing effect chain with the requested audio session
7407 chain = getEffectChain_l(sessionId);
7408 if (chain == 0) {
7409 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007410 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007411 chain = new EffectChain(this, sessionId);
7412 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007413 chain->setStrategy(getStrategyForSession_l(sessionId));
7414 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007415 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007416 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007417 }
7418
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007419 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007420
7421 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007422 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007423 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007424 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007425 if (lStatus != NO_ERROR) {
7426 goto Exit;
7427 }
7428 effectRegistered = true;
7429 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007430 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007431 lStatus = effect->status();
7432 if (lStatus != NO_ERROR) {
7433 goto Exit;
7434 }
Eric Laurentcab11242010-07-15 12:50:15 -07007435 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007436 if (lStatus != NO_ERROR) {
7437 goto Exit;
7438 }
7439 effectCreated = true;
7440
7441 effect->setDevice(mDevice);
7442 effect->setMode(mAudioFlinger->getMode());
7443 }
7444 // create effect handle and connect it to effect module
7445 handle = new EffectHandle(effect, client, effectClient, priority);
7446 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08007447 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007448 *enabled = (int)effect->isEnabled();
7449 }
7450 }
7451
7452Exit:
7453 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007454 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007455 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007456 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007457 }
7458 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007459 AudioSystem::unregisterEffect(effect->id());
7460 }
7461 if (chainCreated) {
7462 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007463 }
7464 handle.clear();
7465 }
7466
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007467 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007468 *status = lStatus;
7469 }
7470 return handle;
7471}
7472
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007473sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7474{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007475 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007476 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007477}
7478
Eric Laurentde070132010-07-13 04:45:46 -07007479// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7480// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007481status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007482{
7483 // check for existing effect chain with the requested audio session
7484 int sessionId = effect->sessionId();
7485 sp<EffectChain> chain = getEffectChain_l(sessionId);
7486 bool chainCreated = false;
7487
7488 if (chain == 0) {
7489 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007490 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007491 chain = new EffectChain(this, sessionId);
7492 addEffectChain_l(chain);
7493 chain->setStrategy(getStrategyForSession_l(sessionId));
7494 chainCreated = true;
7495 }
Steve Block3856b092011-10-20 11:56:00 +01007496 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007497
7498 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007499 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007500 this, effect->desc().name, chain.get());
7501 return BAD_VALUE;
7502 }
7503
7504 status_t status = chain->addEffect_l(effect);
7505 if (status != NO_ERROR) {
7506 if (chainCreated) {
7507 removeEffectChain_l(chain);
7508 }
7509 return status;
7510 }
7511
7512 effect->setDevice(mDevice);
7513 effect->setMode(mAudioFlinger->getMode());
7514 return NO_ERROR;
7515}
7516
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007517void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007518
Steve Block3856b092011-10-20 11:56:00 +01007519 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007520 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007521 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7522 detachAuxEffect_l(effect->id());
7523 }
7524
7525 sp<EffectChain> chain = effect->chain().promote();
7526 if (chain != 0) {
7527 // remove effect chain if removing last effect
7528 if (chain->removeEffect_l(effect) == 0) {
7529 removeEffectChain_l(chain);
7530 }
7531 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007532 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007533 }
7534}
7535
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007536void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007537 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007538{
7539 effectChains = mEffectChains;
7540 for (size_t i = 0; i < mEffectChains.size(); i++) {
7541 mEffectChains[i]->lock();
7542 }
7543}
7544
7545void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007546 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007547{
7548 for (size_t i = 0; i < effectChains.size(); i++) {
7549 effectChains[i]->unlock();
7550 }
7551}
7552
7553sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7554{
7555 Mutex::Autolock _l(mLock);
7556 return getEffectChain_l(sessionId);
7557}
7558
7559sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7560{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007561 size_t size = mEffectChains.size();
7562 for (size_t i = 0; i < size; i++) {
7563 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007564 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007565 }
7566 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007567 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007568}
7569
Glenn Kastenf78aee72012-01-04 11:00:47 -08007570void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007571{
7572 Mutex::Autolock _l(mLock);
7573 size_t size = mEffectChains.size();
7574 for (size_t i = 0; i < size; i++) {
7575 mEffectChains[i]->setMode_l(mode);
7576 }
7577}
7578
7579void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007580 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007581 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007582
Mathias Agopian65ab4712010-07-14 17:59:35 -07007583 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007584 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007585 // delete the effect module if removing last handle on it
7586 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007587 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007588 removeEffect_l(effect);
7589 AudioSystem::unregisterEffect(effect->id());
7590 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007591 }
7592}
7593
7594status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7595{
7596 int session = chain->sessionId();
7597 int16_t *buffer = mMixBuffer;
7598 bool ownsBuffer = false;
7599
Steve Block3856b092011-10-20 11:56:00 +01007600 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007601 if (session > 0) {
7602 // Only one effect chain can be present in direct output thread and it uses
7603 // the mix buffer as input
7604 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007605 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007606 buffer = new int16_t[numSamples];
7607 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007608 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007609 ownsBuffer = true;
7610 }
7611
7612 // Attach all tracks with same session ID to this chain.
7613 for (size_t i = 0; i < mTracks.size(); ++i) {
7614 sp<Track> track = mTracks[i];
7615 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007616 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007617 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007618 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007619 }
7620 }
7621
7622 // indicate all active tracks in the chain
7623 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7624 sp<Track> track = mActiveTracks[i].promote();
7625 if (track == 0) continue;
7626 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007627 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007628 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007629 }
7630 }
7631 }
7632
7633 chain->setInBuffer(buffer, ownsBuffer);
7634 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007635 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007636 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007637 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7638 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007639 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007640 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7641 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007642 // Effect chain for other sessions are inserted at beginning of effect
7643 // chains list to be processed before output mix effects. Relative order between other
7644 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007645 size_t size = mEffectChains.size();
7646 size_t i = 0;
7647 for (i = 0; i < size; i++) {
7648 if (mEffectChains[i]->sessionId() < session) break;
7649 }
7650 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007651 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007652
7653 return NO_ERROR;
7654}
7655
7656size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7657{
7658 int session = chain->sessionId();
7659
Steve Block3856b092011-10-20 11:56:00 +01007660 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007661
7662 for (size_t i = 0; i < mEffectChains.size(); i++) {
7663 if (chain == mEffectChains[i]) {
7664 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007665 // detach all active tracks from the chain
7666 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7667 sp<Track> track = mActiveTracks[i].promote();
7668 if (track == 0) continue;
7669 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007670 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007671 chain.get(), session);
7672 chain->decActiveTrackCnt();
7673 }
7674 }
7675
Mathias Agopian65ab4712010-07-14 17:59:35 -07007676 // detach all tracks with same session ID from this chain
7677 for (size_t i = 0; i < mTracks.size(); ++i) {
7678 sp<Track> track = mTracks[i];
7679 if (session == track->sessionId()) {
7680 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007681 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007682 }
7683 }
Eric Laurentde070132010-07-13 04:45:46 -07007684 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007685 }
7686 }
7687 return mEffectChains.size();
7688}
7689
Eric Laurentde070132010-07-13 04:45:46 -07007690status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7691 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007692{
7693 Mutex::Autolock _l(mLock);
7694 return attachAuxEffect_l(track, EffectId);
7695}
7696
Eric Laurentde070132010-07-13 04:45:46 -07007697status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7698 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007699{
7700 status_t status = NO_ERROR;
7701
7702 if (EffectId == 0) {
7703 track->setAuxBuffer(0, NULL);
7704 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007705 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7706 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007707 if (effect != 0) {
7708 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7709 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7710 } else {
7711 status = INVALID_OPERATION;
7712 }
7713 } else {
7714 status = BAD_VALUE;
7715 }
7716 }
7717 return status;
7718}
7719
7720void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7721{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007722 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007723 sp<Track> track = mTracks[i];
7724 if (track->auxEffectId() == effectId) {
7725 attachAuxEffect_l(track, 0);
7726 }
7727 }
7728}
7729
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007730status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7731{
7732 // only one chain per input thread
7733 if (mEffectChains.size() != 0) {
7734 return INVALID_OPERATION;
7735 }
Steve Block3856b092011-10-20 11:56:00 +01007736 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007737
7738 chain->setInBuffer(NULL);
7739 chain->setOutBuffer(NULL);
7740
Eric Laurent59255e42011-07-27 19:49:51 -07007741 checkSuspendOnAddEffectChain_l(chain);
7742
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007743 mEffectChains.add(chain);
7744
7745 return NO_ERROR;
7746}
7747
7748size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7749{
Steve Block3856b092011-10-20 11:56:00 +01007750 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007751 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007752 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7753 chain.get(), mEffectChains.size(), this);
7754 if (mEffectChains.size() == 1) {
7755 mEffectChains.removeAt(0);
7756 }
7757 return 0;
7758}
7759
Mathias Agopian65ab4712010-07-14 17:59:35 -07007760// ----------------------------------------------------------------------------
7761// EffectModule implementation
7762// ----------------------------------------------------------------------------
7763
7764#undef LOG_TAG
7765#define LOG_TAG "AudioFlinger::EffectModule"
7766
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007767AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007768 const wp<AudioFlinger::EffectChain>& chain,
7769 effect_descriptor_t *desc,
7770 int id,
7771 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007772 : mThread(thread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007773 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007774{
Steve Block3856b092011-10-20 11:56:00 +01007775 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007776 int lStatus;
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007777 if (thread == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007778 return;
7779 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007780
7781 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
7782
7783 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007784 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007785
7786 if (mStatus != NO_ERROR) {
7787 return;
7788 }
7789 lStatus = init();
7790 if (lStatus < 0) {
7791 mStatus = lStatus;
7792 goto Error;
7793 }
7794
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007795 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
7796 mPinned = true;
7797 }
Steve Block3856b092011-10-20 11:56:00 +01007798 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007799 return;
7800Error:
7801 EffectRelease(mEffectInterface);
7802 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01007803 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007804}
7805
7806AudioFlinger::EffectModule::~EffectModule()
7807{
Steve Block3856b092011-10-20 11:56:00 +01007808 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007809 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007810 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
7811 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
7812 sp<ThreadBase> thread = mThread.promote();
7813 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007814 audio_stream_t *stream = thread->stream();
7815 if (stream != NULL) {
7816 stream->remove_audio_effect(stream, mEffectInterface);
7817 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007818 }
7819 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007820 // release effect engine
7821 EffectRelease(mEffectInterface);
7822 }
7823}
7824
Glenn Kasten435dbe62012-01-30 10:15:48 -08007825status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007826{
7827 status_t status;
7828
7829 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007830 int priority = handle->priority();
7831 size_t size = mHandles.size();
7832 sp<EffectHandle> h;
7833 size_t i;
7834 for (i = 0; i < size; i++) {
7835 h = mHandles[i].promote();
7836 if (h == 0) continue;
7837 if (h->priority() <= priority) break;
7838 }
7839 // if inserted in first place, move effect control from previous owner to this handle
7840 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007841 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007842 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007843 enabled = h->enabled();
7844 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007845 }
Eric Laurent59255e42011-07-27 19:49:51 -07007846 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007847 status = NO_ERROR;
7848 } else {
7849 status = ALREADY_EXISTS;
7850 }
Steve Block3856b092011-10-20 11:56:00 +01007851 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007852 mHandles.insertAt(handle, i);
7853 return status;
7854}
7855
7856size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
7857{
7858 Mutex::Autolock _l(mLock);
7859 size_t size = mHandles.size();
7860 size_t i;
7861 for (i = 0; i < size; i++) {
7862 if (mHandles[i] == handle) break;
7863 }
7864 if (i == size) {
7865 return size;
7866 }
Steve Block3856b092011-10-20 11:56:00 +01007867 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07007868
7869 bool enabled = false;
7870 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08007871 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01007872 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07007873 enabled = hdl->enabled();
7874 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007875 mHandles.removeAt(i);
7876 size = mHandles.size();
7877 // if removed from first place, move effect control from this handle to next in line
7878 if (i == 0 && size != 0) {
7879 sp<EffectHandle> h = mHandles[0].promote();
7880 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07007881 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007882 }
7883 }
7884
Eric Laurentec437d82011-07-26 20:54:46 -07007885 // Prevent calls to process() and other functions on effect interface from now on.
7886 // The effect engine will be released by the destructor when the last strong reference on
7887 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007888 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07007889 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07007890 }
7891
Mathias Agopian65ab4712010-07-14 17:59:35 -07007892 return size;
7893}
7894
Eric Laurent59255e42011-07-27 19:49:51 -07007895sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
7896{
7897 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08007898 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007899}
7900
Glenn Kasten58123c32012-02-03 10:32:24 -08007901void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007902{
Glenn Kasten90bebef2012-01-27 15:24:38 -08007903 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007904 // keep a strong reference on this EffectModule to avoid calling the
7905 // destructor before we exit
7906 sp<EffectModule> keep(this);
7907 {
7908 sp<ThreadBase> thread = mThread.promote();
7909 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007910 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007911 }
7912 }
7913}
7914
7915void AudioFlinger::EffectModule::updateState() {
7916 Mutex::Autolock _l(mLock);
7917
7918 switch (mState) {
7919 case RESTART:
7920 reset_l();
7921 // FALL THROUGH
7922
7923 case STARTING:
7924 // clear auxiliary effect input buffer for next accumulation
7925 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7926 memset(mConfig.inputCfg.buffer.raw,
7927 0,
7928 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
7929 }
7930 start_l();
7931 mState = ACTIVE;
7932 break;
7933 case STOPPING:
7934 stop_l();
7935 mDisableWaitCnt = mMaxDisableWaitCnt;
7936 mState = STOPPED;
7937 break;
7938 case STOPPED:
7939 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
7940 // turn off sequence.
7941 if (--mDisableWaitCnt == 0) {
7942 reset_l();
7943 mState = IDLE;
7944 }
7945 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007946 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07007947 break;
7948 }
7949}
7950
7951void AudioFlinger::EffectModule::process()
7952{
7953 Mutex::Autolock _l(mLock);
7954
Eric Laurentec437d82011-07-26 20:54:46 -07007955 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007956 mConfig.inputCfg.buffer.raw == NULL ||
7957 mConfig.outputCfg.buffer.raw == NULL) {
7958 return;
7959 }
7960
Eric Laurent8f45bd72010-08-31 13:50:07 -07007961 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007962 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
7963 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08007964 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007965 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07007966 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007967 }
7968
7969 // do the actual processing in the effect engine
7970 int ret = (*mEffectInterface)->process(mEffectInterface,
7971 &mConfig.inputCfg.buffer,
7972 &mConfig.outputCfg.buffer);
7973
7974 // force transition to IDLE state when engine is ready
7975 if (mState == STOPPED && ret == -ENODATA) {
7976 mDisableWaitCnt = 1;
7977 }
7978
7979 // clear auxiliary effect input buffer for next accumulation
7980 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08007981 memset(mConfig.inputCfg.buffer.raw, 0,
7982 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07007983 }
7984 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08007985 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
7986 // If an insert effect is idle and input buffer is different from output buffer,
7987 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07007988 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07007989 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08007990 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
7991 int16_t *in = mConfig.inputCfg.buffer.s16;
7992 int16_t *out = mConfig.outputCfg.buffer.s16;
7993 for (size_t i = 0; i < frameCnt; i++) {
7994 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007995 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007996 }
7997 }
7998}
7999
8000void AudioFlinger::EffectModule::reset_l()
8001{
8002 if (mEffectInterface == NULL) {
8003 return;
8004 }
8005 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8006}
8007
8008status_t AudioFlinger::EffectModule::configure()
8009{
8010 uint32_t channels;
8011 if (mEffectInterface == NULL) {
8012 return NO_INIT;
8013 }
8014
8015 sp<ThreadBase> thread = mThread.promote();
8016 if (thread == 0) {
8017 return DEAD_OBJECT;
8018 }
8019
8020 // TODO: handle configuration of effects replacing track process
8021 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008022 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008023 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07008024 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008025 }
8026
8027 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008028 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008029 } else {
8030 mConfig.inputCfg.channels = channels;
8031 }
8032 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07008033 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8034 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008035 mConfig.inputCfg.samplingRate = thread->sampleRate();
8036 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8037 mConfig.inputCfg.bufferProvider.cookie = NULL;
8038 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8039 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8040 mConfig.outputCfg.bufferProvider.cookie = NULL;
8041 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8042 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8043 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8044 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008045 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008046 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008047 // - in other sessions:
8048 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8049 // other effect: overwrites output buffer: input buffer == output buffer
8050 // Auxiliary effect:
8051 // accumulates in output buffer: input buffer != output buffer
8052 // Therefore: accumulate <=> input buffer != output buffer
8053 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8054 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8055 } else {
8056 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8057 }
8058 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8059 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8060 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8061 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8062
Steve Block3856b092011-10-20 11:56:00 +01008063 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008064 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8065
Mathias Agopian65ab4712010-07-14 17:59:35 -07008066 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008067 uint32_t size = sizeof(int);
8068 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008069 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008070 sizeof(effect_config_t),
8071 &mConfig,
8072 &size,
8073 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008074 if (status == 0) {
8075 status = cmdStatus;
8076 }
8077
8078 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8079 (1000 * mConfig.outputCfg.buffer.frameCount);
8080
8081 return status;
8082}
8083
8084status_t AudioFlinger::EffectModule::init()
8085{
8086 Mutex::Autolock _l(mLock);
8087 if (mEffectInterface == NULL) {
8088 return NO_INIT;
8089 }
8090 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008091 uint32_t size = sizeof(status_t);
8092 status_t status = (*mEffectInterface)->command(mEffectInterface,
8093 EFFECT_CMD_INIT,
8094 0,
8095 NULL,
8096 &size,
8097 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008098 if (status == 0) {
8099 status = cmdStatus;
8100 }
8101 return status;
8102}
8103
Eric Laurentec35a142011-10-05 17:42:25 -07008104status_t AudioFlinger::EffectModule::start()
8105{
8106 Mutex::Autolock _l(mLock);
8107 return start_l();
8108}
8109
Mathias Agopian65ab4712010-07-14 17:59:35 -07008110status_t AudioFlinger::EffectModule::start_l()
8111{
8112 if (mEffectInterface == NULL) {
8113 return NO_INIT;
8114 }
8115 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008116 uint32_t size = sizeof(status_t);
8117 status_t status = (*mEffectInterface)->command(mEffectInterface,
8118 EFFECT_CMD_ENABLE,
8119 0,
8120 NULL,
8121 &size,
8122 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008123 if (status == 0) {
8124 status = cmdStatus;
8125 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008126 if (status == 0 &&
8127 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8128 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8129 sp<ThreadBase> thread = mThread.promote();
8130 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008131 audio_stream_t *stream = thread->stream();
8132 if (stream != NULL) {
8133 stream->add_audio_effect(stream, mEffectInterface);
8134 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008135 }
8136 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008137 return status;
8138}
8139
Eric Laurentec437d82011-07-26 20:54:46 -07008140status_t AudioFlinger::EffectModule::stop()
8141{
8142 Mutex::Autolock _l(mLock);
8143 return stop_l();
8144}
8145
Mathias Agopian65ab4712010-07-14 17:59:35 -07008146status_t AudioFlinger::EffectModule::stop_l()
8147{
8148 if (mEffectInterface == NULL) {
8149 return NO_INIT;
8150 }
8151 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008152 uint32_t size = sizeof(status_t);
8153 status_t status = (*mEffectInterface)->command(mEffectInterface,
8154 EFFECT_CMD_DISABLE,
8155 0,
8156 NULL,
8157 &size,
8158 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008159 if (status == 0) {
8160 status = cmdStatus;
8161 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008162 if (status == 0 &&
8163 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8164 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8165 sp<ThreadBase> thread = mThread.promote();
8166 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008167 audio_stream_t *stream = thread->stream();
8168 if (stream != NULL) {
8169 stream->remove_audio_effect(stream, mEffectInterface);
8170 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008171 }
8172 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008173 return status;
8174}
8175
Eric Laurent25f43952010-07-28 05:40:18 -07008176status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8177 uint32_t cmdSize,
8178 void *pCmdData,
8179 uint32_t *replySize,
8180 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008181{
8182 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008183// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008184
Eric Laurentec437d82011-07-26 20:54:46 -07008185 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008186 return NO_INIT;
8187 }
Eric Laurent25f43952010-07-28 05:40:18 -07008188 status_t status = (*mEffectInterface)->command(mEffectInterface,
8189 cmdCode,
8190 cmdSize,
8191 pCmdData,
8192 replySize,
8193 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008194 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008195 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008196 for (size_t i = 1; i < mHandles.size(); i++) {
8197 sp<EffectHandle> h = mHandles[i].promote();
8198 if (h != 0) {
8199 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8200 }
8201 }
8202 }
8203 return status;
8204}
8205
8206status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8207{
Eric Laurentdb7c0792011-08-10 10:37:50 -07008208
Mathias Agopian65ab4712010-07-14 17:59:35 -07008209 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008210 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008211
8212 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008213 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8214 if (enabled && status != NO_ERROR) {
8215 return status;
8216 }
8217
Mathias Agopian65ab4712010-07-14 17:59:35 -07008218 switch (mState) {
8219 // going from disabled to enabled
8220 case IDLE:
8221 mState = STARTING;
8222 break;
8223 case STOPPED:
8224 mState = RESTART;
8225 break;
8226 case STOPPING:
8227 mState = ACTIVE;
8228 break;
8229
8230 // going from enabled to disabled
8231 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008232 mState = STOPPED;
8233 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008234 case STARTING:
8235 mState = IDLE;
8236 break;
8237 case ACTIVE:
8238 mState = STOPPING;
8239 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008240 case DESTROYED:
8241 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008242 }
8243 for (size_t i = 1; i < mHandles.size(); i++) {
8244 sp<EffectHandle> h = mHandles[i].promote();
8245 if (h != 0) {
8246 h->setEnabled(enabled);
8247 }
8248 }
8249 }
8250 return NO_ERROR;
8251}
8252
Glenn Kastenc59c0042012-02-02 14:06:11 -08008253bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008254{
8255 switch (mState) {
8256 case RESTART:
8257 case STARTING:
8258 case ACTIVE:
8259 return true;
8260 case IDLE:
8261 case STOPPING:
8262 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008263 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008264 default:
8265 return false;
8266 }
8267}
8268
Glenn Kastenc59c0042012-02-02 14:06:11 -08008269bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008270{
8271 switch (mState) {
8272 case RESTART:
8273 case ACTIVE:
8274 case STOPPING:
8275 case STOPPED:
8276 return true;
8277 case IDLE:
8278 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008279 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008280 default:
8281 return false;
8282 }
8283}
8284
Mathias Agopian65ab4712010-07-14 17:59:35 -07008285status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8286{
8287 Mutex::Autolock _l(mLock);
8288 status_t status = NO_ERROR;
8289
8290 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8291 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008292 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008293 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8294 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008295 status_t cmdStatus;
8296 uint32_t volume[2];
8297 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008298 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008299 volume[0] = *left;
8300 volume[1] = *right;
8301 if (controller) {
8302 pVolume = volume;
8303 }
Eric Laurent25f43952010-07-28 05:40:18 -07008304 status = (*mEffectInterface)->command(mEffectInterface,
8305 EFFECT_CMD_SET_VOLUME,
8306 size,
8307 volume,
8308 &size,
8309 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008310 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8311 *left = volume[0];
8312 *right = volume[1];
8313 }
8314 }
8315 return status;
8316}
8317
8318status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
8319{
8320 Mutex::Autolock _l(mLock);
8321 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008322 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8323 // audio pre processing modules on RecordThread can receive both output and
8324 // input device indication in the same call
8325 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
8326 if (dev) {
8327 status_t cmdStatus;
8328 uint32_t size = sizeof(status_t);
8329
8330 status = (*mEffectInterface)->command(mEffectInterface,
8331 EFFECT_CMD_SET_DEVICE,
8332 sizeof(uint32_t),
8333 &dev,
8334 &size,
8335 &cmdStatus);
8336 if (status == NO_ERROR) {
8337 status = cmdStatus;
8338 }
8339 }
8340 dev = device & AUDIO_DEVICE_IN_ALL;
8341 if (dev) {
8342 status_t cmdStatus;
8343 uint32_t size = sizeof(status_t);
8344
8345 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8346 EFFECT_CMD_SET_INPUT_DEVICE,
8347 sizeof(uint32_t),
8348 &dev,
8349 &size,
8350 &cmdStatus);
8351 if (status2 == NO_ERROR) {
8352 status2 = cmdStatus;
8353 }
8354 if (status == NO_ERROR) {
8355 status = status2;
8356 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008357 }
8358 }
8359 return status;
8360}
8361
Glenn Kastenf78aee72012-01-04 11:00:47 -08008362status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008363{
8364 Mutex::Autolock _l(mLock);
8365 status_t status = NO_ERROR;
8366 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008367 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008368 uint32_t size = sizeof(status_t);
8369 status = (*mEffectInterface)->command(mEffectInterface,
8370 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008371 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008372 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008373 &size,
8374 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008375 if (status == NO_ERROR) {
8376 status = cmdStatus;
8377 }
8378 }
8379 return status;
8380}
8381
Eric Laurent59255e42011-07-27 19:49:51 -07008382void AudioFlinger::EffectModule::setSuspended(bool suspended)
8383{
8384 Mutex::Autolock _l(mLock);
8385 mSuspended = suspended;
8386}
Glenn Kastena3a85482012-01-04 11:01:11 -08008387
8388bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008389{
8390 Mutex::Autolock _l(mLock);
8391 return mSuspended;
8392}
8393
Mathias Agopian65ab4712010-07-14 17:59:35 -07008394status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
8395{
8396 const size_t SIZE = 256;
8397 char buffer[SIZE];
8398 String8 result;
8399
8400 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8401 result.append(buffer);
8402
8403 bool locked = tryLock(mLock);
8404 // failed to lock - AudioFlinger is probably deadlocked
8405 if (!locked) {
8406 result.append("\t\tCould not lock Fx mutex:\n");
8407 }
8408
8409 result.append("\t\tSession Status State Engine:\n");
8410 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8411 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8412 result.append(buffer);
8413
8414 result.append("\t\tDescriptor:\n");
8415 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8416 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8417 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8418 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8419 result.append(buffer);
8420 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8421 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8422 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8423 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8424 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008425 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008426 mDescriptor.apiVersion,
8427 mDescriptor.flags);
8428 result.append(buffer);
8429 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8430 mDescriptor.name);
8431 result.append(buffer);
8432 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8433 mDescriptor.implementor);
8434 result.append(buffer);
8435
8436 result.append("\t\t- Input configuration:\n");
8437 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8438 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8439 (uint32_t)mConfig.inputCfg.buffer.raw,
8440 mConfig.inputCfg.buffer.frameCount,
8441 mConfig.inputCfg.samplingRate,
8442 mConfig.inputCfg.channels,
8443 mConfig.inputCfg.format);
8444 result.append(buffer);
8445
8446 result.append("\t\t- Output configuration:\n");
8447 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8448 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8449 (uint32_t)mConfig.outputCfg.buffer.raw,
8450 mConfig.outputCfg.buffer.frameCount,
8451 mConfig.outputCfg.samplingRate,
8452 mConfig.outputCfg.channels,
8453 mConfig.outputCfg.format);
8454 result.append(buffer);
8455
8456 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8457 result.append(buffer);
8458 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8459 for (size_t i = 0; i < mHandles.size(); ++i) {
8460 sp<EffectHandle> handle = mHandles[i].promote();
8461 if (handle != 0) {
8462 handle->dump(buffer, SIZE);
8463 result.append(buffer);
8464 }
8465 }
8466
8467 result.append("\n");
8468
8469 write(fd, result.string(), result.length());
8470
8471 if (locked) {
8472 mLock.unlock();
8473 }
8474
8475 return NO_ERROR;
8476}
8477
8478// ----------------------------------------------------------------------------
8479// EffectHandle implementation
8480// ----------------------------------------------------------------------------
8481
8482#undef LOG_TAG
8483#define LOG_TAG "AudioFlinger::EffectHandle"
8484
8485AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8486 const sp<AudioFlinger::Client>& client,
8487 const sp<IEffectClient>& effectClient,
8488 int32_t priority)
8489 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008490 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07008491 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008492{
Steve Block3856b092011-10-20 11:56:00 +01008493 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008494
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008495 if (client == 0) {
8496 return;
8497 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008498 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8499 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8500 if (mCblkMemory != 0) {
8501 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8502
Glenn Kastena0d68332012-01-27 16:47:15 -08008503 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008504 new(mCblk) effect_param_cblk_t();
8505 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008506 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008507 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008508 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008509 return;
8510 }
8511}
8512
8513AudioFlinger::EffectHandle::~EffectHandle()
8514{
Steve Block3856b092011-10-20 11:56:00 +01008515 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008516 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01008517 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008518}
8519
8520status_t AudioFlinger::EffectHandle::enable()
8521{
Steve Block3856b092011-10-20 11:56:00 +01008522 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008523 if (!mHasControl) return INVALID_OPERATION;
8524 if (mEffect == 0) return DEAD_OBJECT;
8525
Eric Laurentdb7c0792011-08-10 10:37:50 -07008526 if (mEnabled) {
8527 return NO_ERROR;
8528 }
8529
Eric Laurent59255e42011-07-27 19:49:51 -07008530 mEnabled = true;
8531
8532 sp<ThreadBase> thread = mEffect->thread().promote();
8533 if (thread != 0) {
8534 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8535 }
8536
8537 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8538 if (mEffect->suspended()) {
8539 return NO_ERROR;
8540 }
8541
Eric Laurentdb7c0792011-08-10 10:37:50 -07008542 status_t status = mEffect->setEnabled(true);
8543 if (status != NO_ERROR) {
8544 if (thread != 0) {
8545 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8546 }
8547 mEnabled = false;
8548 }
8549 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008550}
8551
8552status_t AudioFlinger::EffectHandle::disable()
8553{
Steve Block3856b092011-10-20 11:56:00 +01008554 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008555 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008556 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008557
Eric Laurentdb7c0792011-08-10 10:37:50 -07008558 if (!mEnabled) {
8559 return NO_ERROR;
8560 }
Eric Laurent59255e42011-07-27 19:49:51 -07008561 mEnabled = false;
8562
8563 if (mEffect->suspended()) {
8564 return NO_ERROR;
8565 }
8566
8567 status_t status = mEffect->setEnabled(false);
8568
8569 sp<ThreadBase> thread = mEffect->thread().promote();
8570 if (thread != 0) {
8571 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8572 }
8573
8574 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008575}
8576
8577void AudioFlinger::EffectHandle::disconnect()
8578{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008579 disconnect(true);
8580}
8581
Glenn Kasten58123c32012-02-03 10:32:24 -08008582void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008583{
Glenn Kasten58123c32012-02-03 10:32:24 -08008584 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008585 if (mEffect == 0) {
8586 return;
8587 }
Glenn Kasten58123c32012-02-03 10:32:24 -08008588 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07008589
Eric Laurenta85a74a2011-10-19 11:44:54 -07008590 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008591 sp<ThreadBase> thread = mEffect->thread().promote();
8592 if (thread != 0) {
8593 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8594 }
Eric Laurent59255e42011-07-27 19:49:51 -07008595 }
8596
Mathias Agopian65ab4712010-07-14 17:59:35 -07008597 // release sp on module => module destructor can be called now
8598 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008599 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008600 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008601 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008602 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8603 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008604 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008605 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008606 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8607 mClient.clear();
8608 }
8609}
8610
Eric Laurent25f43952010-07-28 05:40:18 -07008611status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8612 uint32_t cmdSize,
8613 void *pCmdData,
8614 uint32_t *replySize,
8615 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008616{
Steve Block3856b092011-10-20 11:56:00 +01008617// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008618// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008619
8620 // only get parameter command is permitted for applications not controlling the effect
8621 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8622 return INVALID_OPERATION;
8623 }
8624 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008625 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008626
8627 // handle commands that are not forwarded transparently to effect engine
8628 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8629 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8630 // no risk to block the whole media server process or mixer threads is we are stuck here
8631 Mutex::Autolock _l(mCblk->lock);
8632 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8633 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8634 mCblk->serverIndex = 0;
8635 mCblk->clientIndex = 0;
8636 return BAD_VALUE;
8637 }
8638 status_t status = NO_ERROR;
8639 while (mCblk->serverIndex < mCblk->clientIndex) {
8640 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008641 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008642 int *p = (int *)(mBuffer + mCblk->serverIndex);
8643 int size = *p++;
8644 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008645 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008646 break;
8647 }
8648 effect_param_t *param = (effect_param_t *)p;
8649 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008650 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008651 mCblk->serverIndex += size;
8652 continue;
8653 }
Eric Laurent25f43952010-07-28 05:40:18 -07008654 uint32_t psize = sizeof(effect_param_t) +
8655 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8656 param->vsize;
8657 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8658 psize,
8659 p,
8660 &rsize,
8661 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008662 // stop at first error encountered
8663 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008664 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008665 *(int *)pReplyData = reply;
8666 break;
8667 } else if (reply != NO_ERROR) {
8668 *(int *)pReplyData = reply;
8669 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008670 }
8671 mCblk->serverIndex += size;
8672 }
8673 mCblk->serverIndex = 0;
8674 mCblk->clientIndex = 0;
8675 return status;
8676 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008677 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008678 return enable();
8679 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008680 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008681 return disable();
8682 }
8683
8684 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8685}
8686
Eric Laurent59255e42011-07-27 19:49:51 -07008687void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008688{
Steve Block3856b092011-10-20 11:56:00 +01008689 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008690
8691 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008692 mEnabled = enabled;
8693
Mathias Agopian65ab4712010-07-14 17:59:35 -07008694 if (signal && mEffectClient != 0) {
8695 mEffectClient->controlStatusChanged(hasControl);
8696 }
8697}
8698
Eric Laurent25f43952010-07-28 05:40:18 -07008699void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8700 uint32_t cmdSize,
8701 void *pCmdData,
8702 uint32_t replySize,
8703 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008704{
8705 if (mEffectClient != 0) {
8706 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8707 }
8708}
8709
8710
8711
8712void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8713{
8714 if (mEffectClient != 0) {
8715 mEffectClient->enableStatusChanged(enabled);
8716 }
8717}
8718
8719status_t AudioFlinger::EffectHandle::onTransact(
8720 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8721{
8722 return BnEffect::onTransact(code, data, reply, flags);
8723}
8724
8725
8726void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8727{
Glenn Kastena0d68332012-01-27 16:47:15 -08008728 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008729
8730 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008731 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008732 mPriority,
8733 mHasControl,
8734 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008735 mCblk ? mCblk->clientIndex : 0,
8736 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008737 );
8738
8739 if (locked) {
8740 mCblk->lock.unlock();
8741 }
8742}
8743
8744#undef LOG_TAG
8745#define LOG_TAG "AudioFlinger::EffectChain"
8746
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008747AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008748 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008749 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07008750 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
8751 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008752{
Dima Zavinfce7a472011-04-19 22:30:36 -07008753 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008754 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008755 return;
8756 }
8757 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
8758 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008759}
8760
8761AudioFlinger::EffectChain::~EffectChain()
8762{
8763 if (mOwnInBuffer) {
8764 delete mInBuffer;
8765 }
8766
8767}
8768
Eric Laurent59255e42011-07-27 19:49:51 -07008769// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008770sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008771{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008772 size_t size = mEffects.size();
8773
8774 for (size_t i = 0; i < size; i++) {
8775 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008776 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008777 }
8778 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008779 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008780}
8781
Eric Laurent59255e42011-07-27 19:49:51 -07008782// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07008783sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008784{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008785 size_t size = mEffects.size();
8786
8787 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07008788 // by convention, return first effect if id provided is 0 (0 is never a valid id)
8789 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008790 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07008791 }
8792 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008793 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008794}
8795
Eric Laurent59255e42011-07-27 19:49:51 -07008796// getEffectFromType_l() must be called with ThreadBase::mLock held
8797sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
8798 const effect_uuid_t *type)
8799{
Eric Laurent59255e42011-07-27 19:49:51 -07008800 size_t size = mEffects.size();
8801
8802 for (size_t i = 0; i < size; i++) {
8803 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008804 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07008805 }
8806 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008807 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07008808}
8809
Mathias Agopian65ab4712010-07-14 17:59:35 -07008810// Must be called with EffectChain::mLock locked
8811void AudioFlinger::EffectChain::process_l()
8812{
Eric Laurentdac69112010-09-28 14:09:57 -07008813 sp<ThreadBase> thread = mThread.promote();
8814 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008815 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07008816 return;
8817 }
Dima Zavinfce7a472011-04-19 22:30:36 -07008818 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
8819 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08008820 // always process effects unless no more tracks are on the session and the effect tail
8821 // has been rendered
8822 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07008823 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08008824 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07008825
Eric Laurent544fe9b2011-11-11 15:42:52 -08008826 if (!tracksOnSession && mTailBufferCount == 0) {
8827 doProcess = false;
8828 }
8829
8830 if (activeTrackCnt() == 0) {
8831 // if no track is active and the effect tail has not been rendered,
8832 // the input buffer must be cleared here as the mixer process will not do it
8833 if (tracksOnSession || mTailBufferCount > 0) {
8834 size_t numSamples = thread->frameCount() * thread->channelCount();
8835 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
8836 if (mTailBufferCount > 0) {
8837 mTailBufferCount--;
8838 }
8839 }
8840 }
Eric Laurentdac69112010-09-28 14:09:57 -07008841 }
8842
Mathias Agopian65ab4712010-07-14 17:59:35 -07008843 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08008844 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07008845 for (size_t i = 0; i < size; i++) {
8846 mEffects[i]->process();
8847 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008848 }
8849 for (size_t i = 0; i < size; i++) {
8850 mEffects[i]->updateState();
8851 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008852}
8853
Eric Laurentcab11242010-07-15 12:50:15 -07008854// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07008855status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008856{
8857 effect_descriptor_t desc = effect->desc();
8858 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
8859
8860 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07008861 effect->setChain(this);
8862 sp<ThreadBase> thread = mThread.promote();
8863 if (thread == 0) {
8864 return NO_INIT;
8865 }
8866 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008867
8868 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8869 // Auxiliary effects are inserted at the beginning of mEffects vector as
8870 // they are processed first and accumulated in chain input buffer
8871 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07008872
Mathias Agopian65ab4712010-07-14 17:59:35 -07008873 // the input buffer for auxiliary effect contains mono samples in
8874 // 32 bit format. This is to avoid saturation in AudoMixer
8875 // accumulation stage. Saturation is done in EffectModule::process() before
8876 // calling the process in effect engine
8877 size_t numSamples = thread->frameCount();
8878 int32_t *buffer = new int32_t[numSamples];
8879 memset(buffer, 0, numSamples * sizeof(int32_t));
8880 effect->setInBuffer((int16_t *)buffer);
8881 // auxiliary effects output samples to chain input buffer for further processing
8882 // by insert effects
8883 effect->setOutBuffer(mInBuffer);
8884 } else {
8885 // Insert effects are inserted at the end of mEffects vector as they are processed
8886 // after track and auxiliary effects.
8887 // Insert effect order as a function of indicated preference:
8888 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
8889 // another effect is present
8890 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
8891 // last effect claiming first position
8892 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
8893 // first effect claiming last position
8894 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
8895 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
8896 // already present
8897
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008898 size_t size = mEffects.size();
8899 size_t idx_insert = size;
8900 ssize_t idx_insert_first = -1;
8901 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008902
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008903 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008904 effect_descriptor_t d = mEffects[i]->desc();
8905 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
8906 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
8907 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
8908 // check invalid effect chaining combinations
8909 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
8910 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008911 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008912 return INVALID_OPERATION;
8913 }
8914 // remember position of first insert effect and by default
8915 // select this as insert position for new effect
8916 if (idx_insert == size) {
8917 idx_insert = i;
8918 }
8919 // remember position of last insert effect claiming
8920 // first position
8921 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
8922 idx_insert_first = i;
8923 }
8924 // remember position of first insert effect claiming
8925 // last position
8926 if (iPref == EFFECT_FLAG_INSERT_LAST &&
8927 idx_insert_last == -1) {
8928 idx_insert_last = i;
8929 }
8930 }
8931 }
8932
8933 // modify idx_insert from first position if needed
8934 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
8935 if (idx_insert_last != -1) {
8936 idx_insert = idx_insert_last;
8937 } else {
8938 idx_insert = size;
8939 }
8940 } else {
8941 if (idx_insert_first != -1) {
8942 idx_insert = idx_insert_first + 1;
8943 }
8944 }
8945
8946 // always read samples from chain input buffer
8947 effect->setInBuffer(mInBuffer);
8948
8949 // if last effect in the chain, output samples to chain
8950 // output buffer, otherwise to chain input buffer
8951 if (idx_insert == size) {
8952 if (idx_insert != 0) {
8953 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
8954 mEffects[idx_insert-1]->configure();
8955 }
8956 effect->setOutBuffer(mOutBuffer);
8957 } else {
8958 effect->setOutBuffer(mInBuffer);
8959 }
8960 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008961
Steve Block3856b092011-10-20 11:56:00 +01008962 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008963 }
8964 effect->configure();
8965 return NO_ERROR;
8966}
8967
Eric Laurentcab11242010-07-15 12:50:15 -07008968// removeEffect_l() must be called with PlaybackThread::mLock held
8969size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008970{
8971 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008972 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008973 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
8974
Glenn Kasten8d6a2442012-02-08 14:04:28 -08008975 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008976 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07008977 // calling stop here will remove pre-processing effect from the audio HAL.
8978 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
8979 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07008980 if (mEffects[i]->state() == EffectModule::ACTIVE ||
8981 mEffects[i]->state() == EffectModule::STOPPING) {
8982 mEffects[i]->stop();
8983 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008984 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
8985 delete[] effect->inBuffer();
8986 } else {
8987 if (i == size - 1 && i != 0) {
8988 mEffects[i - 1]->setOutBuffer(mOutBuffer);
8989 mEffects[i - 1]->configure();
8990 }
8991 }
8992 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01008993 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008994 break;
8995 }
8996 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008997
8998 return mEffects.size();
8999}
9000
Eric Laurentcab11242010-07-15 12:50:15 -07009001// setDevice_l() must be called with PlaybackThread::mLock held
9002void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009003{
9004 size_t size = mEffects.size();
9005 for (size_t i = 0; i < size; i++) {
9006 mEffects[i]->setDevice(device);
9007 }
9008}
9009
Eric Laurentcab11242010-07-15 12:50:15 -07009010// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009011void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009012{
9013 size_t size = mEffects.size();
9014 for (size_t i = 0; i < size; i++) {
9015 mEffects[i]->setMode(mode);
9016 }
9017}
9018
Eric Laurentcab11242010-07-15 12:50:15 -07009019// setVolume_l() must be called with PlaybackThread::mLock held
9020bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009021{
9022 uint32_t newLeft = *left;
9023 uint32_t newRight = *right;
9024 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009025 int ctrlIdx = -1;
9026 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009027
Eric Laurentcab11242010-07-15 12:50:15 -07009028 // first update volume controller
9029 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009030 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009031 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9032 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009033 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009034 break;
9035 }
9036 }
9037
9038 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009039 if (hasControl) {
9040 *left = mNewLeftVolume;
9041 *right = mNewRightVolume;
9042 }
9043 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009044 }
9045
9046 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009047 mLeftVolume = newLeft;
9048 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009049
9050 // second get volume update from volume controller
9051 if (ctrlIdx >= 0) {
9052 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009053 mNewLeftVolume = newLeft;
9054 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009055 }
9056 // then indicate volume to all other effects in chain.
9057 // Pass altered volume to effects before volume controller
9058 // and requested volume to effects after controller
9059 uint32_t lVol = newLeft;
9060 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009061
Mathias Agopian65ab4712010-07-14 17:59:35 -07009062 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009063 if ((int)i == ctrlIdx) continue;
9064 // this also works for ctrlIdx == -1 when there is no volume controller
9065 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009066 lVol = *left;
9067 rVol = *right;
9068 }
9069 mEffects[i]->setVolume(&lVol, &rVol, false);
9070 }
9071 *left = newLeft;
9072 *right = newRight;
9073
9074 return hasControl;
9075}
9076
Mathias Agopian65ab4712010-07-14 17:59:35 -07009077status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
9078{
9079 const size_t SIZE = 256;
9080 char buffer[SIZE];
9081 String8 result;
9082
9083 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9084 result.append(buffer);
9085
9086 bool locked = tryLock(mLock);
9087 // failed to lock - AudioFlinger is probably deadlocked
9088 if (!locked) {
9089 result.append("\tCould not lock mutex:\n");
9090 }
9091
Eric Laurentcab11242010-07-15 12:50:15 -07009092 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9093 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009094 mEffects.size(),
9095 (uint32_t)mInBuffer,
9096 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009097 mActiveTrackCnt);
9098 result.append(buffer);
9099 write(fd, result.string(), result.size());
9100
9101 for (size_t i = 0; i < mEffects.size(); ++i) {
9102 sp<EffectModule> effect = mEffects[i];
9103 if (effect != 0) {
9104 effect->dump(fd, args);
9105 }
9106 }
9107
9108 if (locked) {
9109 mLock.unlock();
9110 }
9111
9112 return NO_ERROR;
9113}
9114
Eric Laurent59255e42011-07-27 19:49:51 -07009115// must be called with ThreadBase::mLock held
9116void AudioFlinger::EffectChain::setEffectSuspended_l(
9117 const effect_uuid_t *type, bool suspend)
9118{
9119 sp<SuspendedEffectDesc> desc;
9120 // use effect type UUID timelow as key as there is no real risk of identical
9121 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009122 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009123 if (suspend) {
9124 if (index >= 0) {
9125 desc = mSuspendedEffects.valueAt(index);
9126 } else {
9127 desc = new SuspendedEffectDesc();
9128 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
9129 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009130 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009131 }
9132 if (desc->mRefCount++ == 0) {
9133 sp<EffectModule> effect = getEffectIfEnabled(type);
9134 if (effect != 0) {
9135 desc->mEffect = effect;
9136 effect->setSuspended(true);
9137 effect->setEnabled(false);
9138 }
9139 }
9140 } else {
9141 if (index < 0) {
9142 return;
9143 }
9144 desc = mSuspendedEffects.valueAt(index);
9145 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009146 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009147 desc->mRefCount = 1;
9148 }
9149 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009150 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009151 if (desc->mEffect != 0) {
9152 sp<EffectModule> effect = desc->mEffect.promote();
9153 if (effect != 0) {
9154 effect->setSuspended(false);
9155 sp<EffectHandle> handle = effect->controlHandle();
9156 if (handle != 0) {
9157 effect->setEnabled(handle->enabled());
9158 }
9159 }
9160 desc->mEffect.clear();
9161 }
9162 mSuspendedEffects.removeItemsAt(index);
9163 }
9164 }
9165}
9166
9167// must be called with ThreadBase::mLock held
9168void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9169{
9170 sp<SuspendedEffectDesc> desc;
9171
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009172 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009173 if (suspend) {
9174 if (index >= 0) {
9175 desc = mSuspendedEffects.valueAt(index);
9176 } else {
9177 desc = new SuspendedEffectDesc();
9178 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009179 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009180 }
9181 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009182 Vector< sp<EffectModule> > effects;
9183 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009184 for (size_t i = 0; i < effects.size(); i++) {
9185 setEffectSuspended_l(&effects[i]->desc().type, true);
9186 }
9187 }
9188 } else {
9189 if (index < 0) {
9190 return;
9191 }
9192 desc = mSuspendedEffects.valueAt(index);
9193 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009194 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009195 desc->mRefCount = 1;
9196 }
9197 if (--desc->mRefCount == 0) {
9198 Vector<const effect_uuid_t *> types;
9199 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9200 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9201 continue;
9202 }
9203 types.add(&mSuspendedEffects.valueAt(i)->mType);
9204 }
9205 for (size_t i = 0; i < types.size(); i++) {
9206 setEffectSuspended_l(types[i], false);
9207 }
Steve Block3856b092011-10-20 11:56:00 +01009208 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009209 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9210 }
9211 }
9212}
9213
Eric Laurent6bffdb82011-09-23 08:40:41 -07009214
9215// The volume effect is used for automated tests only
9216#ifndef OPENSL_ES_H_
9217static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9218 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9219const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9220#endif //OPENSL_ES_H_
9221
Eric Laurentdb7c0792011-08-10 10:37:50 -07009222bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9223{
9224 // auxiliary effects and visualizer are never suspended on output mix
9225 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9226 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009227 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9228 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009229 return false;
9230 }
9231 return true;
9232}
9233
Glenn Kastend0539712012-01-30 12:56:03 -08009234void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009235{
Glenn Kastend0539712012-01-30 12:56:03 -08009236 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009237 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009238 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9239 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009240 }
Eric Laurent59255e42011-07-27 19:49:51 -07009241 }
Eric Laurent59255e42011-07-27 19:49:51 -07009242}
9243
9244sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9245 const effect_uuid_t *type)
9246{
Glenn Kasten090f0192012-01-30 13:00:02 -08009247 sp<EffectModule> effect = getEffectFromType_l(type);
9248 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009249}
9250
9251void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9252 bool enabled)
9253{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009254 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009255 if (enabled) {
9256 if (index < 0) {
9257 // if the effect is not suspend check if all effects are suspended
9258 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9259 if (index < 0) {
9260 return;
9261 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009262 if (!isEffectEligibleForSuspend(effect->desc())) {
9263 return;
9264 }
Eric Laurent59255e42011-07-27 19:49:51 -07009265 setEffectSuspended_l(&effect->desc().type, enabled);
9266 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009267 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009268 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009269 return;
9270 }
Eric Laurent59255e42011-07-27 19:49:51 -07009271 }
Steve Block3856b092011-10-20 11:56:00 +01009272 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009273 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009274 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9275 // if effect is requested to suspended but was not yet enabled, supend it now.
9276 if (desc->mEffect == 0) {
9277 desc->mEffect = effect;
9278 effect->setEnabled(false);
9279 effect->setSuspended(true);
9280 }
9281 } else {
9282 if (index < 0) {
9283 return;
9284 }
Steve Block3856b092011-10-20 11:56:00 +01009285 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009286 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009287 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9288 desc->mEffect.clear();
9289 effect->setSuspended(false);
9290 }
9291}
9292
Mathias Agopian65ab4712010-07-14 17:59:35 -07009293#undef LOG_TAG
9294#define LOG_TAG "AudioFlinger"
9295
9296// ----------------------------------------------------------------------------
9297
9298status_t AudioFlinger::onTransact(
9299 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9300{
9301 return BnAudioFlinger::onTransact(code, data, reply, flags);
9302}
9303
Mathias Agopian65ab4712010-07-14 17:59:35 -07009304}; // namespace android