blob: 23dd90fd2848f205af99eac7a86f34db76b6289d [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070030#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070031#include <binder/Parcel.h>
32#include <binder/IPCThreadState.h>
33#include <utils/String16.h>
34#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070035#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070036
Dima Zavinfce7a472011-04-19 22:30:36 -070037#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080039#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040
Glenn Kastend3cee2f2012-03-13 17:55:35 -070041#undef ADD_BATTERY_DATA
42
43#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080044#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080045#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070046#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070047
48#include <private/media/AudioTrackShared.h>
49#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070050
Dima Zavin64760242011-05-11 14:15:23 -070051#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070052#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
54#include "AudioMixer.h"
55#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080056#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070059#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070060#include <audio_effects/effect_ns.h>
61#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Glenn Kasten3b21c502011-12-15 09:52:39 -080063#include <audio_utils/primitives.h>
64
Eric Laurentfeb0db62011-07-22 09:04:31 -070065#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080066
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070067// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080068#ifdef DEBUG_CPU_USAGE
69#include <cpustats/CentralTendencyStatistics.h>
70#include <cpustats/ThreadCpuUsage.h>
71#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070072
John Grossman4ff14ba2012-02-08 16:37:41 -080073#include <common_time/cc_helper.h>
74#include <common_time/local_clock.h>
75
Glenn Kasten58912562012-04-03 10:45:00 -070076#include "FastMixer.h"
77
78// NBAIO implementations
79#include "AudioStreamOutSink.h"
80#include "MonoPipe.h"
81#include "MonoPipeReader.h"
Glenn Kastenfbae5da2012-05-21 09:17:20 -070082#include "Pipe.h"
83#include "PipeReader.h"
Glenn Kasten58912562012-04-03 10:45:00 -070084#include "SourceAudioBufferProvider.h"
85
Glenn Kasten1dc28b72012-04-24 10:01:03 -070086#include "SchedulingPolicyService.h"
Glenn Kasten58912562012-04-03 10:45:00 -070087
Mathias Agopian65ab4712010-07-14 17:59:35 -070088// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
John Grossman1c345192012-03-27 14:00:17 -070090// Note: the following macro is used for extremely verbose logging message. In
91// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
92// 0; but one side effect of this is to turn all LOGV's as well. Some messages
93// are so verbose that we want to suppress them even when we have ALOG_ASSERT
94// turned on. Do not uncomment the #def below unless you really know what you
95// are doing and want to see all of the extremely verbose messages.
96//#define VERY_VERY_VERBOSE_LOGGING
97#ifdef VERY_VERY_VERBOSE_LOGGING
98#define ALOGVV ALOGV
99#else
100#define ALOGVV(a...) do { } while(0)
101#endif
Eric Laurentde070132010-07-13 04:45:46 -0700102
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103namespace android {
104
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800105static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
106static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700107
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800109static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110
111// retry counts for buffer fill timeout
112// 50 * ~20msecs = 1 second
113static const int8_t kMaxTrackRetries = 50;
114static const int8_t kMaxTrackStartupRetries = 50;
115// allow less retry attempts on direct output thread.
116// direct outputs can be a scarce resource in audio hardware and should
117// be released as quickly as possible.
118static const int8_t kMaxTrackRetriesDirect = 2;
119
120static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800121static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700122
Glenn Kasten7dede872011-12-13 11:04:14 -0800123// don't warn about blocked writes or record buffer overflows more often than this
124static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700125
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700126// RecordThread loop sleep time upon application overrun or audio HAL read error
127static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128
Glenn Kasten7dede872011-12-13 11:04:14 -0800129// maximum time to wait for setParameters to complete
130static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700131
Eric Laurent7cafbb32011-11-22 18:50:29 -0800132// minimum sleep time for the mixer thread loop when tracks are active but in underrun
133static const uint32_t kMinThreadSleepTimeUs = 5000;
134// maximum divider applied to the active sleep time in the mixer thread loop
135static const uint32_t kMaxThreadSleepTimeShift = 2;
136
Glenn Kasten58912562012-04-03 10:45:00 -0700137// minimum normal mix buffer size, expressed in milliseconds rather than frames
138static const uint32_t kMinNormalMixBufferSizeMs = 20;
Glenn Kasten4adcede2012-05-14 12:26:02 -0700139// maximum normal mix buffer size
140static const uint32_t kMaxNormalMixBufferSizeMs = 24;
Glenn Kasten58912562012-04-03 10:45:00 -0700141
John Grossman4ff14ba2012-02-08 16:37:41 -0800142nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800143
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700144// Whether to use fast mixer
145static const enum {
146 FastMixer_Never, // never initialize or use: for debugging only
147 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
148 // normal mixer multiplier is 1
149 FastMixer_Static, // initialize if needed, then use all the time if initialized,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700150 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700151 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700152 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700153 // FIXME for FastMixer_Dynamic:
154 // Supporting this option will require fixing HALs that can't handle large writes.
155 // For example, one HAL implementation returns an error from a large write,
156 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
157 // We could either fix the HAL implementations, or provide a wrapper that breaks
158 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
159} kUseFastMixer = FastMixer_Static;
160
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700161static uint32_t gScreenState; // incremented by 2 when screen state changes, bit 0 == 1 means "off"
162 // AudioFlinger::setParameters() updates, other threads read w/o lock
163
Glenn Kastenfd4e20c2012-06-04 11:51:12 -0700164// Priorities for requestPriority
165static const int kPriorityAudioApp = 2;
166static const int kPriorityFastMixer = 3;
167
Mathias Agopian65ab4712010-07-14 17:59:35 -0700168// ----------------------------------------------------------------------------
169
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700170#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800171// To collect the amplifier usage
172static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800173 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
174 if (service == NULL) {
175 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800176 return;
177 }
178
179 service->addBatteryData(params);
180}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700181#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800182
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700183static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700184{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700185 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700186 int rc;
187
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700188 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
189 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
190 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
191 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700192 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700193 }
194 rc = audio_hw_device_open(mod, dev);
195 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
196 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
197 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700198 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700199 }
200 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
201 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
202 rc = BAD_VALUE;
203 goto out;
204 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700205 return 0;
206
207out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700208 *dev = NULL;
209 return rc;
210}
211
Mathias Agopian65ab4712010-07-14 17:59:35 -0700212// ----------------------------------------------------------------------------
213
214AudioFlinger::AudioFlinger()
215 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800216 mPrimaryHardwareDev(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700217 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800218 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800219 mMasterMute(false),
220 mNextUniqueId(1),
221 mMode(AUDIO_MODE_INVALID),
222 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700223{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700224}
225
226void AudioFlinger::onFirstRef()
227{
Dima Zavin799a70e2011-04-18 16:57:27 -0700228 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700229
Eric Laurent93575202011-01-18 18:39:02 -0800230 Mutex::Autolock _l(mLock);
231
Dima Zavin799a70e2011-04-18 16:57:27 -0700232 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800233 char val_str[PROPERTY_VALUE_MAX] = { 0 };
234 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
235 uint32_t int_val;
236 if (1 == sscanf(val_str, "%u", &int_val)) {
237 mStandbyTimeInNsecs = milliseconds(int_val);
238 ALOGI("Using %u mSec as standby time.", int_val);
239 } else {
240 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
241 ALOGI("Using default %u mSec as standby time.",
242 (uint32_t)(mStandbyTimeInNsecs / 1000000));
243 }
244 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700245
Eric Laurenta4c5a552012-03-29 10:12:40 -0700246 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247}
248
249AudioFlinger::~AudioFlinger()
250{
251 while (!mRecordThreads.isEmpty()) {
252 // closeInput() will remove first entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700253 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700254 }
255 while (!mPlaybackThreads.isEmpty()) {
256 // closeOutput() will remove first entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700257 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700258 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700259
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800260 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
261 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700262 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
263 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700264 }
265}
266
Eric Laurenta4c5a552012-03-29 10:12:40 -0700267static const char * const audio_interfaces[] = {
268 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
269 AUDIO_HARDWARE_MODULE_ID_A2DP,
270 AUDIO_HARDWARE_MODULE_ID_USB,
271};
272#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
273
John Grossman93d90682012-07-23 17:05:46 -0700274AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
275 audio_module_handle_t module,
276 audio_devices_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
John Grossman93d90682012-07-23 17:05:46 -0700287 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
288 if (audioHwDevice != NULL) {
289 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700290 }
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++) {
John Grossman93d90682012-07-23 17:05:46 -0700294 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
295 audio_hw_device_t *dev = audioHwDevice->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700296 if ((dev->get_supported_devices(dev) & devices) == devices)
John Grossman93d90682012-07-23 17:05:46 -0700297 return audioHwDevice;
Dima Zavin799a70e2011-04-18 16:57:27 -0700298 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700299
Dima Zavin799a70e2011-04-18 16:57:27 -0700300 return NULL;
301}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700302
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700303void AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700304{
305 const size_t SIZE = 256;
306 char buffer[SIZE];
307 String8 result;
308
309 result.append("Clients:\n");
310 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800311 sp<Client> client = mClients.valueAt(i).promote();
312 if (client != 0) {
313 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
314 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700315 }
316 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700317
318 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800319 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700320 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
321 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800322 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700323 result.append(buffer);
324 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700325 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700326}
327
328
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700329void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700330{
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());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700342}
343
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700344void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700345{
346 const size_t SIZE = 256;
347 char buffer[SIZE];
348 String8 result;
349 snprintf(buffer, SIZE, "Permission Denial: "
350 "can't dump AudioFlinger from pid=%d, uid=%d\n",
351 IPCThreadState::self()->getCallingPid(),
352 IPCThreadState::self()->getCallingUid());
353 result.append(buffer);
354 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700355}
356
357static bool tryLock(Mutex& mutex)
358{
359 bool locked = false;
360 for (int i = 0; i < kDumpLockRetries; ++i) {
361 if (mutex.tryLock() == NO_ERROR) {
362 locked = true;
363 break;
364 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800365 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700366 }
367 return locked;
368}
369
370status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
371{
Glenn Kasten44deb052012-02-05 18:09:08 -0800372 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700373 dumpPermissionDenial(fd, args);
374 } else {
375 // get state of hardware lock
376 bool hardwareLocked = tryLock(mHardwareLock);
377 if (!hardwareLocked) {
378 String8 result(kHardwareLockedString);
379 write(fd, result.string(), result.size());
380 } else {
381 mHardwareLock.unlock();
382 }
383
384 bool locked = tryLock(mLock);
385
386 // failed to lock - AudioFlinger is probably deadlocked
387 if (!locked) {
388 String8 result(kDeadlockedString);
389 write(fd, result.string(), result.size());
390 }
391
392 dumpClients(fd, args);
393 dumpInternals(fd, args);
394
395 // dump playback threads
396 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
397 mPlaybackThreads.valueAt(i)->dump(fd, args);
398 }
399
400 // dump record threads
401 for (size_t i = 0; i < mRecordThreads.size(); i++) {
402 mRecordThreads.valueAt(i)->dump(fd, args);
403 }
404
Dima Zavin799a70e2011-04-18 16:57:27 -0700405 // dump all hardware devs
406 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700407 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700408 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700409 }
410 if (locked) mLock.unlock();
411 }
412 return NO_ERROR;
413}
414
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800415sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
416{
417 // If pid is already in the mClients wp<> map, then use that entry
418 // (for which promote() is always != 0), otherwise create a new entry and Client.
419 sp<Client> client = mClients.valueFor(pid).promote();
420 if (client == 0) {
421 client = new Client(this, pid);
422 mClients.add(pid, client);
423 }
424
425 return client;
426}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700427
428// IAudioFlinger interface
429
430
431sp<IAudioTrack> AudioFlinger::createTrack(
432 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800433 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700434 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800435 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700436 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800438 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700439 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800440 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800441 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700442 int *sessionId,
443 status_t *status)
444{
445 sp<PlaybackThread::Track> track;
446 sp<TrackHandle> trackHandle;
447 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700448 status_t lStatus;
449 int lSessionId;
450
Glenn Kasten263709e2012-01-06 08:40:01 -0800451 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
452 // but if someone uses binder directly they could bypass that and cause us to crash
453 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000454 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700455 lStatus = BAD_VALUE;
456 goto Exit;
457 }
458
459 {
460 Mutex::Autolock _l(mLock);
461 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700462 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700463 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000464 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700465 lStatus = BAD_VALUE;
466 goto Exit;
467 }
468
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800469 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700470
Steve Block3856b092011-10-20 11:56:00 +0100471 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700472 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700473 // check if an effect chain with the same session ID is present on another
474 // output thread and move it here.
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) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700478 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700479 if (sessions & PlaybackThread::EFFECT_SESSION) {
480 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700481 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700482 }
Eric Laurentde070132010-07-13 04:45:46 -0700483 }
484 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700485 lSessionId = *sessionId;
486 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700487 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700488 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700489 if (sessionId != NULL) {
490 *sessionId = lSessionId;
491 }
492 }
Steve Block3856b092011-10-20 11:56:00 +0100493 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700494
495 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800496 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700497
498 // move effect chain to this output thread if an effect on same session was waiting
499 // for a track to be created
500 if (lStatus == NO_ERROR && effectThread != NULL) {
501 Mutex::Autolock _dl(thread->mLock);
502 Mutex::Autolock _sl(effectThread->mLock);
503 moveEffectChain_l(lSessionId, effectThread, thread, true);
504 }
Eric Laurenta011e352012-03-29 15:51:43 -0700505
506 // Look for sync events awaiting for a session to be used.
507 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
508 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
509 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700510 if (lStatus == NO_ERROR) {
511 track->setSyncEvent(mPendingSyncEvents[i]);
512 } else {
513 mPendingSyncEvents[i]->cancel();
514 }
Eric Laurenta011e352012-03-29 15:51:43 -0700515 mPendingSyncEvents.removeAt(i);
516 i--;
517 }
518 }
519 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700520 }
521 if (lStatus == NO_ERROR) {
522 trackHandle = new TrackHandle(track);
523 } else {
524 // remove local strong reference to Client before deleting the Track so that the Client
525 // destructor is called by the TrackBase destructor with mLock held
526 client.clear();
527 track.clear();
528 }
529
530Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700531 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700532 *status = lStatus;
533 }
534 return trackHandle;
535}
536
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800537uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700538{
539 Mutex::Autolock _l(mLock);
540 PlaybackThread *thread = checkPlaybackThread_l(output);
541 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000542 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700543 return 0;
544 }
545 return thread->sampleRate();
546}
547
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800548int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700549{
550 Mutex::Autolock _l(mLock);
551 PlaybackThread *thread = checkPlaybackThread_l(output);
552 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000553 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700554 return 0;
555 }
556 return thread->channelCount();
557}
558
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800559audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700560{
561 Mutex::Autolock _l(mLock);
562 PlaybackThread *thread = checkPlaybackThread_l(output);
563 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000564 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800565 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700566 }
567 return thread->format();
568}
569
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800570size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700571{
572 Mutex::Autolock _l(mLock);
573 PlaybackThread *thread = checkPlaybackThread_l(output);
574 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000575 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700576 return 0;
577 }
Glenn Kasten58912562012-04-03 10:45:00 -0700578 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
579 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700580 return thread->frameCount();
581}
582
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800583uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700584{
585 Mutex::Autolock _l(mLock);
586 PlaybackThread *thread = checkPlaybackThread_l(output);
587 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000588 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700589 return 0;
590 }
591 return thread->latency();
592}
593
594status_t AudioFlinger::setMasterVolume(float value)
595{
Eric Laurenta1884f92011-08-23 08:25:03 -0700596 status_t ret = initCheck();
597 if (ret != NO_ERROR) {
598 return ret;
599 }
600
Mathias Agopian65ab4712010-07-14 17:59:35 -0700601 // check calling permissions
602 if (!settingsAllowed()) {
603 return PERMISSION_DENIED;
604 }
605
Eric Laurenta4c5a552012-03-29 10:12:40 -0700606 Mutex::Autolock _l(mLock);
John Grossman93d90682012-07-23 17:05:46 -0700607 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700608
John Grossman93d90682012-07-23 17:05:46 -0700609 // Set master volume in the HALs which support it.
610 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
611 AutoMutex lock(mHardwareLock);
612 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800613
John Grossman93d90682012-07-23 17:05:46 -0700614 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
615 if (dev->canSetMasterVolume()) {
616 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800617 }
John Grossman93d90682012-07-23 17:05:46 -0700618 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700619 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700620
John Grossman93d90682012-07-23 17:05:46 -0700621 // Now set the master volume in each playback thread. Playback threads
622 // assigned to HALs which do not have master volume support will apply
623 // master volume during the mix operation. Threads with HALs which do
624 // support master volume will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800625 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossman93d90682012-07-23 17:05:46 -0700626 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700627
628 return NO_ERROR;
629}
630
Glenn Kastenf78aee72012-01-04 11:00:47 -0800631status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700632{
Eric Laurenta1884f92011-08-23 08:25:03 -0700633 status_t ret = initCheck();
634 if (ret != NO_ERROR) {
635 return ret;
636 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700637
638 // check calling permissions
639 if (!settingsAllowed()) {
640 return PERMISSION_DENIED;
641 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800642 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000643 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700644 return BAD_VALUE;
645 }
646
647 { // scope for the lock
648 AutoMutex lock(mHardwareLock);
John Grossman93d90682012-07-23 17:05:46 -0700649 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700650 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossman93d90682012-07-23 17:05:46 -0700651 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700652 mHardwareStatus = AUDIO_HW_IDLE;
653 }
654
655 if (NO_ERROR == ret) {
656 Mutex::Autolock _l(mLock);
657 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800658 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700659 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700660 }
661
662 return ret;
663}
664
665status_t AudioFlinger::setMicMute(bool state)
666{
Eric Laurenta1884f92011-08-23 08:25:03 -0700667 status_t ret = initCheck();
668 if (ret != NO_ERROR) {
669 return ret;
670 }
671
Mathias Agopian65ab4712010-07-14 17:59:35 -0700672 // check calling permissions
673 if (!settingsAllowed()) {
674 return PERMISSION_DENIED;
675 }
676
677 AutoMutex lock(mHardwareLock);
John Grossman93d90682012-07-23 17:05:46 -0700678 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700679 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
John Grossman93d90682012-07-23 17:05:46 -0700680 ret = dev->set_mic_mute(dev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700681 mHardwareStatus = AUDIO_HW_IDLE;
682 return ret;
683}
684
685bool AudioFlinger::getMicMute() const
686{
Eric Laurenta1884f92011-08-23 08:25:03 -0700687 status_t ret = initCheck();
688 if (ret != NO_ERROR) {
689 return false;
690 }
691
Dima Zavinfce7a472011-04-19 22:30:36 -0700692 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800693 AutoMutex lock(mHardwareLock);
John Grossman93d90682012-07-23 17:05:46 -0700694 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700695 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
John Grossman93d90682012-07-23 17:05:46 -0700696 dev->get_mic_mute(dev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700697 mHardwareStatus = AUDIO_HW_IDLE;
698 return state;
699}
700
701status_t AudioFlinger::setMasterMute(bool muted)
702{
John Grossman91de9b52012-07-20 14:51:35 -0700703 status_t ret = initCheck();
704 if (ret != NO_ERROR) {
705 return ret;
706 }
707
Mathias Agopian65ab4712010-07-14 17:59:35 -0700708 // check calling permissions
709 if (!settingsAllowed()) {
710 return PERMISSION_DENIED;
711 }
712
John Grossman93d90682012-07-23 17:05:46 -0700713 Mutex::Autolock _l(mLock);
714 mMasterMute = muted;
John Grossman91de9b52012-07-20 14:51:35 -0700715
John Grossman93d90682012-07-23 17:05:46 -0700716 // Set master mute in the HALs which support it.
717 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
718 AutoMutex lock(mHardwareLock);
719 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman91de9b52012-07-20 14:51:35 -0700720
John Grossman93d90682012-07-23 17:05:46 -0700721 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
722 if (dev->canSetMasterMute()) {
723 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossman91de9b52012-07-20 14:51:35 -0700724 }
John Grossman93d90682012-07-23 17:05:46 -0700725 mHardwareStatus = AUDIO_HW_IDLE;
John Grossman91de9b52012-07-20 14:51:35 -0700726 }
727
John Grossman93d90682012-07-23 17:05:46 -0700728 // Now set the master mute in each playback thread. Playback threads
729 // assigned to HALs which do not have master mute support will apply master
730 // mute during the mix operation. Threads with HALs which do support master
731 // mute will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800732 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossman93d90682012-07-23 17:05:46 -0700733 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700734
735 return NO_ERROR;
736}
737
738float AudioFlinger::masterVolume() const
739{
Glenn Kasten98067102011-12-13 11:47:54 -0800740 Mutex::Autolock _l(mLock);
741 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700742}
743
744bool AudioFlinger::masterMute() const
745{
Glenn Kasten98067102011-12-13 11:47:54 -0800746 Mutex::Autolock _l(mLock);
747 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700748}
749
John Grossman4ff14ba2012-02-08 16:37:41 -0800750float AudioFlinger::masterVolume_l() const
751{
John Grossman4ff14ba2012-02-08 16:37:41 -0800752 return mMasterVolume;
753}
754
John Grossman91de9b52012-07-20 14:51:35 -0700755bool AudioFlinger::masterMute_l() const
756{
John Grossman93d90682012-07-23 17:05:46 -0700757 return mMasterMute;
John Grossman91de9b52012-07-20 14:51:35 -0700758}
759
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800760status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
761 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700762{
763 // check calling permissions
764 if (!settingsAllowed()) {
765 return PERMISSION_DENIED;
766 }
767
Glenn Kasten263709e2012-01-06 08:40:01 -0800768 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000769 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700770 return BAD_VALUE;
771 }
772
773 AutoMutex lock(mLock);
774 PlaybackThread *thread = NULL;
775 if (output) {
776 thread = checkPlaybackThread_l(output);
777 if (thread == NULL) {
778 return BAD_VALUE;
779 }
780 }
781
782 mStreamTypes[stream].volume = value;
783
784 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800785 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700786 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700787 }
788 } else {
789 thread->setStreamVolume(stream, value);
790 }
791
792 return NO_ERROR;
793}
794
Glenn Kastenfff6d712012-01-12 16:38:12 -0800795status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796{
797 // check calling permissions
798 if (!settingsAllowed()) {
799 return PERMISSION_DENIED;
800 }
801
Glenn Kasten263709e2012-01-06 08:40:01 -0800802 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700803 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000804 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805 return BAD_VALUE;
806 }
807
Eric Laurent93575202011-01-18 18:39:02 -0800808 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700809 mStreamTypes[stream].mute = muted;
810 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700811 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700812
813 return NO_ERROR;
814}
815
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800816float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817{
Glenn Kasten263709e2012-01-06 08:40:01 -0800818 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700819 return 0.0f;
820 }
821
822 AutoMutex lock(mLock);
823 float volume;
824 if (output) {
825 PlaybackThread *thread = checkPlaybackThread_l(output);
826 if (thread == NULL) {
827 return 0.0f;
828 }
829 volume = thread->streamVolume(stream);
830 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800831 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700832 }
833
834 return volume;
835}
836
Glenn Kastenfff6d712012-01-12 16:38:12 -0800837bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838{
Glenn Kasten263709e2012-01-06 08:40:01 -0800839 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700840 return true;
841 }
842
Glenn Kasten6637baa2012-01-09 09:40:36 -0800843 AutoMutex lock(mLock);
844 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845}
846
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800847status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700848{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800849 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700850 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
851 // check calling permissions
852 if (!settingsAllowed()) {
853 return PERMISSION_DENIED;
854 }
855
Mathias Agopian65ab4712010-07-14 17:59:35 -0700856 // ioHandle == 0 means the parameters are global to the audio hardware interface
857 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700858 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700859 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800860 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700861 AutoMutex lock(mHardwareLock);
862 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
863 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
864 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
865 status_t result = dev->set_parameters(dev, keyValuePairs.string());
866 final_result = result ?: final_result;
867 }
868 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800869 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700870 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
871 AudioParameter param = AudioParameter(keyValuePairs);
872 String8 value;
873 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700874 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
875 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700876 for (size_t i = 0; i < mRecordThreads.size(); i++) {
877 sp<RecordThread> thread = mRecordThreads.valueAt(i);
878 RecordThread::RecordTrack *track = thread->track();
879 if (track != NULL) {
Glenn Kastenbb4350d2012-07-03 15:56:38 -0700880 audio_devices_t device = thread->device() & AUDIO_DEVICE_IN_ALL;
Eric Laurentbee53372011-08-29 12:42:48 -0700881 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700882 thread->setEffectSuspended(FX_IID_AEC,
883 suspend,
884 track->sessionId());
885 thread->setEffectSuspended(FX_IID_NS,
886 suspend,
887 track->sessionId());
888 }
889 }
Eric Laurentbee53372011-08-29 12:42:48 -0700890 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700891 }
892 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700893 String8 screenState;
894 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
895 bool isOff = screenState == "off";
896 if (isOff != (gScreenState & 1)) {
897 gScreenState = ((gScreenState & ~1) + 2) | isOff;
898 }
899 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700900 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700901 }
902
903 // hold a strong ref on thread in case closeOutput() or closeInput() is called
904 // and the thread is exited once the lock is released
905 sp<ThreadBase> thread;
906 {
907 Mutex::Autolock _l(mLock);
908 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -0700909 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700910 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800911 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700912 // indicate output device change to all input threads for pre processing
913 AudioParameter param = AudioParameter(keyValuePairs);
914 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700915 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
916 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700917 for (size_t i = 0; i < mRecordThreads.size(); i++) {
918 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
919 }
920 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700921 }
922 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800923 if (thread != 0) {
924 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700925 }
926 return BAD_VALUE;
927}
928
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800929String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700930{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800931// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700932// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
933
Eric Laurenta4c5a552012-03-29 10:12:40 -0700934 Mutex::Autolock _l(mLock);
935
Mathias Agopian65ab4712010-07-14 17:59:35 -0700936 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700937 String8 out_s8;
938
Dima Zavin799a70e2011-04-18 16:57:27 -0700939 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800940 char *s;
941 {
942 AutoMutex lock(mHardwareLock);
943 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700944 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800945 s = dev->get_parameters(dev, keys.string());
946 mHardwareStatus = AUDIO_HW_IDLE;
947 }
John Grossmanef7740b2012-02-09 11:28:36 -0800948 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700949 free(s);
950 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700951 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700952 }
953
Mathias Agopian65ab4712010-07-14 17:59:35 -0700954 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
955 if (playbackThread != NULL) {
956 return playbackThread->getParameters(keys);
957 }
958 RecordThread *recordThread = checkRecordThread_l(ioHandle);
959 if (recordThread != NULL) {
960 return recordThread->getParameters(keys);
961 }
962 return String8("");
963}
964
Glenn Kastendd8104c2012-07-02 12:42:44 -0700965size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
966 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700967{
Eric Laurenta1884f92011-08-23 08:25:03 -0700968 status_t ret = initCheck();
969 if (ret != NO_ERROR) {
970 return 0;
971 }
972
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800973 AutoMutex lock(mHardwareLock);
974 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700975 struct audio_config config = {
976 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -0700977 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700978 format: format,
979 };
John Grossman93d90682012-07-23 17:05:46 -0700980 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
981 size_t size = dev->get_input_buffer_size(dev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800982 mHardwareStatus = AUDIO_HW_IDLE;
983 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700984}
985
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800986unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700987{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700988 Mutex::Autolock _l(mLock);
989
990 RecordThread *recordThread = checkRecordThread_l(ioHandle);
991 if (recordThread != NULL) {
992 return recordThread->getInputFramesLost();
993 }
994 return 0;
995}
996
997status_t AudioFlinger::setVoiceVolume(float value)
998{
Eric Laurenta1884f92011-08-23 08:25:03 -0700999 status_t ret = initCheck();
1000 if (ret != NO_ERROR) {
1001 return ret;
1002 }
1003
Mathias Agopian65ab4712010-07-14 17:59:35 -07001004 // check calling permissions
1005 if (!settingsAllowed()) {
1006 return PERMISSION_DENIED;
1007 }
1008
1009 AutoMutex lock(mHardwareLock);
John Grossman93d90682012-07-23 17:05:46 -07001010 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001011 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossman93d90682012-07-23 17:05:46 -07001012 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001013 mHardwareStatus = AUDIO_HW_IDLE;
1014
1015 return ret;
1016}
1017
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001018status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1019 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001020{
1021 status_t status;
1022
1023 Mutex::Autolock _l(mLock);
1024
1025 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1026 if (playbackThread != NULL) {
1027 return playbackThread->getRenderPosition(halFrames, dspFrames);
1028 }
1029
1030 return BAD_VALUE;
1031}
1032
1033void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1034{
1035
1036 Mutex::Autolock _l(mLock);
1037
Glenn Kastenbb001922012-02-03 11:10:26 -08001038 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001039 if (mNotificationClients.indexOfKey(pid) < 0) {
1040 sp<NotificationClient> notificationClient = new NotificationClient(this,
1041 client,
1042 pid);
Steve Block3856b092011-10-20 11:56:00 +01001043 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001044
1045 mNotificationClients.add(pid, notificationClient);
1046
1047 sp<IBinder> binder = client->asBinder();
1048 binder->linkToDeath(notificationClient);
1049
1050 // the config change is always sent from playback or record threads to avoid deadlock
1051 // with AudioSystem::gLock
1052 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1053 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1054 }
1055
1056 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1057 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1058 }
1059 }
1060}
1061
1062void AudioFlinger::removeNotificationClient(pid_t pid)
1063{
1064 Mutex::Autolock _l(mLock);
1065
Glenn Kastena3b09252012-01-20 09:19:01 -08001066 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001067
Steve Block3856b092011-10-20 11:56:00 +01001068 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001069 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001070 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001071 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001072 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001073 ALOGV(" pid %d @ %d", ref->mPid, i);
1074 if (ref->mPid == pid) {
1075 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001076 mAudioSessionRefs.removeAt(i);
1077 delete ref;
1078 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001079 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001080 } else {
1081 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001082 }
1083 }
1084 if (removed) {
1085 purgeStaleEffects_l();
1086 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001087}
1088
1089// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001090void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001091{
1092 size_t size = mNotificationClients.size();
1093 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001094 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1095 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001096 }
1097}
1098
1099// removeClient_l() must be called with AudioFlinger::mLock held
1100void AudioFlinger::removeClient_l(pid_t pid)
1101{
Steve Block3856b092011-10-20 11:56:00 +01001102 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001103 mClients.removeItem(pid);
1104}
1105
Eric Laurent717e1282012-06-29 16:36:52 -07001106// getEffectThread_l() must be called with AudioFlinger::mLock held
1107sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1108{
1109 sp<PlaybackThread> thread;
1110
1111 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1112 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1113 ALOG_ASSERT(thread == 0);
1114 thread = mPlaybackThreads.valueAt(i);
1115 }
1116 }
1117
1118 return thread;
1119}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001120
1121// ----------------------------------------------------------------------------
1122
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001123AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001124 audio_devices_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001125 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001126 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001127 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001128 // mChannelMask
1129 mChannelCount(0),
1130 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1131 mParamStatus(NO_ERROR),
Glenn Kasten5ad92f62012-07-19 10:02:15 -07001132 mStandby(false), mDevice(device), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001133 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001134{
1135}
1136
1137AudioFlinger::ThreadBase::~ThreadBase()
1138{
1139 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001140 // do not lock the mutex in destructor
1141 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001142 if (mPowerManager != 0) {
1143 sp<IBinder> binder = mPowerManager->asBinder();
1144 binder->unlinkToDeath(mDeathRecipient);
1145 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001146}
1147
1148void AudioFlinger::ThreadBase::exit()
1149{
Steve Block3856b092011-10-20 11:56:00 +01001150 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001151 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001152 // This lock prevents the following race in thread (uniprocessor for illustration):
1153 // if (!exitPending()) {
1154 // // context switch from here to exit()
1155 // // exit() calls requestExit(), what exitPending() observes
1156 // // exit() calls signal(), which is dropped since no waiters
1157 // // context switch back from exit() to here
1158 // mWaitWorkCV.wait(...);
1159 // // now thread is hung
1160 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001161 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001162 requestExit();
1163 mWaitWorkCV.signal();
1164 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001165 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1166 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001167 requestExitAndWait();
1168}
1169
Mathias Agopian65ab4712010-07-14 17:59:35 -07001170status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1171{
1172 status_t status;
1173
Steve Block3856b092011-10-20 11:56:00 +01001174 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001175 Mutex::Autolock _l(mLock);
1176
1177 mNewParameters.add(keyValuePairs);
1178 mWaitWorkCV.signal();
1179 // wait condition with timeout in case the thread loop has exited
1180 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001181 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001182 status = mParamStatus;
1183 mWaitWorkCV.signal();
1184 } else {
1185 status = TIMED_OUT;
1186 }
1187 return status;
1188}
1189
1190void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1191{
1192 Mutex::Autolock _l(mLock);
1193 sendConfigEvent_l(event, param);
1194}
1195
1196// sendConfigEvent_l() must be called with ThreadBase::mLock held
1197void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1198{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001199 ConfigEvent configEvent;
1200 configEvent.mEvent = event;
1201 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001202 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001203 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001204 mWaitWorkCV.signal();
1205}
1206
1207void AudioFlinger::ThreadBase::processConfigEvents()
1208{
1209 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001210 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001211 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001212 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001213 mConfigEvents.removeAt(0);
1214 // release mLock before locking AudioFlinger mLock: lock order is always
1215 // AudioFlinger then ThreadBase to avoid cross deadlock
1216 mLock.unlock();
1217 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001218 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001219 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001220 mLock.lock();
1221 }
1222 mLock.unlock();
1223}
1224
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001225void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001226{
1227 const size_t SIZE = 256;
1228 char buffer[SIZE];
1229 String8 result;
1230
1231 bool locked = tryLock(mLock);
1232 if (!locked) {
1233 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1234 write(fd, buffer, strlen(buffer));
1235 }
1236
Eric Laurent612bbb52012-03-14 15:03:26 -07001237 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1238 result.append(buffer);
1239 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1240 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001241 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1242 result.append(buffer);
1243 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1244 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001245 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1246 result.append(buffer);
1247 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001248 result.append(buffer);
1249 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1250 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001251 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1252 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001253 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1254 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001255 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001256 result.append(buffer);
1257
1258 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1259 result.append(buffer);
1260 result.append(" Index Command");
1261 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1262 snprintf(buffer, SIZE, "\n %02d ", i);
1263 result.append(buffer);
1264 result.append(mNewParameters[i]);
1265 }
1266
1267 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1268 result.append(buffer);
1269 snprintf(buffer, SIZE, " Index event param\n");
1270 result.append(buffer);
1271 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001272 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001273 result.append(buffer);
1274 }
1275 result.append("\n");
1276
1277 write(fd, result.string(), result.size());
1278
1279 if (locked) {
1280 mLock.unlock();
1281 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001282}
1283
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001284void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001285{
1286 const size_t SIZE = 256;
1287 char buffer[SIZE];
1288 String8 result;
1289
1290 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1291 write(fd, buffer, strlen(buffer));
1292
1293 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1294 sp<EffectChain> chain = mEffectChains[i];
1295 if (chain != 0) {
1296 chain->dump(fd, args);
1297 }
1298 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001299}
1300
Eric Laurentfeb0db62011-07-22 09:04:31 -07001301void AudioFlinger::ThreadBase::acquireWakeLock()
1302{
1303 Mutex::Autolock _l(mLock);
1304 acquireWakeLock_l();
1305}
1306
1307void AudioFlinger::ThreadBase::acquireWakeLock_l()
1308{
1309 if (mPowerManager == 0) {
1310 // use checkService() to avoid blocking if power service is not up yet
1311 sp<IBinder> binder =
1312 defaultServiceManager()->checkService(String16("power"));
1313 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001314 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001315 } else {
1316 mPowerManager = interface_cast<IPowerManager>(binder);
1317 binder->linkToDeath(mDeathRecipient);
1318 }
1319 }
1320 if (mPowerManager != 0) {
1321 sp<IBinder> binder = new BBinder();
1322 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1323 binder,
1324 String16(mName));
1325 if (status == NO_ERROR) {
1326 mWakeLockToken = binder;
1327 }
Steve Block3856b092011-10-20 11:56:00 +01001328 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001329 }
1330}
1331
1332void AudioFlinger::ThreadBase::releaseWakeLock()
1333{
1334 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001335 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001336}
1337
1338void AudioFlinger::ThreadBase::releaseWakeLock_l()
1339{
1340 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001341 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001342 if (mPowerManager != 0) {
1343 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1344 }
1345 mWakeLockToken.clear();
1346 }
1347}
1348
1349void AudioFlinger::ThreadBase::clearPowerManager()
1350{
1351 Mutex::Autolock _l(mLock);
1352 releaseWakeLock_l();
1353 mPowerManager.clear();
1354}
1355
1356void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1357{
1358 sp<ThreadBase> thread = mThread.promote();
1359 if (thread != 0) {
1360 thread->clearPowerManager();
1361 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001362 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001363}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001364
Eric Laurent59255e42011-07-27 19:49:51 -07001365void AudioFlinger::ThreadBase::setEffectSuspended(
1366 const effect_uuid_t *type, bool suspend, int sessionId)
1367{
1368 Mutex::Autolock _l(mLock);
1369 setEffectSuspended_l(type, suspend, sessionId);
1370}
1371
1372void AudioFlinger::ThreadBase::setEffectSuspended_l(
1373 const effect_uuid_t *type, bool suspend, int sessionId)
1374{
Glenn Kasten090f0192012-01-30 13:00:02 -08001375 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001376 if (chain != 0) {
1377 if (type != NULL) {
1378 chain->setEffectSuspended_l(type, suspend);
1379 } else {
1380 chain->setEffectSuspendedAll_l(suspend);
1381 }
1382 }
1383
1384 updateSuspendedSessions_l(type, suspend, sessionId);
1385}
1386
1387void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1388{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001389 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001390 if (index < 0) {
1391 return;
1392 }
1393
Glenn Kasten0a7af182012-07-09 16:09:19 -07001394 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1395 mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001396
1397 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001398 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001399 for (int j = 0; j < desc->mRefCount; j++) {
1400 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1401 chain->setEffectSuspendedAll_l(true);
1402 } else {
Steve Block3856b092011-10-20 11:56:00 +01001403 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001404 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001405 chain->setEffectSuspended_l(&desc->mType, true);
1406 }
1407 }
1408 }
1409}
1410
Eric Laurent59255e42011-07-27 19:49:51 -07001411void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1412 bool suspend,
1413 int sessionId)
1414{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001415 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001416
1417 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1418
1419 if (suspend) {
1420 if (index >= 0) {
Glenn Kasten0a7af182012-07-09 16:09:19 -07001421 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001422 } else {
1423 mSuspendedSessions.add(sessionId, sessionEffects);
1424 }
1425 } else {
1426 if (index < 0) {
1427 return;
1428 }
Glenn Kasten0a7af182012-07-09 16:09:19 -07001429 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001430 }
1431
1432
1433 int key = EffectChain::kKeyForSuspendAll;
1434 if (type != NULL) {
1435 key = type->timeLow;
1436 }
1437 index = sessionEffects.indexOfKey(key);
1438
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001439 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001440 if (suspend) {
1441 if (index >= 0) {
1442 desc = sessionEffects.valueAt(index);
1443 } else {
1444 desc = new SuspendedSessionDesc();
1445 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001446 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001447 }
1448 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001449 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001450 }
1451 desc->mRefCount++;
1452 } else {
1453 if (index < 0) {
1454 return;
1455 }
1456 desc = sessionEffects.valueAt(index);
1457 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001458 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001459 sessionEffects.removeItemsAt(index);
1460 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001461 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001462 sessionId);
1463 mSuspendedSessions.removeItem(sessionId);
1464 }
1465 }
1466 }
1467 if (!sessionEffects.isEmpty()) {
1468 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1469 }
1470}
1471
1472void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1473 bool enabled,
1474 int sessionId)
1475{
1476 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001477 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1478}
Eric Laurent59255e42011-07-27 19:49:51 -07001479
Eric Laurenta85a74a2011-10-19 11:44:54 -07001480void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1481 bool enabled,
1482 int sessionId)
1483{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001484 if (mType != RECORD) {
1485 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1486 // another session. This gives the priority to well behaved effect control panels
1487 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001488 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1489 // global effects
1490 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001491 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1492 }
1493 }
Eric Laurent59255e42011-07-27 19:49:51 -07001494
1495 sp<EffectChain> chain = getEffectChain_l(sessionId);
1496 if (chain != 0) {
1497 chain->checkSuspendOnEffectEnabled(effect, enabled);
1498 }
1499}
1500
Mathias Agopian65ab4712010-07-14 17:59:35 -07001501// ----------------------------------------------------------------------------
1502
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001503AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1504 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001505 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001506 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001507 type_t type)
1508 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001509 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001510 // mStreamTypes[] initialized in constructor body
1511 mOutput(output),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001512 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001513 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001514 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001515 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001516 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001517 // index 0 is reserved for normal mixer's submix
1518 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001519{
Glenn Kasten480b4682012-02-28 12:30:08 -08001520 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001521
John Grossman93d90682012-07-23 17:05:46 -07001522 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1523 // it would be safer to explicitly pass initial masterVolume/masterMute as
1524 // parameter.
1525 //
1526 // If the HAL we are using has support for master volume or master mute,
1527 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1528 // and the mute set to false).
1529 mMasterVolume = audioFlinger->masterVolume_l();
1530 mMasterMute = audioFlinger->masterMute_l();
1531 if (mOutput && mOutput->audioHwDev) {
1532 if (mOutput->audioHwDev->canSetMasterVolume()) {
1533 mMasterVolume = 1.0;
1534 }
1535
1536 if (mOutput->audioHwDev->canSetMasterMute()) {
1537 mMasterMute = false;
1538 }
1539 }
1540
Mathias Agopian65ab4712010-07-14 17:59:35 -07001541 readOutputParameters();
1542
Glenn Kasten263709e2012-01-06 08:40:01 -08001543 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001544 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1545 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1546 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001547 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1548 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001549 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001550 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1551 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001552}
1553
1554AudioFlinger::PlaybackThread::~PlaybackThread()
1555{
1556 delete [] mMixBuffer;
1557}
1558
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001559void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001560{
1561 dumpInternals(fd, args);
1562 dumpTracks(fd, args);
1563 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001564}
1565
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001566void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001567{
1568 const size_t SIZE = 256;
1569 char buffer[SIZE];
1570 String8 result;
1571
Glenn Kasten58912562012-04-03 10:45:00 -07001572 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1573 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1574 const stream_type_t *st = &mStreamTypes[i];
1575 if (i > 0) {
1576 result.appendFormat(", ");
1577 }
1578 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1579 if (st->mute) {
1580 result.append("M");
1581 }
1582 }
1583 result.append("\n");
1584 write(fd, result.string(), result.length());
1585 result.clear();
1586
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1588 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001589 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001590 for (size_t i = 0; i < mTracks.size(); ++i) {
1591 sp<Track> track = mTracks[i];
1592 if (track != 0) {
1593 track->dump(buffer, SIZE);
1594 result.append(buffer);
1595 }
1596 }
1597
1598 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1599 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001600 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001601 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001602 sp<Track> track = mActiveTracks[i].promote();
1603 if (track != 0) {
1604 track->dump(buffer, SIZE);
1605 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001606 }
1607 }
1608 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001609
1610 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1611 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1612 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1613 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614}
1615
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001616void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001617{
1618 const size_t SIZE = 256;
1619 char buffer[SIZE];
1620 String8 result;
1621
1622 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1623 result.append(buffer);
1624 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1625 result.append(buffer);
1626 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1627 result.append(buffer);
1628 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1629 result.append(buffer);
1630 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1631 result.append(buffer);
1632 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1633 result.append(buffer);
1634 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1635 result.append(buffer);
1636 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001637 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001638
1639 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001640}
1641
1642// Thread virtuals
1643status_t AudioFlinger::PlaybackThread::readyToRun()
1644{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001645 status_t status = initCheck();
1646 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001647 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001648 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001649 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001650 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001651 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001652}
1653
1654void AudioFlinger::PlaybackThread::onFirstRef()
1655{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001656 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001657}
1658
1659// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001660sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001661 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001662 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001663 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001664 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001665 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001666 int frameCount,
1667 const sp<IMemory>& sharedBuffer,
1668 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001669 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001670 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001671 status_t *status)
1672{
1673 sp<Track> track;
1674 status_t lStatus;
1675
Glenn Kasten73d22752012-03-19 13:38:30 -07001676 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1677
1678 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001679 if (flags & IAudioFlinger::TRACK_FAST) {
1680 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001681 // not timed
1682 (!isTimed) &&
1683 // either of these use cases:
1684 (
1685 // use case 1: shared buffer with any frame count
1686 (
1687 (sharedBuffer != 0)
1688 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001689 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001690 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001691 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001692 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001693 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001694 )
1695 ) &&
1696 // PCM data
1697 audio_is_linear_pcm(format) &&
1698 // mono or stereo
1699 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1700 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001701#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001702 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001703 (sampleRate == mSampleRate) &&
1704#endif
1705 // normal mixer has an associated fast mixer
1706 hasFastMixer() &&
1707 // there are sufficient fast track slots available
1708 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001709 // FIXME test that MixerThread for this fast track has a capable output HAL
1710 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001711 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001712 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1713 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001714 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001715 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001716 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001717 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001718 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001719 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07001720 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001721 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1722 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1723 audio_is_linear_pcm(format),
1724 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001725 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001726 // For compatibility with AudioTrack calculation, buffer depth is forced
1727 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1728 // This is probably too conservative, but legacy application code may depend on it.
1729 // If you change this calculation, also review the start threshold which is related.
1730 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1731 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1732 if (minBufCount < 2) {
1733 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001734 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001735 int minFrameCount = mNormalFrameCount * minBufCount;
1736 if (frameCount < minFrameCount) {
1737 frameCount = minFrameCount;
1738 }
1739 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001740 }
1741
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001743 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1744 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001745 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001746 "for output %p with format %d",
1747 sampleRate, format, channelMask, mOutput, mFormat);
1748 lStatus = BAD_VALUE;
1749 goto Exit;
1750 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001751 }
1752 } else {
1753 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1754 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001755 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001756 lStatus = BAD_VALUE;
1757 goto Exit;
1758 }
1759 }
1760
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001761 lStatus = initCheck();
1762 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001763 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764 goto Exit;
1765 }
1766
1767 { // scope for mLock
1768 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001769
1770 // all tracks in same audio session must share the same routing strategy otherwise
1771 // conflicts will happen when tracks are moved from one output to another by audio policy
1772 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001773 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001774 for (size_t i = 0; i < mTracks.size(); ++i) {
1775 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001776 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001777 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001778 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001779 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001780 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001781 lStatus = BAD_VALUE;
1782 goto Exit;
1783 }
1784 }
1785 }
1786
John Grossman4ff14ba2012-02-08 16:37:41 -08001787 if (!isTimed) {
1788 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001789 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001790 } else {
1791 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1792 channelMask, frameCount, sharedBuffer, sessionId);
1793 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001794 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001795 lStatus = NO_MEMORY;
1796 goto Exit;
1797 }
1798 mTracks.add(track);
1799
1800 sp<EffectChain> chain = getEffectChain_l(sessionId);
1801 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001802 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001803 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001804 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001805 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001806 }
1807 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001808
Glenn Kasten3acbd052012-02-28 10:39:56 -08001809 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1810 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1811 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1812 // so ask activity manager to do this on our behalf
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07001813 int err = requestPriority(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001814 if (err != 0) {
1815 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07001816 kPriorityAudioApp, callingPid, tid, err);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001817 }
1818 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001819
Mathias Agopian65ab4712010-07-14 17:59:35 -07001820 lStatus = NO_ERROR;
1821
1822Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001823 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001824 *status = lStatus;
1825 }
1826 return track;
1827}
1828
Eric Laurente737cda2012-05-22 18:55:44 -07001829uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1830{
1831 if (mFastMixer != NULL) {
1832 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1833 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1834 }
1835 return latency;
1836}
1837
1838uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1839{
1840 return latency;
1841}
1842
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843uint32_t AudioFlinger::PlaybackThread::latency() const
1844{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001845 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001846 return latency_l();
1847}
1848uint32_t AudioFlinger::PlaybackThread::latency_l() const
1849{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001850 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001851 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001852 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853 return 0;
1854 }
1855}
1856
Glenn Kasten6637baa2012-01-09 09:40:36 -08001857void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001858{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001859 Mutex::Autolock _l(mLock);
John Grossman93d90682012-07-23 17:05:46 -07001860 // Don't apply master volume in SW if our HAL can do it for us.
1861 if (mOutput && mOutput->audioHwDev &&
1862 mOutput->audioHwDev->canSetMasterVolume()) {
1863 mMasterVolume = 1.0;
1864 } else {
1865 mMasterVolume = value;
1866 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001867}
1868
Glenn Kasten6637baa2012-01-09 09:40:36 -08001869void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001870{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001871 Mutex::Autolock _l(mLock);
John Grossman93d90682012-07-23 17:05:46 -07001872 // Don't apply master mute in SW if our HAL can do it for us.
1873 if (mOutput && mOutput->audioHwDev &&
1874 mOutput->audioHwDev->canSetMasterMute()) {
1875 mMasterMute = false;
1876 } else {
1877 mMasterMute = muted;
1878 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001879}
1880
Glenn Kasten6637baa2012-01-09 09:40:36 -08001881void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001882{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001883 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001884 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001885}
1886
Glenn Kasten6637baa2012-01-09 09:40:36 -08001887void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001888{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001889 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001890 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001891}
1892
Glenn Kastenfff6d712012-01-12 16:38:12 -08001893float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001894{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001895 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001896 return mStreamTypes[stream].volume;
1897}
1898
Mathias Agopian65ab4712010-07-14 17:59:35 -07001899// addTrack_l() must be called with ThreadBase::mLock held
1900status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1901{
1902 status_t status = ALREADY_EXISTS;
1903
1904 // set retry count for buffer fill
1905 track->mRetryCount = kMaxTrackStartupRetries;
1906 if (mActiveTracks.indexOf(track) < 0) {
1907 // the track is newly added, make sure it fills up all its
1908 // buffers before playing. This is to ensure the client will
1909 // effectively get the latency it requested.
1910 track->mFillingUpStatus = Track::FS_FILLING;
1911 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001912 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001913 mActiveTracks.add(track);
1914 if (track->mainBuffer() != mMixBuffer) {
1915 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1916 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001917 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001918 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001919 }
1920 }
1921
1922 status = NO_ERROR;
1923 }
1924
Steve Block3856b092011-10-20 11:56:00 +01001925 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926 mWaitWorkCV.broadcast();
1927
1928 return status;
1929}
1930
1931// destroyTrack_l() must be called with ThreadBase::mLock held
1932void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1933{
1934 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001935 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001936 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001937 removeTrack_l(track);
1938 }
1939}
1940
1941void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1942{
Eric Laurent29864602012-05-08 18:57:51 -07001943 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001944 mTracks.remove(track);
1945 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001946 // redundant as track is about to be destroyed, for dumpsys only
1947 track->mName = -1;
1948 if (track->isFastTrack()) {
1949 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001950 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001951 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1952 mFastTrackAvailMask |= 1 << index;
1953 // redundant as track is about to be destroyed, for dumpsys only
1954 track->mFastIndex = -1;
1955 }
Eric Laurentb469b942011-05-09 12:09:06 -07001956 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1957 if (chain != 0) {
1958 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959 }
1960}
1961
1962String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1963{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001964 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001965 char *s;
1966
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001967 Mutex::Autolock _l(mLock);
1968 if (initCheck() != NO_ERROR) {
1969 return out_s8;
1970 }
1971
Dima Zavin799a70e2011-04-18 16:57:27 -07001972 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001973 out_s8 = String8(s);
1974 free(s);
1975 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001976}
1977
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001978// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001979void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1980 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001981 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001982
Steve Block3856b092011-10-20 11:56:00 +01001983 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001984
1985 switch (event) {
1986 case AudioSystem::OUTPUT_OPENED:
1987 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001988 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001989 desc.samplingRate = mSampleRate;
1990 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001991 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992 desc.latency = latency();
1993 param2 = &desc;
1994 break;
1995
1996 case AudioSystem::STREAM_CONFIG_CHANGED:
1997 param2 = &param;
1998 case AudioSystem::OUTPUT_CLOSED:
1999 default:
2000 break;
2001 }
2002 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2003}
2004
2005void AudioFlinger::PlaybackThread::readOutputParameters()
2006{
Dima Zavin799a70e2011-04-18 16:57:27 -07002007 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002008 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2009 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07002010 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002011 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002012 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002013 if (mFrameCount & 15) {
2014 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2015 mFrameCount);
2016 }
2017
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002018 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002019 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002020 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002021 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002022 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2023 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2024 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2025 maxNormalFrameCount = maxNormalFrameCount & ~15;
2026 if (maxNormalFrameCount < minNormalFrameCount) {
2027 maxNormalFrameCount = minNormalFrameCount;
2028 }
2029 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2030 if (multiplier <= 1.0) {
2031 multiplier = 1.0;
2032 } else if (multiplier <= 2.0) {
2033 if (2 * mFrameCount <= maxNormalFrameCount) {
2034 multiplier = 2.0;
2035 } else {
2036 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2037 }
2038 } else {
2039 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2040 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2041 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2042 // FIXME this rounding up should not be done if no HAL SRC
2043 uint32_t truncMult = (uint32_t) multiplier;
2044 if ((truncMult & 1)) {
2045 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2046 ++truncMult;
2047 }
2048 }
2049 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002050 }
Glenn Kasten58912562012-04-03 10:45:00 -07002051 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002052 mNormalFrameCount = multiplier * mFrameCount;
2053 // round up to nearest 16 frames to satisfy AudioMixer
2054 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002055 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002056
Glenn Kastene9dd0172012-01-27 18:08:45 -08002057 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002058 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2059 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002060
Eric Laurentde070132010-07-13 04:45:46 -07002061 // force reconfiguration of effect chains and engines to take new buffer size and audio
2062 // parameters into account
2063 // Note that mLock is not held when readOutputParameters() is called from the constructor
2064 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2065 // matter.
2066 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2067 Vector< sp<EffectChain> > effectChains = mEffectChains;
2068 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002069 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002070 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002071}
2072
Eric Laurente737cda2012-05-22 18:55:44 -07002073
Mathias Agopian65ab4712010-07-14 17:59:35 -07002074status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2075{
Glenn Kastena0d68332012-01-27 16:47:15 -08002076 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002077 return BAD_VALUE;
2078 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002079 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002080 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002081 return INVALID_OPERATION;
2082 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002083 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002084
Dima Zavin799a70e2011-04-18 16:57:27 -07002085 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002086}
2087
Eric Laurent39e94f82010-07-28 01:32:47 -07002088uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002089{
2090 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002091 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002092 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002093 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002094 }
2095
2096 for (size_t i = 0; i < mTracks.size(); ++i) {
2097 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002098 if (sessionId == track->sessionId() &&
2099 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002100 result |= TRACK_SESSION;
2101 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002102 }
2103 }
2104
Eric Laurent39e94f82010-07-28 01:32:47 -07002105 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002106}
2107
Eric Laurentde070132010-07-13 04:45:46 -07002108uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2109{
Dima Zavinfce7a472011-04-19 22:30:36 -07002110 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002111 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002112 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2113 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002114 }
2115 for (size_t i = 0; i < mTracks.size(); i++) {
2116 sp<Track> track = mTracks[i];
2117 if (sessionId == track->sessionId() &&
2118 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002119 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002120 }
2121 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002122 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002123}
2124
Mathias Agopian65ab4712010-07-14 17:59:35 -07002125
Glenn Kastenaed850d2012-01-26 09:46:34 -08002126AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002127{
2128 Mutex::Autolock _l(mLock);
2129 return mOutput;
2130}
2131
2132AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2133{
2134 Mutex::Autolock _l(mLock);
2135 AudioStreamOut *output = mOutput;
2136 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002137 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2138 // must push a NULL and wait for ack
2139 mOutputSink.clear();
2140 mPipeSink.clear();
2141 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002142 return output;
2143}
2144
2145// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002146audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002147{
2148 if (mOutput == NULL) {
2149 return NULL;
2150 }
2151 return &mOutput->stream->common;
2152}
2153
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002154uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002155{
Eric Laurentab9071b2012-06-04 13:45:29 -07002156 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002157}
2158
Eric Laurenta011e352012-03-29 15:51:43 -07002159status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2160{
2161 if (!isValidSyncEvent(event)) {
2162 return BAD_VALUE;
2163 }
2164
2165 Mutex::Autolock _l(mLock);
2166
2167 for (size_t i = 0; i < mTracks.size(); ++i) {
2168 sp<Track> track = mTracks[i];
2169 if (event->triggerSession() == track->sessionId()) {
2170 track->setSyncEvent(event);
2171 return NO_ERROR;
2172 }
2173 }
2174
2175 return NAME_NOT_FOUND;
2176}
2177
2178bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2179{
2180 switch (event->type()) {
2181 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2182 return true;
2183 default:
2184 break;
2185 }
2186 return false;
2187}
2188
Eric Laurent44a957f2012-05-15 15:26:05 -07002189void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2190{
2191 size_t count = tracksToRemove.size();
2192 if (CC_UNLIKELY(count)) {
2193 for (size_t i = 0 ; i < count ; i++) {
2194 const sp<Track>& track = tracksToRemove.itemAt(i);
2195 if ((track->sharedBuffer() != 0) &&
2196 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2197 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2198 }
2199 }
2200 }
2201
2202}
2203
Mathias Agopian65ab4712010-07-14 17:59:35 -07002204// ----------------------------------------------------------------------------
2205
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002206AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002207 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002208 : PlaybackThread(audioFlinger, output, id, device, type),
2209 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002210 // mFastMixer below
2211 mFastMixerFutex(0)
2212 // mOutputSink below
2213 // mPipeSink below
2214 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002215{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002216 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002217 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002218 "mFrameCount=%d, mNormalFrameCount=%d",
2219 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2220 mNormalFrameCount);
2221 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2222
Mathias Agopian65ab4712010-07-14 17:59:35 -07002223 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002224 if (mChannelCount != FCC_2) {
2225 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002226 }
Glenn Kasten58912562012-04-03 10:45:00 -07002227
2228 // create an NBAIO sink for the HAL output stream, and negotiate
2229 mOutputSink = new AudioStreamOutSink(output->stream);
2230 size_t numCounterOffers = 0;
2231 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2232 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2233 ALOG_ASSERT(index == 0);
2234
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002235 // initialize fast mixer depending on configuration
2236 bool initFastMixer;
2237 switch (kUseFastMixer) {
2238 case FastMixer_Never:
2239 initFastMixer = false;
2240 break;
2241 case FastMixer_Always:
2242 initFastMixer = true;
2243 break;
2244 case FastMixer_Static:
2245 case FastMixer_Dynamic:
2246 initFastMixer = mFrameCount < mNormalFrameCount;
2247 break;
2248 }
2249 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002250
2251 // create a MonoPipe to connect our submix to FastMixer
2252 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002253 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2254 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2255 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2256 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002257 const NBAIO_Format offers[1] = {format};
2258 size_t numCounterOffers = 0;
2259 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2260 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002261 monoPipe->setAvgFrames((mScreenState & 1) ?
2262 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002263 mPipeSink = monoPipe;
2264
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002265#ifdef TEE_SINK_FRAMES
2266 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2267 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2268 numCounterOffers = 0;
2269 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2270 ALOG_ASSERT(index == 0);
2271 mTeeSink = teeSink;
2272 PipeReader *teeSource = new PipeReader(*teeSink);
2273 numCounterOffers = 0;
2274 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2275 ALOG_ASSERT(index == 0);
2276 mTeeSource = teeSource;
2277#endif
2278
Glenn Kasten58912562012-04-03 10:45:00 -07002279 // create fast mixer and configure it initially with just one fast track for our submix
2280 mFastMixer = new FastMixer();
2281 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002282#ifdef STATE_QUEUE_DUMP
2283 sq->setObserverDump(&mStateQueueObserverDump);
2284 sq->setMutatorDump(&mStateQueueMutatorDump);
2285#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002286 FastMixerState *state = sq->begin();
2287 FastTrack *fastTrack = &state->mFastTracks[0];
2288 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2289 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2290 fastTrack->mVolumeProvider = NULL;
2291 fastTrack->mGeneration++;
2292 state->mFastTracksGen++;
2293 state->mTrackMask = 1;
2294 // fast mixer will use the HAL output sink
2295 state->mOutputSink = mOutputSink.get();
2296 state->mOutputSinkGen++;
2297 state->mFrameCount = mFrameCount;
2298 state->mCommand = FastMixerState::COLD_IDLE;
2299 // already done in constructor initialization list
2300 //mFastMixerFutex = 0;
2301 state->mColdFutexAddr = &mFastMixerFutex;
2302 state->mColdGen++;
2303 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002304 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002305 sq->end();
2306 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2307
2308 // start the fast mixer
2309 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002310 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002311 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002312 if (err != 0) {
2313 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002314 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002315 }
Glenn Kasten58912562012-04-03 10:45:00 -07002316
Glenn Kastenc15d6652012-05-30 14:52:57 -07002317#ifdef AUDIO_WATCHDOG
2318 // create and start the watchdog
2319 mAudioWatchdog = new AudioWatchdog();
2320 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2321 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2322 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002323 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002324 if (err != 0) {
2325 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002326 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002327 }
2328#endif
2329
Glenn Kasten58912562012-04-03 10:45:00 -07002330 } else {
2331 mFastMixer = NULL;
2332 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002333
2334 switch (kUseFastMixer) {
2335 case FastMixer_Never:
2336 case FastMixer_Dynamic:
2337 mNormalSink = mOutputSink;
2338 break;
2339 case FastMixer_Always:
2340 mNormalSink = mPipeSink;
2341 break;
2342 case FastMixer_Static:
2343 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2344 break;
2345 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002346}
2347
2348AudioFlinger::MixerThread::~MixerThread()
2349{
Glenn Kasten58912562012-04-03 10:45:00 -07002350 if (mFastMixer != NULL) {
2351 FastMixerStateQueue *sq = mFastMixer->sq();
2352 FastMixerState *state = sq->begin();
2353 if (state->mCommand == FastMixerState::COLD_IDLE) {
2354 int32_t old = android_atomic_inc(&mFastMixerFutex);
2355 if (old == -1) {
2356 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2357 }
2358 }
2359 state->mCommand = FastMixerState::EXIT;
2360 sq->end();
2361 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2362 mFastMixer->join();
2363 // Though the fast mixer thread has exited, it's state queue is still valid.
2364 // We'll use that extract the final state which contains one remaining fast track
2365 // corresponding to our sub-mix.
2366 state = sq->begin();
2367 ALOG_ASSERT(state->mTrackMask == 1);
2368 FastTrack *fastTrack = &state->mFastTracks[0];
2369 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2370 delete fastTrack->mBufferProvider;
2371 sq->end(false /*didModify*/);
2372 delete mFastMixer;
Glenn Kastenc15d6652012-05-30 14:52:57 -07002373 if (mAudioWatchdog != 0) {
2374 mAudioWatchdog->requestExit();
2375 mAudioWatchdog->requestExitAndWait();
2376 mAudioWatchdog.clear();
2377 }
Glenn Kasten58912562012-04-03 10:45:00 -07002378 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002379 delete mAudioMixer;
2380}
2381
Glenn Kasten83efdd02012-02-24 07:21:32 -08002382class CpuStats {
2383public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002384 CpuStats();
2385 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002386#ifdef DEBUG_CPU_USAGE
2387private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002388 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2389 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2390
2391 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2392
2393 int mCpuNum; // thread's current CPU number
2394 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002395#endif
2396};
2397
Glenn Kasten190a46f2012-03-06 11:27:10 -08002398CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002399#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002400 : mCpuNum(-1), mCpukHz(-1)
2401#endif
2402{
2403}
2404
2405void CpuStats::sample(const String8 &title) {
2406#ifdef DEBUG_CPU_USAGE
2407 // get current thread's delta CPU time in wall clock ns
2408 double wcNs;
2409 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2410
2411 // record sample for wall clock statistics
2412 if (valid) {
2413 mWcStats.sample(wcNs);
2414 }
2415
2416 // get the current CPU number
2417 int cpuNum = sched_getcpu();
2418
2419 // get the current CPU frequency in kHz
2420 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2421
2422 // check if either CPU number or frequency changed
2423 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2424 mCpuNum = cpuNum;
2425 mCpukHz = cpukHz;
2426 // ignore sample for purposes of cycles
2427 valid = false;
2428 }
2429
2430 // if no change in CPU number or frequency, then record sample for cycle statistics
2431 if (valid && mCpukHz > 0) {
2432 double cycles = wcNs * cpukHz * 0.000001;
2433 mHzStats.sample(cycles);
2434 }
2435
2436 unsigned n = mWcStats.n();
2437 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002438 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002439 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002440 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2441 double perLoop = elapsed / (double) n;
2442 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002443 double perLoop1k = perLoop * 0.001;
2444 double mean = mWcStats.mean();
2445 double stddev = mWcStats.stddev();
2446 double minimum = mWcStats.minimum();
2447 double maximum = mWcStats.maximum();
2448 double meanCycles = mHzStats.mean();
2449 double stddevCycles = mHzStats.stddev();
2450 double minCycles = mHzStats.minimum();
2451 double maxCycles = mHzStats.maximum();
2452 mCpuUsage.resetElapsed();
2453 mWcStats.reset();
2454 mHzStats.reset();
2455 ALOGD("CPU usage for %s over past %.1f secs\n"
2456 " (%u mixer loops at %.1f mean ms per loop):\n"
2457 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2458 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2459 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2460 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002461 elapsed * .000000001, n, perLoop * .000001,
2462 mean * .001,
2463 stddev * .001,
2464 minimum * .001,
2465 maximum * .001,
2466 mean / perLoop100,
2467 stddev / perLoop100,
2468 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002469 maximum / perLoop100,
2470 meanCycles / perLoop1k,
2471 stddevCycles / perLoop1k,
2472 minCycles / perLoop1k,
2473 maxCycles / perLoop1k);
2474
Glenn Kasten83efdd02012-02-24 07:21:32 -08002475 }
2476 }
2477#endif
2478};
2479
Glenn Kasten37d825e2012-02-24 07:21:48 -08002480void AudioFlinger::PlaybackThread::checkSilentMode_l()
2481{
2482 if (!mMasterMute) {
2483 char value[PROPERTY_VALUE_MAX];
2484 if (property_get("ro.audio.silent", value, "0") > 0) {
2485 char *endptr;
2486 unsigned long ul = strtoul(value, &endptr, 0);
2487 if (*endptr == '\0' && ul != 0) {
2488 ALOGD("Silence is golden");
2489 // The setprop command will not allow a property to be changed after
2490 // the first time it is set, so we don't have to worry about un-muting.
2491 setMasterMute_l(true);
2492 }
2493 }
2494 }
2495}
2496
Glenn Kasten000f0e32012-03-01 17:10:56 -08002497bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002498{
2499 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002500
Glenn Kasten000f0e32012-03-01 17:10:56 -08002501 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002502
2503 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002505
Glenn Kasten000f0e32012-03-01 17:10:56 -08002506 // DUPLICATING
2507 // FIXME could this be made local to while loop?
2508 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002509
Glenn Kasten66fcab92012-02-24 14:59:21 -08002510 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002511 sleepTime = idleSleepTime;
2512
Glenn Kasten9f34a362012-03-20 16:46:41 -07002513 if (mType == MIXER) {
2514 sleepTimeShift = 0;
2515 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002516
Glenn Kasten83efdd02012-02-24 07:21:32 -08002517 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002518 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002519
Eric Laurentfeb0db62011-07-22 09:04:31 -07002520 acquireWakeLock();
2521
Mathias Agopian65ab4712010-07-14 17:59:35 -07002522 while (!exitPending())
2523 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002524 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002525
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002526 Vector< sp<EffectChain> > effectChains;
2527
Mathias Agopian65ab4712010-07-14 17:59:35 -07002528 processConfigEvents();
2529
Mathias Agopian65ab4712010-07-14 17:59:35 -07002530 { // scope for mLock
2531
2532 Mutex::Autolock _l(mLock);
2533
2534 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002535 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002536 }
2537
Glenn Kastenfa26a852012-03-06 11:28:04 -08002538 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002539
Mathias Agopian65ab4712010-07-14 17:59:35 -07002540 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002541 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002542 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002544
2545 threadLoop_standby();
2546
Mathias Agopian65ab4712010-07-14 17:59:35 -07002547 mStandby = true;
2548 mBytesWritten = 0;
2549 }
2550
Glenn Kasten3e074702012-02-28 18:40:35 -08002551 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002552 // we're about to wait, flush the binder command buffer
2553 IPCThreadState::self()->flushCommands();
2554
Glenn Kastenfa26a852012-03-06 11:28:04 -08002555 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002556
Mathias Agopian65ab4712010-07-14 17:59:35 -07002557 if (exitPending()) break;
2558
Eric Laurentfeb0db62011-07-22 09:04:31 -07002559 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002560 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002561 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002562 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002563 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002564 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002565
Eric Laurentda747442012-04-25 18:53:13 -07002566 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002567 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002568
Glenn Kasten37d825e2012-02-24 07:21:48 -08002569 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002570
Glenn Kasten000f0e32012-03-01 17:10:56 -08002571 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002572 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002573 if (mType == MIXER) {
2574 sleepTimeShift = 0;
2575 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002576
Mathias Agopian65ab4712010-07-14 17:59:35 -07002577 continue;
2578 }
2579 }
2580
Glenn Kasten81028042012-04-30 18:15:12 -07002581 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002582 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002583
2584 // prevent any changes in effect chain list and in each effect chain
2585 // during mixing and effect process as the audio buffers could be deleted
2586 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002587 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002588 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002589
Glenn Kastenfec279f2012-03-08 07:47:15 -08002590 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002591 threadLoop_mix();
2592 } else {
2593 threadLoop_sleepTime();
2594 }
2595
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002596 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002597 sleepTime = suspendSleepTimeUs();
2598 }
2599
2600 // only process effects if we're going to write
2601 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002602 for (size_t i = 0; i < effectChains.size(); i ++) {
2603 effectChains[i]->process_l();
2604 }
2605 }
2606
2607 // enable changes in effect chain
2608 unlockEffectChains(effectChains);
2609
2610 // sleepTime == 0 means we must write to audio hardware
2611 if (sleepTime == 0) {
2612
2613 threadLoop_write();
2614
2615if (mType == MIXER) {
2616 // write blocked detection
2617 nsecs_t now = systemTime();
2618 nsecs_t delta = now - mLastWriteTime;
2619 if (!mStandby && delta > maxPeriod) {
2620 mNumDelayedWrites++;
2621 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002622#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002623 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002624#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002625 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2626 ns2ms(delta), mNumDelayedWrites, this);
2627 lastWarning = now;
2628 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002629 }
2630}
2631
2632 mStandby = false;
2633 } else {
2634 usleep(sleepTime);
2635 }
2636
Glenn Kasten58912562012-04-03 10:45:00 -07002637 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002638 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002639 // same lock. This will also mutate and push a new fast mixer state.
2640 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002641 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002642
Glenn Kastenfa26a852012-03-06 11:28:04 -08002643 // FIXME I don't understand the need for this here;
2644 // it was in the original code but maybe the
2645 // assignment in saveOutputTracks() makes this unnecessary?
2646 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002647
2648 // Effect chains will be actually deleted here if they were removed from
2649 // mEffectChains list during mixing or effects processing
2650 effectChains.clear();
2651
2652 // FIXME Note that the above .clear() is no longer necessary since effectChains
2653 // is now local to this block, but will keep it for now (at least until merge done).
2654 }
2655
Glenn Kasten9f34a362012-03-20 16:46:41 -07002656 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2657 if (mType == MIXER || mType == DIRECT) {
2658 // put output stream into standby mode
2659 if (!mStandby) {
2660 mOutput->stream->common.standby(&mOutput->stream->common);
2661 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002662 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002663
2664 releaseWakeLock();
2665
2666 ALOGV("Thread %p type %d exiting", this, mType);
2667 return false;
2668}
2669
Glenn Kasten58912562012-04-03 10:45:00 -07002670void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2671{
Glenn Kasten58912562012-04-03 10:45:00 -07002672 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2673}
2674
2675void AudioFlinger::MixerThread::threadLoop_write()
2676{
2677 // FIXME we should only do one push per cycle; confirm this is true
2678 // Start the fast mixer if it's not already running
2679 if (mFastMixer != NULL) {
2680 FastMixerStateQueue *sq = mFastMixer->sq();
2681 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002682 if (state->mCommand != FastMixerState::MIX_WRITE &&
2683 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002684 if (state->mCommand == FastMixerState::COLD_IDLE) {
2685 int32_t old = android_atomic_inc(&mFastMixerFutex);
2686 if (old == -1) {
2687 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2688 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002689 if (mAudioWatchdog != 0) {
2690 mAudioWatchdog->resume();
2691 }
Glenn Kasten58912562012-04-03 10:45:00 -07002692 }
2693 state->mCommand = FastMixerState::MIX_WRITE;
2694 sq->end();
2695 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002696 if (kUseFastMixer == FastMixer_Dynamic) {
2697 mNormalSink = mPipeSink;
2698 }
Glenn Kasten58912562012-04-03 10:45:00 -07002699 } else {
2700 sq->end(false /*didModify*/);
2701 }
2702 }
2703 PlaybackThread::threadLoop_write();
2704}
2705
Glenn Kasten000f0e32012-03-01 17:10:56 -08002706// shared by MIXER and DIRECT, overridden by DUPLICATING
2707void AudioFlinger::PlaybackThread::threadLoop_write()
2708{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002709 // FIXME rewrite to reduce number of system calls
2710 mLastWriteTime = systemTime();
2711 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002712 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002713
Eric Laurent67c0a582012-05-01 19:31:12 -07002714 // If an NBAIO sink is present, use it to write the normal mixer's submix
2715 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002716#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002717 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002718#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002719 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002720#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002721 // update the setpoint when gScreenState changes
2722 uint32_t screenState = gScreenState;
2723 if (screenState != mScreenState) {
2724 mScreenState = screenState;
2725 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2726 if (pipe != NULL) {
2727 pipe->setAvgFrames((mScreenState & 1) ?
2728 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2729 }
2730 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002731 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002732#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002733 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002734#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002735 if (framesWritten > 0) {
2736 bytesWritten = framesWritten << mBitShift;
2737 } else {
2738 bytesWritten = framesWritten;
2739 }
2740 // otherwise use the HAL / AudioStreamOut directly
2741 } else {
2742 // Direct output thread.
2743 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002744 }
2745
Eric Laurent67c0a582012-05-01 19:31:12 -07002746 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002747 mNumWrites++;
2748 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002749}
2750
Glenn Kasten58912562012-04-03 10:45:00 -07002751void AudioFlinger::MixerThread::threadLoop_standby()
2752{
2753 // Idle the fast mixer if it's currently running
2754 if (mFastMixer != NULL) {
2755 FastMixerStateQueue *sq = mFastMixer->sq();
2756 FastMixerState *state = sq->begin();
2757 if (!(state->mCommand & FastMixerState::IDLE)) {
2758 state->mCommand = FastMixerState::COLD_IDLE;
2759 state->mColdFutexAddr = &mFastMixerFutex;
2760 state->mColdGen++;
2761 mFastMixerFutex = 0;
2762 sq->end();
2763 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2764 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002765 if (kUseFastMixer == FastMixer_Dynamic) {
2766 mNormalSink = mOutputSink;
2767 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002768 if (mAudioWatchdog != 0) {
2769 mAudioWatchdog->pause();
2770 }
Glenn Kasten58912562012-04-03 10:45:00 -07002771 } else {
2772 sq->end(false /*didModify*/);
2773 }
2774 }
2775 PlaybackThread::threadLoop_standby();
2776}
2777
Glenn Kasten000f0e32012-03-01 17:10:56 -08002778// shared by MIXER and DIRECT, overridden by DUPLICATING
2779void AudioFlinger::PlaybackThread::threadLoop_standby()
2780{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002781 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002782 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002783}
2784
2785void AudioFlinger::MixerThread::threadLoop_mix()
2786{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002787 // obtain the presentation timestamp of the next output buffer
2788 int64_t pts;
2789 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002790
Glenn Kasten952eeb22012-03-06 11:30:57 -08002791 if (NULL != mOutput->stream->get_next_write_timestamp) {
2792 status = mOutput->stream->get_next_write_timestamp(
2793 mOutput->stream, &pts);
2794 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002795
Glenn Kasten952eeb22012-03-06 11:30:57 -08002796 if (status != NO_ERROR) {
2797 pts = AudioBufferProvider::kInvalidPTS;
2798 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002799
Glenn Kasten952eeb22012-03-06 11:30:57 -08002800 // mix buffers...
2801 mAudioMixer->process(pts);
2802 // increase sleep time progressively when application underrun condition clears.
2803 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2804 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2805 // such that we would underrun the audio HAL.
2806 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2807 sleepTimeShift--;
2808 }
2809 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002810 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002811 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002812}
2813
2814void AudioFlinger::MixerThread::threadLoop_sleepTime()
2815{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002816 // If no tracks are ready, sleep once for the duration of an output
2817 // buffer size, then write 0s to the output
2818 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002819 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002820 sleepTime = activeSleepTime >> sleepTimeShift;
2821 if (sleepTime < kMinThreadSleepTimeUs) {
2822 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002823 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002824 // reduce sleep time in case of consecutive application underruns to avoid
2825 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2826 // duration we would end up writing less data than needed by the audio HAL if
2827 // the condition persists.
2828 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2829 sleepTimeShift++;
2830 }
2831 } else {
2832 sleepTime = idleSleepTime;
2833 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002834 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002835 memset (mMixBuffer, 0, mixBufferSize);
2836 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002837 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002838 }
2839 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002840}
2841
2842// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002843AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002844 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002845{
2846
Glenn Kasten29c23c32012-01-26 13:37:52 -08002847 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002848 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002849 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002850 size_t mixedTracks = 0;
2851 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002852 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002853 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002854 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002855
2856 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002857 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002858
Eric Laurent571d49c2010-08-11 05:20:11 -07002859 if (masterMute) {
2860 masterVolume = 0;
2861 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002862 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002863 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002864 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002865 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002866 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002867 masterVolume = (float)((v + (1 << 23)) >> 24);
2868 chain.clear();
2869 }
2870
Glenn Kasten288ed212012-04-25 17:52:27 -07002871 // prepare a new state to push
2872 FastMixerStateQueue *sq = NULL;
2873 FastMixerState *state = NULL;
2874 bool didModify = false;
2875 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2876 if (mFastMixer != NULL) {
2877 sq = mFastMixer->sq();
2878 state = sq->begin();
2879 }
2880
Mathias Agopian65ab4712010-07-14 17:59:35 -07002881 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002882 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002883 if (t == 0) continue;
2884
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002885 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002886 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002887
Glenn Kasten288ed212012-04-25 17:52:27 -07002888 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002889 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002890
2891 // It's theoretically possible (though unlikely) for a fast track to be created
2892 // and then removed within the same normal mix cycle. This is not a problem, as
2893 // the track never becomes active so it's fast mixer slot is never touched.
2894 // The converse, of removing an (active) track and then creating a new track
2895 // at the identical fast mixer slot within the same normal mix cycle,
2896 // is impossible because the slot isn't marked available until the end of each cycle.
2897 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002898 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2899 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002900 FastTrack *fastTrack = &state->mFastTracks[j];
2901
2902 // Determine whether the track is currently in underrun condition,
2903 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002904 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2905 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002906 uint32_t recentFull = (underruns.mBitFields.mFull -
2907 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2908 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2909 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2910 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2911 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2912 uint32_t recentUnderruns = recentPartial + recentEmpty;
2913 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002914 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002915 // or stopped which can occur when flush() is called while active
2916 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002917 track->mUnderrunCount += recentUnderruns;
2918 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002919
Glenn Kastend08f48c2012-05-01 18:14:02 -07002920 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002921 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002922 bool isActive = true;
2923 switch (track->mState) {
2924 case TrackBase::STOPPING_1:
2925 // track stays active in STOPPING_1 state until first underrun
2926 if (recentUnderruns > 0) {
2927 track->mState = TrackBase::STOPPING_2;
2928 }
2929 break;
2930 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002931 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002932 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002933 break;
2934 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002935 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002936 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002937 break;
2938 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002939 if (recentFull > 0 || recentPartial > 0) {
2940 // track has provided at least some frames recently: reset retry count
2941 track->mRetryCount = kMaxTrackRetries;
2942 }
2943 if (recentUnderruns == 0) {
2944 // no recent underruns: stay active
2945 break;
2946 }
2947 // there has recently been an underrun of some kind
2948 if (track->sharedBuffer() == 0) {
2949 // were any of the recent underruns "empty" (no frames available)?
2950 if (recentEmpty == 0) {
2951 // no, then ignore the partial underruns as they are allowed indefinitely
2952 break;
2953 }
2954 // there has recently been an "empty" underrun: decrement the retry counter
2955 if (--(track->mRetryCount) > 0) {
2956 break;
2957 }
2958 // indicate to client process that the track was disabled because of underrun;
2959 // it will then automatically call start() when data is available
2960 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2961 // remove from active list, but state remains ACTIVE [confusing but true]
2962 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002963 break;
2964 }
2965 // fall through
2966 case TrackBase::STOPPING_2:
2967 case TrackBase::PAUSED:
2968 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002969 case TrackBase::STOPPED:
2970 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002971 // Check for presentation complete if track is inactive
2972 // We have consumed all the buffers of this track.
2973 // This would be incomplete if we auto-paused on underrun
2974 {
2975 size_t audioHALFrames =
2976 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2977 size_t framesWritten =
2978 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2979 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2980 // track stays in active list until presentation is complete
2981 break;
2982 }
2983 }
2984 if (track->isStopping_2()) {
2985 track->mState = TrackBase::STOPPED;
2986 }
2987 if (track->isStopped()) {
2988 // Can't reset directly, as fast mixer is still polling this track
2989 // track->reset();
2990 // So instead mark this track as needing to be reset after push with ack
2991 resetMask |= 1 << i;
2992 }
2993 isActive = false;
2994 break;
2995 case TrackBase::IDLE:
2996 default:
2997 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07002998 }
2999
3000 if (isActive) {
3001 // was it previously inactive?
3002 if (!(state->mTrackMask & (1 << j))) {
3003 ExtendedAudioBufferProvider *eabp = track;
3004 VolumeProvider *vp = track;
3005 fastTrack->mBufferProvider = eabp;
3006 fastTrack->mVolumeProvider = vp;
3007 fastTrack->mSampleRate = track->mSampleRate;
3008 fastTrack->mChannelMask = track->mChannelMask;
3009 fastTrack->mGeneration++;
3010 state->mTrackMask |= 1 << j;
3011 didModify = true;
3012 // no acknowledgement required for newly active tracks
3013 }
3014 // cache the combined master volume and stream type volume for fast mixer; this
3015 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3016 track->mCachedVolume = track->isMuted() ?
3017 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3018 ++fastTracks;
3019 } else {
3020 // was it previously active?
3021 if (state->mTrackMask & (1 << j)) {
3022 fastTrack->mBufferProvider = NULL;
3023 fastTrack->mGeneration++;
3024 state->mTrackMask &= ~(1 << j);
3025 didModify = true;
3026 // If any fast tracks were removed, we must wait for acknowledgement
3027 // because we're about to decrement the last sp<> on those tracks.
3028 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003029 } else {
3030 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003031 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003032 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003033 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003034 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003035 }
3036 continue;
3037 }
3038
3039 { // local variable scope to avoid goto warning
3040
Mathias Agopian65ab4712010-07-14 17:59:35 -07003041 audio_track_cblk_t* cblk = track->cblk();
3042
3043 // The first time a track is added we wait
3044 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003045 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003046 // make sure that we have enough frames to mix one full buffer.
3047 // enforce this condition only once to enable draining the buffer in case the client
3048 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003049 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003050 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003051 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003052 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003053 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003054 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003055 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003056 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003057 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003058 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003059 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003060 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003061 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3062 // the minimum track buffer size is normally twice the number of frames necessary
3063 // to fill one buffer and the resampler should not leave more than one buffer worth
3064 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003065 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003066 }
3067 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003068 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003069 !track->isPaused() && !track->isTerminated())
3070 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003071 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003072
3073 mixedTracks++;
3074
3075 // track->mainBuffer() != mMixBuffer means there is an effect chain
3076 // connected to the track
3077 chain.clear();
3078 if (track->mainBuffer() != mMixBuffer) {
3079 chain = getEffectChain_l(track->sessionId());
3080 // Delegate volume control to effect in track effect chain if needed
3081 if (chain != 0) {
3082 tracksWithEffect++;
3083 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003084 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003085 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003086 }
3087 }
3088
3089
3090 int param = AudioMixer::VOLUME;
3091 if (track->mFillingUpStatus == Track::FS_FILLED) {
3092 // no ramp for the first volume setting
3093 track->mFillingUpStatus = Track::FS_ACTIVE;
3094 if (track->mState == TrackBase::RESUMING) {
3095 track->mState = TrackBase::ACTIVE;
3096 param = AudioMixer::RAMP_VOLUME;
3097 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003098 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003099 } else if (cblk->server != 0) {
3100 // If the track is stopped before the first frame was mixed,
3101 // do not apply ramp
3102 param = AudioMixer::RAMP_VOLUME;
3103 }
3104
3105 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003106 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003107 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003108 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003109 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003110 if (track->isPausing()) {
3111 track->setPaused();
3112 }
3113 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003114
Mathias Agopian65ab4712010-07-14 17:59:35 -07003115 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003116 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003117 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003118 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003119 vl = vlr & 0xFFFF;
3120 vr = vlr >> 16;
3121 // track volumes come from shared memory, so can't be trusted and must be clamped
3122 if (vl > MAX_GAIN_INT) {
3123 ALOGV("Track left volume out of range: %04X", vl);
3124 vl = MAX_GAIN_INT;
3125 }
3126 if (vr > MAX_GAIN_INT) {
3127 ALOGV("Track right volume out of range: %04X", vr);
3128 vr = MAX_GAIN_INT;
3129 }
3130 // now apply the master volume and stream type volume
3131 vl = (uint32_t)(v * vl) << 12;
3132 vr = (uint32_t)(v * vr) << 12;
3133 // assuming master volume and stream type volume each go up to 1.0,
3134 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003135
Glenn Kasten05632a52012-01-03 14:22:33 -08003136 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3137 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003138 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003139 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003140 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003141 }
3142 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003143 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003144 // Delegate volume control to effect in track effect chain if needed
3145 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3146 // Do not ramp volume if volume is controlled by effect
3147 param = AudioMixer::VOLUME;
3148 track->mHasVolumeController = true;
3149 } else {
3150 // force no volume ramp when volume controller was just disabled or removed
3151 // from effect chain to avoid volume spike
3152 if (track->mHasVolumeController) {
3153 param = AudioMixer::VOLUME;
3154 }
3155 track->mHasVolumeController = false;
3156 }
3157
3158 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003159 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003160 vl = (vl + (1 << 11)) >> 12;
3161 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3162 vr = (vr + (1 << 11)) >> 12;
3163 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003164
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003165 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 -07003166
Mathias Agopian65ab4712010-07-14 17:59:35 -07003167 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003168 mAudioMixer->setBufferProvider(name, track);
3169 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003170
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003171 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3172 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3173 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003174 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003175 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003176 AudioMixer::TRACK,
3177 AudioMixer::FORMAT, (void *)track->format());
3178 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003179 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003180 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003181 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003182 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003183 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 AudioMixer::RESAMPLE,
3185 AudioMixer::SAMPLE_RATE,
3186 (void *)(cblk->sampleRate));
3187 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003188 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003189 AudioMixer::TRACK,
3190 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3191 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003192 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003193 AudioMixer::TRACK,
3194 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3195
3196 // reset retry count
3197 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003198
Eric Laurent27741442012-01-17 19:20:12 -08003199 // If one track is ready, set the mixer ready if:
3200 // - the mixer was not ready during previous round OR
3201 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003202 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003203 mixerStatus != MIXER_TRACKS_ENABLED) {
3204 mixerStatus = MIXER_TRACKS_READY;
3205 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003206 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003207 // clear effect chain input buffer if an active track underruns to avoid sending
3208 // previous audio buffer again to effects
3209 chain = getEffectChain_l(track->sessionId());
3210 if (chain != 0) {
3211 chain->clearInputBuffer();
3212 }
3213
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003214 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Eric Laurent83faee02012-04-27 18:24:29 -07003215 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3216 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003217 // We have consumed all the buffers of this track.
3218 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003219 // TODO: use actual buffer filling status instead of latency when available from
3220 // audio HAL
3221 size_t audioHALFrames =
3222 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3223 size_t framesWritten =
3224 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3225 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003226 if (track->isStopped()) {
3227 track->reset();
3228 }
Eric Laurenta011e352012-03-29 15:51:43 -07003229 tracksToRemove->add(track);
3230 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003231 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003232 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003233 // No buffers for this track. Give it a few chances to
3234 // fill a buffer, then remove it from active list.
3235 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003236 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003237 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003238 // indicate to client process that the track was disabled because of underrun;
3239 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003240 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003241 // If one track is not ready, mark the mixer also not ready if:
3242 // - the mixer was ready during previous round OR
3243 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003244 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003245 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003246 mixerStatus = MIXER_TRACKS_ENABLED;
3247 }
3248 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003249 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003250 }
Glenn Kasten58912562012-04-03 10:45:00 -07003251
3252 } // local variable scope to avoid goto warning
3253track_is_ready: ;
3254
Mathias Agopian65ab4712010-07-14 17:59:35 -07003255 }
3256
Glenn Kasten288ed212012-04-25 17:52:27 -07003257 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003258 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003259 if (didModify) {
3260 state->mFastTracksGen++;
3261 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3262 if (kUseFastMixer == FastMixer_Dynamic &&
3263 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3264 state->mCommand = FastMixerState::COLD_IDLE;
3265 state->mColdFutexAddr = &mFastMixerFutex;
3266 state->mColdGen++;
3267 mFastMixerFutex = 0;
3268 if (kUseFastMixer == FastMixer_Dynamic) {
3269 mNormalSink = mOutputSink;
3270 }
3271 // If we go into cold idle, need to wait for acknowledgement
3272 // so that fast mixer stops doing I/O.
3273 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003274 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003275 }
3276 sq->end();
3277 }
3278 if (sq != NULL) {
3279 sq->end(didModify);
3280 sq->push(block);
3281 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07003282 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3283 mAudioWatchdog->pause();
3284 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003285
3286 // Now perform the deferred reset on fast tracks that have stopped
3287 while (resetMask != 0) {
3288 size_t i = __builtin_ctz(resetMask);
3289 ALOG_ASSERT(i < count);
3290 resetMask &= ~(1 << i);
3291 sp<Track> t = mActiveTracks[i].promote();
3292 if (t == 0) continue;
3293 Track* track = t.get();
3294 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3295 track->reset();
3296 }
Glenn Kasten58912562012-04-03 10:45:00 -07003297
Mathias Agopian65ab4712010-07-14 17:59:35 -07003298 // remove all the tracks that need to be...
3299 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003300 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003301 for (size_t i=0 ; i<count ; i++) {
3302 const sp<Track>& track = tracksToRemove->itemAt(i);
3303 mActiveTracks.remove(track);
3304 if (track->mainBuffer() != mMixBuffer) {
3305 chain = getEffectChain_l(track->sessionId());
3306 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003307 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003308 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003309 }
3310 }
3311 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003312 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003313 }
3314 }
3315 }
3316
3317 // mix buffer must be cleared if all tracks are connected to an
3318 // effect chain as in this case the mixer will not write to
3319 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003320 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3321 // FIXME as a performance optimization, should remember previous zero status
3322 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003323 }
3324
Glenn Kasten58912562012-04-03 10:45:00 -07003325 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003326 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003327 if (fastTracks > 0) {
3328 mixerStatus = MIXER_TRACKS_READY;
3329 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003330 return mixerStatus;
3331}
3332
Glenn Kasten66fcab92012-02-24 14:59:21 -08003333/*
3334The derived values that are cached:
3335 - mixBufferSize from frame count * frame size
3336 - activeSleepTime from activeSleepTimeUs()
3337 - idleSleepTime from idleSleepTimeUs()
3338 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3339 - maxPeriod from frame count and sample rate (MIXER only)
3340
3341The parameters that affect these derived values are:
3342 - frame count
3343 - frame size
3344 - sample rate
3345 - device type: A2DP or not
3346 - device latency
3347 - format: PCM or not
3348 - active sleep time
3349 - idle sleep time
3350*/
3351
3352void AudioFlinger::PlaybackThread::cacheParameters_l()
3353{
Glenn Kasten58912562012-04-03 10:45:00 -07003354 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003355 activeSleepTime = activeSleepTimeUs();
3356 idleSleepTime = idleSleepTimeUs();
3357}
3358
Eric Laurent22167852012-06-20 12:26:32 -07003359void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003360{
Steve Block3856b092011-10-20 11:56:00 +01003361 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003362 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003363 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003364
Mathias Agopian65ab4712010-07-14 17:59:35 -07003365 size_t size = mTracks.size();
3366 for (size_t i = 0; i < size; i++) {
3367 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003368 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003369 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003370 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003371 }
3372 }
3373}
3374
Mathias Agopian65ab4712010-07-14 17:59:35 -07003375// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003376int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003377{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003378 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003379}
3380
3381// deleteTrackName_l() must be called with ThreadBase::mLock held
3382void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3383{
Steve Block3856b092011-10-20 11:56:00 +01003384 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003385 mAudioMixer->deleteTrackName(name);
3386}
3387
3388// checkForNewParameters_l() must be called with ThreadBase::mLock held
3389bool AudioFlinger::MixerThread::checkForNewParameters_l()
3390{
Glenn Kasten58912562012-04-03 10:45:00 -07003391 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3392 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003393 bool reconfig = false;
3394
3395 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003396
3397 if (mFastMixer != NULL) {
3398 FastMixerStateQueue *sq = mFastMixer->sq();
3399 FastMixerState *state = sq->begin();
3400 if (!(state->mCommand & FastMixerState::IDLE)) {
3401 previousCommand = state->mCommand;
3402 state->mCommand = FastMixerState::HOT_IDLE;
3403 sq->end();
3404 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3405 } else {
3406 sq->end(false /*didModify*/);
3407 }
3408 }
3409
Mathias Agopian65ab4712010-07-14 17:59:35 -07003410 status_t status = NO_ERROR;
3411 String8 keyValuePair = mNewParameters[0];
3412 AudioParameter param = AudioParameter(keyValuePair);
3413 int value;
3414
3415 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3416 reconfig = true;
3417 }
3418 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003419 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003420 status = BAD_VALUE;
3421 } else {
3422 reconfig = true;
3423 }
3424 }
3425 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003426 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003427 status = BAD_VALUE;
3428 } else {
3429 reconfig = true;
3430 }
3431 }
3432 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3433 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003434 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003435 // if frame count is changed after track creation
3436 if (!mTracks.isEmpty()) {
3437 status = INVALID_OPERATION;
3438 } else {
3439 reconfig = true;
3440 }
3441 }
3442 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003443#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003444 // when changing the audio output device, call addBatteryData to notify
3445 // the change
Glenn Kasten5ad92f62012-07-19 10:02:15 -07003446 if (mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003447 uint32_t params = 0;
3448 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003449 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003450 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3451 }
3452
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003453 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003454 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003455 // check if any other device (except speaker) is on
3456 if (value & deviceWithoutSpeaker ) {
3457 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3458 }
3459
3460 if (params != 0) {
3461 addBatteryData(params);
3462 }
3463 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003464#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003465
Mathias Agopian65ab4712010-07-14 17:59:35 -07003466 // forward device change to effects that have requested to be
3467 // aware of attached audio device.
Glenn Kasten5ad92f62012-07-19 10:02:15 -07003468 mDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003469 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003470 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003471 }
3472 }
3473
3474 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003475 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003476 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003477 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003478 mOutput->stream->common.standby(&mOutput->stream->common);
3479 mStandby = true;
3480 mBytesWritten = 0;
3481 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003482 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003483 }
3484 if (status == NO_ERROR && reconfig) {
3485 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003486 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3487 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003488 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003489 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003490 for (size_t i = 0; i < mTracks.size() ; i++) {
Glenn Kasten254af182012-07-03 14:59:05 -07003491 int name = getTrackName_l(mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003492 if (name < 0) break;
3493 mTracks[i]->mName = name;
3494 // limit track sample rate to 2 x new output sample rate
3495 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3496 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3497 }
3498 }
3499 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3500 }
3501 }
3502
3503 mNewParameters.removeAt(0);
3504
3505 mParamStatus = status;
3506 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003507 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3508 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003509 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003510 }
Glenn Kasten58912562012-04-03 10:45:00 -07003511
3512 if (!(previousCommand & FastMixerState::IDLE)) {
3513 ALOG_ASSERT(mFastMixer != NULL);
3514 FastMixerStateQueue *sq = mFastMixer->sq();
3515 FastMixerState *state = sq->begin();
3516 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3517 state->mCommand = previousCommand;
3518 sq->end();
3519 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3520 }
3521
Mathias Agopian65ab4712010-07-14 17:59:35 -07003522 return reconfig;
3523}
3524
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07003525void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003526{
3527 const size_t SIZE = 256;
3528 char buffer[SIZE];
3529 String8 result;
3530
3531 PlaybackThread::dumpInternals(fd, args);
3532
3533 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3534 result.append(buffer);
3535 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003536
3537 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3538 FastMixerDumpState copy = mFastMixerDumpState;
3539 copy.dump(fd);
3540
Glenn Kasten39993082012-05-31 13:40:27 -07003541#ifdef STATE_QUEUE_DUMP
3542 // Similar for state queue
3543 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3544 observerCopy.dump(fd);
3545 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3546 mutatorCopy.dump(fd);
3547#endif
3548
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003549 // Write the tee output to a .wav file
3550 NBAIO_Source *teeSource = mTeeSource.get();
3551 if (teeSource != NULL) {
3552 char teePath[64];
3553 struct timeval tv;
3554 gettimeofday(&tv, NULL);
3555 struct tm tm;
3556 localtime_r(&tv.tv_sec, &tm);
3557 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3558 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3559 if (teeFd >= 0) {
3560 char wavHeader[44];
3561 memcpy(wavHeader,
3562 "RIFF\0\0\0\0WAVEfmt \20\0\0\0\1\0\2\0\104\254\0\0\0\0\0\0\4\0\20\0data\0\0\0\0",
3563 sizeof(wavHeader));
3564 NBAIO_Format format = teeSource->format();
3565 unsigned channelCount = Format_channelCount(format);
3566 ALOG_ASSERT(channelCount <= FCC_2);
3567 unsigned sampleRate = Format_sampleRate(format);
3568 wavHeader[22] = channelCount; // number of channels
3569 wavHeader[24] = sampleRate; // sample rate
3570 wavHeader[25] = sampleRate >> 8;
3571 wavHeader[32] = channelCount * 2; // block alignment
3572 write(teeFd, wavHeader, sizeof(wavHeader));
3573 size_t total = 0;
3574 bool firstRead = true;
3575 for (;;) {
3576#define TEE_SINK_READ 1024
3577 short buffer[TEE_SINK_READ * FCC_2];
3578 size_t count = TEE_SINK_READ;
3579 ssize_t actual = teeSource->read(buffer, count);
3580 bool wasFirstRead = firstRead;
3581 firstRead = false;
3582 if (actual <= 0) {
3583 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3584 continue;
3585 }
3586 break;
3587 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003588 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003589 write(teeFd, buffer, actual * channelCount * sizeof(short));
3590 total += actual;
3591 }
3592 lseek(teeFd, (off_t) 4, SEEK_SET);
3593 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3594 write(teeFd, &temp, sizeof(temp));
3595 lseek(teeFd, (off_t) 40, SEEK_SET);
3596 temp = total * channelCount * sizeof(short);
3597 write(teeFd, &temp, sizeof(temp));
3598 close(teeFd);
3599 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3600 } else {
3601 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3602 }
3603 }
3604
Glenn Kastenc15d6652012-05-30 14:52:57 -07003605 if (mAudioWatchdog != 0) {
3606 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3607 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3608 wdCopy.dump(fd);
3609 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003610}
3611
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003612uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003613{
Glenn Kasten58912562012-04-03 10:45:00 -07003614 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003615}
3616
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003617uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003618{
Glenn Kasten58912562012-04-03 10:45:00 -07003619 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003620}
3621
Glenn Kasten66fcab92012-02-24 14:59:21 -08003622void AudioFlinger::MixerThread::cacheParameters_l()
3623{
3624 PlaybackThread::cacheParameters_l();
3625
3626 // FIXME: Relaxed timing because of a certain device that can't meet latency
3627 // Should be reduced to 2x after the vendor fixes the driver issue
3628 // increase threshold again due to low power audio mode. The way this warning
3629 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003630 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003631}
3632
Mathias Agopian65ab4712010-07-14 17:59:35 -07003633// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003634AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003635 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003636 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003637 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003638{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003639}
3640
3641AudioFlinger::DirectOutputThread::~DirectOutputThread()
3642{
3643}
3644
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003645AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3646 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003647)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003648{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003649 sp<Track> trackToRemove;
3650
Glenn Kastenfec279f2012-03-08 07:47:15 -08003651 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003652
Glenn Kasten952eeb22012-03-06 11:30:57 -08003653 // find out which tracks need to be processed
3654 if (mActiveTracks.size() != 0) {
3655 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003656 // The track died recently
3657 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003658
Glenn Kasten952eeb22012-03-06 11:30:57 -08003659 Track* const track = t.get();
3660 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003661
Glenn Kasten952eeb22012-03-06 11:30:57 -08003662 // The first time a track is added we wait
3663 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003664 uint32_t minFrames;
3665 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3666 minFrames = mNormalFrameCount;
3667 } else {
3668 minFrames = 1;
3669 }
3670 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003671 !track->isPaused() && !track->isTerminated())
3672 {
3673 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003674
Glenn Kasten952eeb22012-03-06 11:30:57 -08003675 if (track->mFillingUpStatus == Track::FS_FILLED) {
3676 track->mFillingUpStatus = Track::FS_ACTIVE;
3677 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003678 if (track->mState == TrackBase::RESUMING) {
3679 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003680 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003681 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003682
Glenn Kasten952eeb22012-03-06 11:30:57 -08003683 // compute volume for this track
3684 float left, right;
3685 if (track->isMuted() || mMasterMute || track->isPausing() ||
3686 mStreamTypes[track->streamType()].mute) {
3687 left = right = 0;
3688 if (track->isPausing()) {
3689 track->setPaused();
3690 }
3691 } else {
3692 float typeVolume = mStreamTypes[track->streamType()].volume;
3693 float v = mMasterVolume * typeVolume;
3694 uint32_t vlr = cblk->getVolumeLR();
3695 float v_clamped = v * (vlr & 0xFFFF);
3696 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3697 left = v_clamped/MAX_GAIN;
3698 v_clamped = v * (vlr >> 16);
3699 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3700 right = v_clamped/MAX_GAIN;
3701 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003702
Glenn Kasten952eeb22012-03-06 11:30:57 -08003703 if (left != mLeftVolFloat || right != mRightVolFloat) {
3704 mLeftVolFloat = left;
3705 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003706
Glenn Kasten952eeb22012-03-06 11:30:57 -08003707 // Convert volumes from float to 8.24
3708 uint32_t vl = (uint32_t)(left * (1 << 24));
3709 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003710
Glenn Kasten952eeb22012-03-06 11:30:57 -08003711 // Delegate volume control to effect in track effect chain if needed
3712 // only one effect chain can be present on DirectOutputThread, so if
3713 // there is one, the track is connected to it
3714 if (!mEffectChains.isEmpty()) {
3715 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003716 mEffectChains[0]->setVolume_l(&vl, &vr);
3717 left = (float)vl / (1 << 24);
3718 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003719 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003720 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003721 }
3722
3723 // reset retry count
3724 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003725 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003726 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003727 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003728 // clear effect chain input buffer if an active track underruns to avoid sending
3729 // previous audio buffer again to effects
3730 if (!mEffectChains.isEmpty()) {
3731 mEffectChains[0]->clearInputBuffer();
3732 }
3733
Glenn Kasten952eeb22012-03-06 11:30:57 -08003734 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Eric Laurent67c0a582012-05-01 19:31:12 -07003735 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
3736 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003737 // We have consumed all the buffers of this track.
3738 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003739 // TODO: implement behavior for compressed audio
3740 size_t audioHALFrames =
3741 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3742 size_t framesWritten =
3743 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3744 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003745 if (track->isStopped()) {
3746 track->reset();
3747 }
Eric Laurenta011e352012-03-29 15:51:43 -07003748 trackToRemove = track;
3749 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003750 } else {
3751 // No buffers for this track. Give it a few chances to
3752 // fill a buffer, then remove it from active list.
3753 if (--(track->mRetryCount) <= 0) {
3754 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
3755 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003756 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003757 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003758 }
3759 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003760 }
3761 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003762
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003763 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003764 // remove all the tracks that need to be...
3765 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003766 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003767 mActiveTracks.remove(trackToRemove);
3768 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003769 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003770 trackToRemove->sessionId());
3771 mEffectChains[0]->decActiveTrackCnt();
3772 }
3773 if (trackToRemove->isTerminated()) {
3774 removeTrack_l(trackToRemove);
3775 }
3776 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003777
Glenn Kastenfec279f2012-03-08 07:47:15 -08003778 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003779}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003780
Glenn Kasten000f0e32012-03-01 17:10:56 -08003781void AudioFlinger::DirectOutputThread::threadLoop_mix()
3782{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003783 AudioBufferProvider::Buffer buffer;
3784 size_t frameCount = mFrameCount;
3785 int8_t *curBuf = (int8_t *)mMixBuffer;
3786 // output audio to hardware
3787 while (frameCount) {
3788 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003789 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003790 if (CC_UNLIKELY(buffer.raw == NULL)) {
3791 memset(curBuf, 0, frameCount * mFrameSize);
3792 break;
3793 }
3794 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3795 frameCount -= buffer.frameCount;
3796 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003797 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003798 }
3799 sleepTime = 0;
3800 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003801 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003802
Glenn Kasten000f0e32012-03-01 17:10:56 -08003803}
3804
3805void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3806{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003807 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003808 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003809 sleepTime = activeSleepTime;
3810 } else {
3811 sleepTime = idleSleepTime;
3812 }
3813 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003814 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003815 sleepTime = 0;
3816 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003817}
3818
3819// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003820int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003821{
3822 return 0;
3823}
3824
3825// deleteTrackName_l() must be called with ThreadBase::mLock held
3826void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3827{
3828}
3829
3830// checkForNewParameters_l() must be called with ThreadBase::mLock held
3831bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3832{
3833 bool reconfig = false;
3834
3835 while (!mNewParameters.isEmpty()) {
3836 status_t status = NO_ERROR;
3837 String8 keyValuePair = mNewParameters[0];
3838 AudioParameter param = AudioParameter(keyValuePair);
3839 int value;
3840
3841 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3842 // do not accept frame count changes if tracks are open as the track buffer
3843 // size depends on frame count and correct behavior would not be garantied
3844 // if frame count is changed after track creation
3845 if (!mTracks.isEmpty()) {
3846 status = INVALID_OPERATION;
3847 } else {
3848 reconfig = true;
3849 }
3850 }
3851 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003852 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003853 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003854 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003855 mOutput->stream->common.standby(&mOutput->stream->common);
3856 mStandby = true;
3857 mBytesWritten = 0;
3858 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003859 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003860 }
3861 if (status == NO_ERROR && reconfig) {
3862 readOutputParameters();
3863 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3864 }
3865 }
3866
3867 mNewParameters.removeAt(0);
3868
3869 mParamStatus = status;
3870 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003871 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3872 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003873 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003874 }
3875 return reconfig;
3876}
3877
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003878uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003879{
3880 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003881 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003882 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003883 } else {
3884 time = 10000;
3885 }
3886 return time;
3887}
3888
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003889uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003890{
3891 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003892 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003893 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003894 } else {
3895 time = 10000;
3896 }
3897 return time;
3898}
3899
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003900uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003901{
3902 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003903 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003904 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3905 } else {
3906 time = 10000;
3907 }
3908 return time;
3909}
3910
Glenn Kasten66fcab92012-02-24 14:59:21 -08003911void AudioFlinger::DirectOutputThread::cacheParameters_l()
3912{
3913 PlaybackThread::cacheParameters_l();
3914
3915 // use shorter standby delay as on normal output to release
3916 // hardware resources as soon as possible
3917 standbyDelay = microseconds(activeSleepTime*2);
3918}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003919
Mathias Agopian65ab4712010-07-14 17:59:35 -07003920// ----------------------------------------------------------------------------
3921
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003922AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003923 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003924 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3925 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003926{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003927 addOutputTrack(mainThread);
3928}
3929
3930AudioFlinger::DuplicatingThread::~DuplicatingThread()
3931{
3932 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3933 mOutputTracks[i]->destroy();
3934 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003935}
3936
Glenn Kasten000f0e32012-03-01 17:10:56 -08003937void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003938{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003939 // mix buffers...
3940 if (outputsReady(outputTracks)) {
3941 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3942 } else {
3943 memset(mMixBuffer, 0, mixBufferSize);
3944 }
3945 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003946 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003947 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003948}
3949
3950void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3951{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003952 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003953 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003954 sleepTime = activeSleepTime;
3955 } else {
3956 sleepTime = idleSleepTime;
3957 }
3958 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003959 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3960 writeFrames = mNormalFrameCount;
3961 memset(mMixBuffer, 0, mixBufferSize);
3962 } else {
3963 // flush remaining overflow buffers in output tracks
3964 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003965 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003966 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003967 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003968}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003969
Glenn Kasten000f0e32012-03-01 17:10:56 -08003970void AudioFlinger::DuplicatingThread::threadLoop_write()
3971{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003972 for (size_t i = 0; i < outputTracks.size(); i++) {
3973 outputTracks[i]->write(mMixBuffer, writeFrames);
3974 }
3975 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003976}
Glenn Kasten688a6402012-02-29 07:57:06 -08003977
Glenn Kasten000f0e32012-03-01 17:10:56 -08003978void AudioFlinger::DuplicatingThread::threadLoop_standby()
3979{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003980 // DuplicatingThread implements standby by stopping all tracks
3981 for (size_t i = 0; i < outputTracks.size(); i++) {
3982 outputTracks[i]->stop();
3983 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003984}
3985
Glenn Kastenfa26a852012-03-06 11:28:04 -08003986void AudioFlinger::DuplicatingThread::saveOutputTracks()
3987{
3988 outputTracks = mOutputTracks;
3989}
3990
3991void AudioFlinger::DuplicatingThread::clearOutputTracks()
3992{
3993 outputTracks.clear();
3994}
3995
Mathias Agopian65ab4712010-07-14 17:59:35 -07003996void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3997{
Glenn Kastenb6b74062012-02-24 14:12:20 -08003998 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08003999 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004000 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004001 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004002 this,
4003 mSampleRate,
4004 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004005 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004006 frameCount);
4007 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004008 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004009 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004010 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004011 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004012 }
4013}
4014
4015void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4016{
4017 Mutex::Autolock _l(mLock);
4018 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004019 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004020 mOutputTracks[i]->destroy();
4021 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004022 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004023 return;
4024 }
4025 }
Steve Block3856b092011-10-20 11:56:00 +01004026 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004027}
4028
Glenn Kasten438b0362012-03-06 11:24:48 -08004029// caller must hold mLock
4030void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004031{
4032 mWaitTimeMs = UINT_MAX;
4033 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4034 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004035 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004036 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4037 if (waitTimeMs < mWaitTimeMs) {
4038 mWaitTimeMs = waitTimeMs;
4039 }
4040 }
4041 }
4042}
4043
4044
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004045bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004046{
4047 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004048 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004049 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004050 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004051 return false;
4052 }
4053 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004054 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004055 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004056 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004057 return false;
4058 }
4059 }
4060 return true;
4061}
4062
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004063uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004064{
4065 return (mWaitTimeMs * 1000) / 2;
4066}
4067
Glenn Kasten66fcab92012-02-24 14:59:21 -08004068void AudioFlinger::DuplicatingThread::cacheParameters_l()
4069{
4070 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4071 updateWaitTime_l();
4072
4073 MixerThread::cacheParameters_l();
4074}
4075
Mathias Agopian65ab4712010-07-14 17:59:35 -07004076// ----------------------------------------------------------------------------
4077
4078// TrackBase constructor must be called with AudioFlinger::mLock held
4079AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004080 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004081 const sp<Client>& client,
4082 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004083 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004084 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004085 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004086 const sp<IMemory>& sharedBuffer,
4087 int sessionId)
4088 : RefBase(),
4089 mThread(thread),
4090 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004091 mCblk(NULL),
4092 // mBuffer
4093 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004094 mFrameCount(0),
4095 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004096 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004097 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004098 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004099 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004100 // mChannelCount
4101 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004102{
Steve Block3856b092011-10-20 11:56:00 +01004103 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004104
Steve Blockb8a80522011-12-20 16:23:08 +00004105 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004106 size_t size = sizeof(audio_track_cblk_t);
4107 uint8_t channelCount = popcount(channelMask);
4108 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4109 if (sharedBuffer == 0) {
4110 size += bufferSize;
4111 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004112
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004113 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004114 mCblkMemory = client->heap()->allocate(size);
4115 if (mCblkMemory != 0) {
4116 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004117 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004118 new(mCblk) audio_track_cblk_t();
4119 // clear all buffers
4120 mCblk->frameCount = frameCount;
4121 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004122// uncomment the following lines to quickly test 32-bit wraparound
4123// mCblk->user = 0xffff0000;
4124// mCblk->server = 0xffff0000;
4125// mCblk->userBase = 0xffff0000;
4126// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004127 mChannelCount = channelCount;
4128 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004129 if (sharedBuffer == 0) {
4130 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4131 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4132 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004133 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004134 mCblk->flags = CBLK_UNDERRUN_ON;
4135 } else {
4136 mBuffer = sharedBuffer->pointer();
4137 }
4138 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4139 }
4140 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004141 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004142 client->heap()->dump("AudioTrack");
4143 return;
4144 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004145 } else {
4146 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004147 // construct the shared structure in-place.
4148 new(mCblk) audio_track_cblk_t();
4149 // clear all buffers
4150 mCblk->frameCount = frameCount;
4151 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004152// uncomment the following lines to quickly test 32-bit wraparound
4153// mCblk->user = 0xffff0000;
4154// mCblk->server = 0xffff0000;
4155// mCblk->userBase = 0xffff0000;
4156// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004157 mChannelCount = channelCount;
4158 mChannelMask = channelMask;
4159 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4160 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4161 // Force underrun condition to avoid false underrun callback until first data is
4162 // written to buffer (other flags are cleared)
4163 mCblk->flags = CBLK_UNDERRUN_ON;
4164 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004165 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004166}
4167
4168AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4169{
Glenn Kastena0d68332012-01-27 16:47:15 -08004170 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004171 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004172 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004173 } else {
4174 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004175 }
4176 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004177 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004178 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004179 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004180 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004181 // If the client's reference count drops to zero, the associated destructor
4182 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4183 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004184 mClient.clear();
4185 }
4186}
4187
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004188// AudioBufferProvider interface
4189// getNextBuffer() = 0;
4190// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004191void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4192{
Glenn Kastene0feee32011-12-13 11:53:26 -08004193 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004194 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004195 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004196 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004197 buffer->frameCount = 0;
4198}
4199
4200bool AudioFlinger::ThreadBase::TrackBase::step() {
4201 bool result;
4202 audio_track_cblk_t* cblk = this->cblk();
4203
4204 result = cblk->stepServer(mFrameCount);
4205 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004206 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004207 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004208 }
4209 return result;
4210}
4211
4212void AudioFlinger::ThreadBase::TrackBase::reset() {
4213 audio_track_cblk_t* cblk = this->cblk();
4214
4215 cblk->user = 0;
4216 cblk->server = 0;
4217 cblk->userBase = 0;
4218 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004219 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004220 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004221}
4222
Mathias Agopian65ab4712010-07-14 17:59:35 -07004223int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4224 return (int)mCblk->sampleRate;
4225}
4226
Mathias Agopian65ab4712010-07-14 17:59:35 -07004227void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4228 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004229 size_t frameSize = cblk->frameSize;
4230 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4231 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004232
4233 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004234 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4235 "TrackBase::getBuffer buffer out of range:\n"
4236 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4237 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004238 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004239 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004240
4241 return bufferStart;
4242}
4243
Eric Laurenta011e352012-03-29 15:51:43 -07004244status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4245{
4246 mSyncEvents.add(event);
4247 return NO_ERROR;
4248}
4249
Mathias Agopian65ab4712010-07-14 17:59:35 -07004250// ----------------------------------------------------------------------------
4251
4252// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4253AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004254 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004255 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004256 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004257 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004258 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004259 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004260 int frameCount,
4261 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004262 int sessionId,
4263 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004264 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004265 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004266 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004267 // mRetryCount initialized later when needed
4268 mSharedBuffer(sharedBuffer),
4269 mStreamType(streamType),
4270 mName(-1), // see note below
4271 mMainBuffer(thread->mixBuffer()),
4272 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004273 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004274 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004275 mFlags(flags),
4276 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004277 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004278 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004279{
4280 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004281 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4282 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004283 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004284 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Glenn Kasten254af182012-07-03 14:59:05 -07004285 mName = thread->getTrackName_l(channelMask);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004286 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004287 if (mName < 0) {
4288 ALOGE("no more track names available");
4289 return;
4290 }
4291 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004292 if (flags & IAudioFlinger::TRACK_FAST) {
4293 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4294 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4295 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004296 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004297 // FIXME This is too eager. We allocate a fast track index before the
4298 // fast track becomes active. Since fast tracks are a scarce resource,
4299 // this means we are potentially denying other more important fast tracks from
4300 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004301 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004302 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004303 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004304 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004305 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004306 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004307 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004308 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004309}
4310
4311AudioFlinger::PlaybackThread::Track::~Track()
4312{
Steve Block3856b092011-10-20 11:56:00 +01004313 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004314 sp<ThreadBase> thread = mThread.promote();
4315 if (thread != 0) {
4316 Mutex::Autolock _l(thread->mLock);
4317 mState = TERMINATED;
4318 }
4319}
4320
4321void AudioFlinger::PlaybackThread::Track::destroy()
4322{
4323 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4324 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004325 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004326 // we must acquire a strong reference on this Track before locking mLock
4327 // here so that the destructor is called only when exiting this function.
4328 // On the other hand, as long as Track::destroy() is only called by
4329 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4330 // this Track with its member mTrack.
4331 sp<Track> keep(this);
4332 { // scope for mLock
4333 sp<ThreadBase> thread = mThread.promote();
4334 if (thread != 0) {
4335 if (!isOutputTrack()) {
4336 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004337 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004338
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004339#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004340 // to track the speaker usage
4341 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004342#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004343 }
4344 AudioSystem::releaseOutput(thread->id());
4345 }
4346 Mutex::Autolock _l(thread->mLock);
4347 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4348 playbackThread->destroyTrack_l(this);
4349 }
4350 }
4351}
4352
Glenn Kasten288ed212012-04-25 17:52:27 -07004353/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4354{
Glenn Kastene213c862012-04-25 13:46:15 -07004355 result.append(" Name Client Type Fmt Chn mask Session mFrCnt fCount S M F SRate L dB R dB "
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07004356 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004357}
4358
Mathias Agopian65ab4712010-07-14 17:59:35 -07004359void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4360{
Glenn Kasten83d86532012-01-17 14:39:34 -08004361 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004362 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004363 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004364 } else {
4365 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4366 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004367 track_state state = mState;
4368 char stateChar;
4369 switch (state) {
4370 case IDLE:
4371 stateChar = 'I';
4372 break;
4373 case TERMINATED:
4374 stateChar = 'T';
4375 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004376 case STOPPING_1:
4377 stateChar = 's';
4378 break;
4379 case STOPPING_2:
4380 stateChar = '5';
4381 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004382 case STOPPED:
4383 stateChar = 'S';
4384 break;
4385 case RESUMING:
4386 stateChar = 'R';
4387 break;
4388 case ACTIVE:
4389 stateChar = 'A';
4390 break;
4391 case PAUSING:
4392 stateChar = 'p';
4393 break;
4394 case PAUSED:
4395 stateChar = 'P';
4396 break;
Eric Laurent29864602012-05-08 18:57:51 -07004397 case FLUSHED:
4398 stateChar = 'F';
4399 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004400 default:
4401 stateChar = '?';
4402 break;
4403 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004404 char nowInUnderrun;
4405 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4406 case UNDERRUN_FULL:
4407 nowInUnderrun = ' ';
4408 break;
4409 case UNDERRUN_PARTIAL:
4410 nowInUnderrun = '<';
4411 break;
4412 case UNDERRUN_EMPTY:
4413 nowInUnderrun = '*';
4414 break;
4415 default:
4416 nowInUnderrun = '?';
4417 break;
4418 }
Glenn Kastene213c862012-04-25 13:46:15 -07004419 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4420 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004421 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004422 mStreamType,
4423 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004424 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004425 mSessionId,
4426 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004427 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004428 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004429 mMute,
4430 mFillingUpStatus,
4431 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004432 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4433 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004434 mCblk->server,
4435 mCblk->user,
4436 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004437 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004438 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004439 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004440 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004441}
4442
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004443// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004444status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004445 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004446{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004447 audio_track_cblk_t* cblk = this->cblk();
4448 uint32_t framesReady;
4449 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004450
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004451 // Check if last stepServer failed, try to step now
4452 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004453 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4454 // Since the fast mixer is higher priority than client callback thread,
4455 // it does not result in priority inversion for client.
4456 // But a non-blocking solution would be preferable to avoid
4457 // fast mixer being unable to tryLock(), and
4458 // to avoid the extra context switches if the client wakes up,
4459 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004460 if (!step()) goto getNextBuffer_exit;
4461 ALOGV("stepServer recovered");
4462 mStepServerFailed = false;
4463 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004464
Glenn Kasten288ed212012-04-25 17:52:27 -07004465 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004466 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004467
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004468 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004469 uint32_t s = cblk->server;
4470 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4471
4472 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4473 if (framesReq > framesReady) {
4474 framesReq = framesReady;
4475 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004476 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004477 framesReq = bufferEnd - s;
4478 }
4479
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004480 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004481 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004482 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004483 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004484
4485getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004486 buffer->raw = NULL;
4487 buffer->frameCount = 0;
4488 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4489 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004490}
4491
Glenn Kasten288ed212012-04-25 17:52:27 -07004492// Note that framesReady() takes a mutex on the control block using tryLock().
4493// This could result in priority inversion if framesReady() is called by the normal mixer,
4494// as the normal mixer thread runs at lower
4495// priority than the client's callback thread: there is a short window within framesReady()
4496// during which the normal mixer could be preempted, and the client callback would block.
4497// Another problem can occur if framesReady() is called by the fast mixer:
4498// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4499// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4500size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004501 return mCblk->framesReady();
4502}
4503
Glenn Kasten288ed212012-04-25 17:52:27 -07004504// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004505bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004506 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004507
John Grossman4ff14ba2012-02-08 16:37:41 -08004508 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004509 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4510 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004511 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004512 return true;
4513 }
4514 return false;
4515}
4516
Glenn Kasten3acbd052012-02-28 10:39:56 -08004517status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004518 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004519{
4520 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004521 ALOGV("start(%d), calling pid %d session %d",
4522 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004523
Mathias Agopian65ab4712010-07-14 17:59:35 -07004524 sp<ThreadBase> thread = mThread.promote();
4525 if (thread != 0) {
4526 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004527 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004528 // here the track could be either new, or restarted
4529 // in both cases "unstop" the track
4530 if (mState == PAUSED) {
4531 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004532 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004533 } else {
4534 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004535 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004536 }
4537
4538 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4539 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004540 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004541 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004542
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004543#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004544 // to track the speaker usage
4545 if (status == NO_ERROR) {
4546 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4547 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004548#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004549 }
4550 if (status == NO_ERROR) {
4551 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4552 playbackThread->addTrack_l(this);
4553 } else {
4554 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004555 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004556 }
4557 } else {
4558 status = BAD_VALUE;
4559 }
4560 return status;
4561}
4562
4563void AudioFlinger::PlaybackThread::Track::stop()
4564{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004565 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004566 sp<ThreadBase> thread = mThread.promote();
4567 if (thread != 0) {
4568 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004569 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004570 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004571 // If the track is not active (PAUSED and buffers full), flush buffers
4572 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4573 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4574 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004575 mState = STOPPED;
4576 } else if (!isFastTrack()) {
4577 mState = STOPPED;
4578 } else {
4579 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4580 // and then to STOPPED and reset() when presentation is complete
4581 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004582 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004583 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004584 }
4585 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4586 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004587 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004588 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004589
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004590#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004591 // to track the speaker usage
4592 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004593#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004594 }
4595 }
4596}
4597
4598void AudioFlinger::PlaybackThread::Track::pause()
4599{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004600 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004601 sp<ThreadBase> thread = mThread.promote();
4602 if (thread != 0) {
4603 Mutex::Autolock _l(thread->mLock);
4604 if (mState == ACTIVE || mState == RESUMING) {
4605 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004606 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004607 if (!isOutputTrack()) {
4608 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004609 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004610 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004611
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004612#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004613 // to track the speaker usage
4614 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004615#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004616 }
4617 }
4618 }
4619}
4620
4621void AudioFlinger::PlaybackThread::Track::flush()
4622{
Steve Block3856b092011-10-20 11:56:00 +01004623 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004624 sp<ThreadBase> thread = mThread.promote();
4625 if (thread != 0) {
4626 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004627 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4628 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004629 return;
4630 }
4631 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004632 // FLUSHED state
4633 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004634 // do not reset the track if it is still in the process of being stopped or paused.
4635 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004636 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004637 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004638 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4639 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4640 reset();
4641 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004642 }
4643}
4644
4645void AudioFlinger::PlaybackThread::Track::reset()
4646{
4647 // Do not reset twice to avoid discarding data written just after a flush and before
4648 // the audioflinger thread detects the track is stopped.
4649 if (!mResetDone) {
4650 TrackBase::reset();
4651 // Force underrun condition to avoid false underrun callback until first data is
4652 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004653 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4654 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004655 mFillingUpStatus = FS_FILLING;
4656 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004657 if (mState == FLUSHED) {
4658 mState = IDLE;
4659 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004660 }
4661}
4662
4663void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4664{
4665 mMute = muted;
4666}
4667
Mathias Agopian65ab4712010-07-14 17:59:35 -07004668status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4669{
4670 status_t status = DEAD_OBJECT;
4671 sp<ThreadBase> thread = mThread.promote();
4672 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004673 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004674 sp<AudioFlinger> af = mClient->audioFlinger();
4675
4676 Mutex::Autolock _l(af->mLock);
4677
4678 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004679
Eric Laurent109347d2012-07-02 12:31:03 -07004680 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004681 Mutex::Autolock _dl(playbackThread->mLock);
4682 Mutex::Autolock _sl(srcThread->mLock);
4683 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4684 if (chain == 0) {
4685 return INVALID_OPERATION;
4686 }
4687
4688 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4689 if (effect == 0) {
4690 return INVALID_OPERATION;
4691 }
4692 srcThread->removeEffect_l(effect);
4693 playbackThread->addEffect_l(effect);
4694 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4695 if (effect->state() == EffectModule::ACTIVE ||
4696 effect->state() == EffectModule::STOPPING) {
4697 effect->start();
4698 }
4699
4700 sp<EffectChain> dstChain = effect->chain().promote();
4701 if (dstChain == 0) {
4702 srcThread->addEffect_l(effect);
4703 return INVALID_OPERATION;
4704 }
4705 AudioSystem::unregisterEffect(effect->id());
4706 AudioSystem::registerEffect(&effect->desc(),
4707 srcThread->id(),
4708 dstChain->strategy(),
4709 AUDIO_SESSION_OUTPUT_MIX,
4710 effect->id());
4711 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004712 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004713 }
4714 return status;
4715}
4716
4717void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4718{
4719 mAuxEffectId = EffectId;
4720 mAuxBuffer = buffer;
4721}
4722
Eric Laurenta011e352012-03-29 15:51:43 -07004723bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4724 size_t audioHalFrames)
4725{
4726 // a track is considered presented when the total number of frames written to audio HAL
4727 // corresponds to the number of frames written when presentationComplete() is called for the
4728 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4729 if (mPresentationCompleteFrames == 0) {
4730 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4731 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4732 mPresentationCompleteFrames, audioHalFrames);
4733 }
4734 if (framesWritten >= mPresentationCompleteFrames) {
4735 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4736 mSessionId, framesWritten);
4737 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004738 return true;
4739 }
4740 return false;
4741}
4742
4743void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4744{
4745 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4746 if (mSyncEvents[i]->type() == type) {
4747 mSyncEvents[i]->trigger();
4748 mSyncEvents.removeAt(i);
4749 i--;
4750 }
4751 }
4752}
4753
Glenn Kasten58912562012-04-03 10:45:00 -07004754// implement VolumeBufferProvider interface
4755
4756uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4757{
4758 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4759 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4760 uint32_t vlr = mCblk->getVolumeLR();
4761 uint32_t vl = vlr & 0xFFFF;
4762 uint32_t vr = vlr >> 16;
4763 // track volumes come from shared memory, so can't be trusted and must be clamped
4764 if (vl > MAX_GAIN_INT) {
4765 vl = MAX_GAIN_INT;
4766 }
4767 if (vr > MAX_GAIN_INT) {
4768 vr = MAX_GAIN_INT;
4769 }
4770 // now apply the cached master volume and stream type volume;
4771 // this is trusted but lacks any synchronization or barrier so may be stale
4772 float v = mCachedVolume;
4773 vl *= v;
4774 vr *= v;
4775 // re-combine into U4.16
4776 vlr = (vr << 16) | (vl & 0xFFFF);
4777 // FIXME look at mute, pause, and stop flags
4778 return vlr;
4779}
Eric Laurenta011e352012-03-29 15:51:43 -07004780
Eric Laurent29864602012-05-08 18:57:51 -07004781status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4782{
4783 if (mState == TERMINATED || mState == PAUSED ||
4784 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4785 (mState == STOPPED)))) {
4786 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4787 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4788 event->cancel();
4789 return INVALID_OPERATION;
4790 }
4791 TrackBase::setSyncEvent(event);
4792 return NO_ERROR;
4793}
4794
John Grossman4ff14ba2012-02-08 16:37:41 -08004795// timed audio tracks
4796
4797sp<AudioFlinger::PlaybackThread::TimedTrack>
4798AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004799 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004800 const sp<Client>& client,
4801 audio_stream_type_t streamType,
4802 uint32_t sampleRate,
4803 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004804 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004805 int frameCount,
4806 const sp<IMemory>& sharedBuffer,
4807 int sessionId) {
4808 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004809 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004810
Glenn Kastena0356762012-03-19 10:38:51 -07004811 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004812 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4813 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004814}
4815
4816AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004817 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004818 const sp<Client>& client,
4819 audio_stream_type_t streamType,
4820 uint32_t sampleRate,
4821 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004822 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004823 int frameCount,
4824 const sp<IMemory>& sharedBuffer,
4825 int sessionId)
4826 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004827 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004828 mQueueHeadInFlight(false),
4829 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004830 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004831 mTimedSilenceBuffer(NULL),
4832 mTimedSilenceBufferSize(0),
4833 mTimedAudioOutputOnTime(false),
4834 mMediaTimeTransformValid(false)
4835{
4836 LocalClock lc;
4837 mLocalTimeFreq = lc.getLocalFreq();
4838
4839 mLocalTimeToSampleTransform.a_zero = 0;
4840 mLocalTimeToSampleTransform.b_zero = 0;
4841 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4842 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4843 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4844 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004845
4846 mMediaTimeToSampleTransform.a_zero = 0;
4847 mMediaTimeToSampleTransform.b_zero = 0;
4848 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4849 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4850 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4851 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004852}
4853
4854AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4855 mClient->releaseTimedTrack();
4856 delete [] mTimedSilenceBuffer;
4857}
4858
4859status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4860 size_t size, sp<IMemory>* buffer) {
4861
4862 Mutex::Autolock _l(mTimedBufferQueueLock);
4863
4864 trimTimedBufferQueue_l();
4865
4866 // lazily initialize the shared memory heap for timed buffers
4867 if (mTimedMemoryDealer == NULL) {
4868 const int kTimedBufferHeapSize = 512 << 10;
4869
4870 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4871 "AudioFlingerTimed");
4872 if (mTimedMemoryDealer == NULL)
4873 return NO_MEMORY;
4874 }
4875
4876 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4877 if (newBuffer == NULL) {
4878 newBuffer = mTimedMemoryDealer->allocate(size);
4879 if (newBuffer == NULL)
4880 return NO_MEMORY;
4881 }
4882
4883 *buffer = newBuffer;
4884 return NO_ERROR;
4885}
4886
4887// caller must hold mTimedBufferQueueLock
4888void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4889 int64_t mediaTimeNow;
4890 {
4891 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4892 if (!mMediaTimeTransformValid)
4893 return;
4894
4895 int64_t targetTimeNow;
4896 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4897 ? mCCHelper.getCommonTime(&targetTimeNow)
4898 : mCCHelper.getLocalTime(&targetTimeNow);
4899
4900 if (OK != res)
4901 return;
4902
4903 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4904 &mediaTimeNow)) {
4905 return;
4906 }
4907 }
4908
John Grossman1c345192012-03-27 14:00:17 -07004909 size_t trimEnd;
4910 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004911 int64_t bufEnd;
4912
John Grossmanc95cfbb2012-04-12 11:53:11 -07004913 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4914 // We have a next buffer. Just use its PTS as the PTS of the frame
4915 // following the last frame in this buffer. If the stream is sparse
4916 // (ie, there are deliberate gaps left in the stream which should be
4917 // filled with silence by the TimedAudioTrack), then this can result
4918 // in one extra buffer being left un-trimmed when it could have
4919 // been. In general, this is not typical, and we would rather
4920 // optimized away the TS calculation below for the more common case
4921 // where PTSes are contiguous.
4922 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4923 } else {
4924 // We have no next buffer. Compute the PTS of the frame following
4925 // the last frame in this buffer by computing the duration of of
4926 // this frame in media time units and adding it to the PTS of the
4927 // buffer.
4928 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4929 / mCblk->frameSize;
4930
4931 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4932 &bufEnd)) {
4933 ALOGE("Failed to convert frame count of %lld to media time"
4934 " duration" " (scale factor %d/%u) in %s",
4935 frameCount,
4936 mMediaTimeToSampleTransform.a_to_b_numer,
4937 mMediaTimeToSampleTransform.a_to_b_denom,
4938 __PRETTY_FUNCTION__);
4939 break;
4940 }
4941 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004942 }
John Grossman9fbdee12012-03-26 17:51:46 -07004943
4944 if (bufEnd > mediaTimeNow)
4945 break;
4946
4947 // Is the buffer we want to use in the middle of a mix operation right
4948 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4949 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004950 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004951 mTrimQueueHeadOnRelease = true;
4952 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004953 }
4954
John Grossman9fbdee12012-03-26 17:51:46 -07004955 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004956 if (trimStart < trimEnd) {
4957 // Update the bookkeeping for framesReady()
4958 for (size_t i = trimStart; i < trimEnd; ++i) {
4959 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4960 }
4961
4962 // Now actually remove the buffers from the queue.
4963 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004964 }
4965}
4966
John Grossman1c345192012-03-27 14:00:17 -07004967void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4968 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004969 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4970 "%s called (reason \"%s\"), but timed buffer queue has no"
4971 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004972
4973 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4974 mTimedBufferQueue.removeAt(0);
4975}
4976
4977void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4978 const TimedBuffer& buf,
4979 const char* logTag) {
4980 uint32_t bufBytes = buf.buffer()->size();
4981 uint32_t consumedAlready = buf.position();
4982
Eric Laurentb388e532012-04-14 13:32:48 -07004983 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004984 "Bad bookkeeping while updating frames pending. Timed buffer is"
4985 " only %u bytes long, but claims to have consumed %u"
4986 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004987 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004988
4989 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004990 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4991 "Bad bookkeeping while updating frames pending. Should have at"
4992 " least %u queued frames, but we think we have only %u. (update"
4993 " reason: \"%s\")",
4994 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004995
4996 mFramesPendingInQueue -= bufFrames;
4997}
4998
John Grossman4ff14ba2012-02-08 16:37:41 -08004999status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5000 const sp<IMemory>& buffer, int64_t pts) {
5001
5002 {
5003 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5004 if (!mMediaTimeTransformValid)
5005 return INVALID_OPERATION;
5006 }
5007
5008 Mutex::Autolock _l(mTimedBufferQueueLock);
5009
John Grossman1c345192012-03-27 14:00:17 -07005010 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5011 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005012 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5013
5014 return NO_ERROR;
5015}
5016
5017status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5018 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5019
John Grossman1c345192012-03-27 14:00:17 -07005020 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5021 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5022 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005023
5024 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5025 target == TimedAudioTrack::COMMON_TIME)) {
5026 return BAD_VALUE;
5027 }
5028
5029 Mutex::Autolock lock(mMediaTimeTransformLock);
5030 mMediaTimeTransform = xform;
5031 mMediaTimeTransformTarget = target;
5032 mMediaTimeTransformValid = true;
5033
5034 return NO_ERROR;
5035}
5036
5037#define min(a, b) ((a) < (b) ? (a) : (b))
5038
5039// implementation of getNextBuffer for tracks whose buffers have timestamps
5040status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5041 AudioBufferProvider::Buffer* buffer, int64_t pts)
5042{
5043 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005044 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005045 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005046 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005047 return INVALID_OPERATION;
5048 }
5049
John Grossman4ff14ba2012-02-08 16:37:41 -08005050 Mutex::Autolock _l(mTimedBufferQueueLock);
5051
John Grossman9fbdee12012-03-26 17:51:46 -07005052 ALOG_ASSERT(!mQueueHeadInFlight,
5053 "getNextBuffer called without releaseBuffer!");
5054
John Grossman4ff14ba2012-02-08 16:37:41 -08005055 while (true) {
5056
5057 // if we have no timed buffers, then fail
5058 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005059 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005060 buffer->frameCount = 0;
5061 return NOT_ENOUGH_DATA;
5062 }
5063
5064 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5065
5066 // calculate the PTS of the head of the timed buffer queue expressed in
5067 // local time
5068 int64_t headLocalPTS;
5069 {
5070 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5071
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005072 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005073
5074 if (mMediaTimeTransform.a_to_b_denom == 0) {
5075 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005076 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005077 return NO_ERROR;
5078 }
5079
5080 int64_t transformedPTS;
5081 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5082 &transformedPTS)) {
5083 // the transform failed. this shouldn't happen, but if it does
5084 // then just drop this buffer
5085 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005086 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005087 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005088 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005089 return NO_ERROR;
5090 }
5091
5092 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5093 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5094 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005095 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005096 buffer->frameCount = 0;
5097 return INVALID_OPERATION;
5098 }
5099 } else {
5100 headLocalPTS = transformedPTS;
5101 }
5102 }
5103
5104 // adjust the head buffer's PTS to reflect the portion of the head buffer
5105 // that has already been consumed
5106 int64_t effectivePTS = headLocalPTS +
5107 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5108
5109 // Calculate the delta in samples between the head of the input buffer
5110 // queue and the start of the next output buffer that will be written.
5111 // If the transformation fails because of over or underflow, it means
5112 // that the sample's position in the output stream is so far out of
5113 // whack that it should just be dropped.
5114 int64_t sampleDelta;
5115 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5116 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005117 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5118 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005119 continue;
5120 }
5121 if (!mLocalTimeToSampleTransform.doForwardTransform(
5122 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005123 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005124 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005125 continue;
5126 }
5127
John Grossman1c345192012-03-27 14:00:17 -07005128 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5129 " sampleDelta=[%d.%08x]",
5130 head.pts(), head.position(), pts,
5131 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5132 + (sampleDelta >> 32)),
5133 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005134
5135 // if the delta between the ideal placement for the next input sample and
5136 // the current output position is within this threshold, then we will
5137 // concatenate the next input samples to the previous output
5138 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005139 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005140
5141 // if this is the first buffer of audio that we're emitting from this track
5142 // then it should be almost exactly on time.
5143 const int64_t kSampleStartupThreshold = 1LL << 32;
5144
5145 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005146 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005147 // the next input is close enough to being on time, so concatenate it
5148 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005149 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005150
John Grossman1c345192012-03-27 14:00:17 -07005151 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5152 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005153 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005154 }
5155
5156 // Looks like our output is not on time. Reset our on timed status.
5157 // Next time we mix samples from our input queue, then should be within
5158 // the StartupThreshold.
5159 mTimedAudioOutputOnTime = false;
5160 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005161 // the gap between the current output position and the proper start of
5162 // the next input sample is too big, so fill it with silence
5163 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5164
John Grossman9fbdee12012-03-26 17:51:46 -07005165 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005166 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5167 return NO_ERROR;
5168 } else {
5169 // the next input sample is late
5170 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5171 size_t onTimeSamplePosition =
5172 head.position() + lateFrames * mCblk->frameSize;
5173
5174 if (onTimeSamplePosition > head.buffer()->size()) {
5175 // all the remaining samples in the head are too late, so
5176 // drop it and move on
5177 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005178 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005179 continue;
5180 } else {
5181 // skip over the late samples
5182 head.setPosition(onTimeSamplePosition);
5183
5184 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005185 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005186
5187 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5188 return NO_ERROR;
5189 }
5190 }
5191 }
5192}
5193
5194// Yield samples from the timed buffer queue head up to the given output
5195// buffer's capacity.
5196//
5197// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005198void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005199 AudioBufferProvider::Buffer* buffer) {
5200
5201 const TimedBuffer& head = mTimedBufferQueue[0];
5202
5203 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5204 head.position());
5205
5206 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5207 mCblk->frameSize);
5208 size_t framesRequested = buffer->frameCount;
5209 buffer->frameCount = min(framesLeftInHead, framesRequested);
5210
John Grossman9fbdee12012-03-26 17:51:46 -07005211 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005212 mTimedAudioOutputOnTime = true;
5213}
5214
5215// Yield samples of silence up to the given output buffer's capacity
5216//
5217// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005218void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005219 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5220
5221 // lazily allocate a buffer filled with silence
5222 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5223 delete [] mTimedSilenceBuffer;
5224 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5225 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5226 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5227 }
5228
5229 buffer->raw = mTimedSilenceBuffer;
5230 size_t framesRequested = buffer->frameCount;
5231 buffer->frameCount = min(numFrames, framesRequested);
5232
5233 mTimedAudioOutputOnTime = false;
5234}
5235
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005236// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005237void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5238 AudioBufferProvider::Buffer* buffer) {
5239
5240 Mutex::Autolock _l(mTimedBufferQueueLock);
5241
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005242 // If the buffer which was just released is part of the buffer at the head
5243 // of the queue, be sure to update the amt of the buffer which has been
5244 // consumed. If the buffer being returned is not part of the head of the
5245 // queue, its either because the buffer is part of the silence buffer, or
5246 // because the head of the timed queue was trimmed after the mixer called
5247 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005248 if (buffer->raw == mTimedSilenceBuffer) {
5249 ALOG_ASSERT(!mQueueHeadInFlight,
5250 "Queue head in flight during release of silence buffer!");
5251 goto done;
5252 }
5253
5254 ALOG_ASSERT(mQueueHeadInFlight,
5255 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5256 " head in flight.");
5257
5258 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005259 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005260
5261 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005262 void* end = reinterpret_cast<void*>(
5263 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5264 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005265
John Grossman9fbdee12012-03-26 17:51:46 -07005266 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5267 "released buffer not within the head of the timed buffer"
5268 " queue; qHead = [%p, %p], released buffer = %p",
5269 start, end, buffer->raw);
5270
5271 head.setPosition(head.position() +
5272 (buffer->frameCount * mCblk->frameSize));
5273 mQueueHeadInFlight = false;
5274
John Grossman1c345192012-03-27 14:00:17 -07005275 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5276 "Bad bookkeeping during releaseBuffer! Should have at"
5277 " least %u queued frames, but we think we have only %u",
5278 buffer->frameCount, mFramesPendingInQueue);
5279
5280 mFramesPendingInQueue -= buffer->frameCount;
5281
John Grossman9fbdee12012-03-26 17:51:46 -07005282 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5283 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005284 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005285 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005286 }
John Grossman9fbdee12012-03-26 17:51:46 -07005287 } else {
5288 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5289 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005290 }
5291
John Grossman9fbdee12012-03-26 17:51:46 -07005292done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005293 buffer->raw = 0;
5294 buffer->frameCount = 0;
5295}
5296
Glenn Kasten288ed212012-04-25 17:52:27 -07005297size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005298 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005299 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005300}
5301
5302AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5303 : mPTS(0), mPosition(0) {}
5304
5305AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5306 const sp<IMemory>& buffer, int64_t pts)
5307 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5308
Mathias Agopian65ab4712010-07-14 17:59:35 -07005309// ----------------------------------------------------------------------------
5310
5311// RecordTrack constructor must be called with AudioFlinger::mLock held
5312AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005313 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005314 const sp<Client>& client,
5315 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005316 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005317 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005318 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005319 int sessionId)
5320 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005321 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005322 mOverflow(false)
5323{
5324 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005325 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5326 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5327 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5328 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5329 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5330 } else {
5331 mCblk->frameSize = sizeof(int8_t);
5332 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005333 }
5334}
5335
5336AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5337{
5338 sp<ThreadBase> thread = mThread.promote();
5339 if (thread != 0) {
5340 AudioSystem::releaseInput(thread->id());
5341 }
5342}
5343
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005344// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005345status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005346{
5347 audio_track_cblk_t* cblk = this->cblk();
5348 uint32_t framesAvail;
5349 uint32_t framesReq = buffer->frameCount;
5350
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005351 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005352 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005353 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005354 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005355 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005356 }
5357
5358 framesAvail = cblk->framesAvailable_l();
5359
Glenn Kastenf6b16782011-12-15 09:51:17 -08005360 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005361 uint32_t s = cblk->server;
5362 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5363
5364 if (framesReq > framesAvail) {
5365 framesReq = framesAvail;
5366 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005367 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005368 framesReq = bufferEnd - s;
5369 }
5370
5371 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372 buffer->frameCount = framesReq;
5373 return NO_ERROR;
5374 }
5375
5376getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005377 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005378 buffer->frameCount = 0;
5379 return NOT_ENOUGH_DATA;
5380}
5381
Glenn Kasten3acbd052012-02-28 10:39:56 -08005382status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005383 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005384{
5385 sp<ThreadBase> thread = mThread.promote();
5386 if (thread != 0) {
5387 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005388 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005389 } else {
5390 return BAD_VALUE;
5391 }
5392}
5393
5394void AudioFlinger::RecordThread::RecordTrack::stop()
5395{
5396 sp<ThreadBase> thread = mThread.promote();
5397 if (thread != 0) {
5398 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005399 recordThread->mLock.lock();
5400 bool doStop = recordThread->stop_l(this);
5401 if (doStop) {
5402 TrackBase::reset();
5403 // Force overrun condition to avoid false overrun callback until first data is
5404 // read from buffer
5405 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5406 }
5407 recordThread->mLock.unlock();
5408 if (doStop) {
5409 AudioSystem::stopInput(recordThread->id());
5410 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005411 }
5412}
5413
5414void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5415{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005416 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005417 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005418 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005419 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005420 mSessionId,
5421 mFrameCount,
5422 mState,
5423 mCblk->sampleRate,
5424 mCblk->server,
5425 mCblk->user);
5426}
5427
5428
5429// ----------------------------------------------------------------------------
5430
5431AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005432 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005433 DuplicatingThread *sourceThread,
5434 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005435 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005436 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005437 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005438 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5439 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005440 mActive(false), mSourceThread(sourceThread)
5441{
5442
Mathias Agopian65ab4712010-07-14 17:59:35 -07005443 if (mCblk != NULL) {
5444 mCblk->flags |= CBLK_DIRECTION_OUT;
5445 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446 mOutBuffer.frameCount = 0;
5447 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005448 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005449 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5450 mCblk, mBuffer, mCblk->buffers,
5451 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005452 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005453 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005454 }
5455}
5456
5457AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5458{
5459 clearBufferQueue();
5460}
5461
Glenn Kasten3acbd052012-02-28 10:39:56 -08005462status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005463 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005464{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005465 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005466 if (status != NO_ERROR) {
5467 return status;
5468 }
5469
5470 mActive = true;
5471 mRetryCount = 127;
5472 return status;
5473}
5474
5475void AudioFlinger::PlaybackThread::OutputTrack::stop()
5476{
5477 Track::stop();
5478 clearBufferQueue();
5479 mOutBuffer.frameCount = 0;
5480 mActive = false;
5481}
5482
5483bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5484{
5485 Buffer *pInBuffer;
5486 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005487 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005488 bool outputBufferFull = false;
5489 inBuffer.frameCount = frames;
5490 inBuffer.i16 = data;
5491
5492 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5493
5494 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005495 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005496 sp<ThreadBase> thread = mThread.promote();
5497 if (thread != 0) {
5498 MixerThread *mixerThread = (MixerThread *)thread.get();
5499 if (mCblk->frameCount > frames){
5500 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5501 uint32_t startFrames = (mCblk->frameCount - frames);
5502 pInBuffer = new Buffer;
5503 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5504 pInBuffer->frameCount = startFrames;
5505 pInBuffer->i16 = pInBuffer->mBuffer;
5506 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5507 mBufferQueue.add(pInBuffer);
5508 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005509 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005510 }
5511 }
5512 }
5513 }
5514
5515 while (waitTimeLeftMs) {
5516 // First write pending buffers, then new data
5517 if (mBufferQueue.size()) {
5518 pInBuffer = mBufferQueue.itemAt(0);
5519 } else {
5520 pInBuffer = &inBuffer;
5521 }
5522
5523 if (pInBuffer->frameCount == 0) {
5524 break;
5525 }
5526
5527 if (mOutBuffer.frameCount == 0) {
5528 mOutBuffer.frameCount = pInBuffer->frameCount;
5529 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005530 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005531 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005532 outputBufferFull = true;
5533 break;
5534 }
5535 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5536 if (waitTimeLeftMs >= waitTimeMs) {
5537 waitTimeLeftMs -= waitTimeMs;
5538 } else {
5539 waitTimeLeftMs = 0;
5540 }
5541 }
5542
5543 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5544 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5545 mCblk->stepUser(outFrames);
5546 pInBuffer->frameCount -= outFrames;
5547 pInBuffer->i16 += outFrames * channelCount;
5548 mOutBuffer.frameCount -= outFrames;
5549 mOutBuffer.i16 += outFrames * channelCount;
5550
5551 if (pInBuffer->frameCount == 0) {
5552 if (mBufferQueue.size()) {
5553 mBufferQueue.removeAt(0);
5554 delete [] pInBuffer->mBuffer;
5555 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005556 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005557 } else {
5558 break;
5559 }
5560 }
5561 }
5562
5563 // If we could not write all frames, allocate a buffer and queue it for next time.
5564 if (inBuffer.frameCount) {
5565 sp<ThreadBase> thread = mThread.promote();
5566 if (thread != 0 && !thread->standby()) {
5567 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5568 pInBuffer = new Buffer;
5569 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5570 pInBuffer->frameCount = inBuffer.frameCount;
5571 pInBuffer->i16 = pInBuffer->mBuffer;
5572 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5573 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005574 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005575 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005576 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005577 }
5578 }
5579 }
5580
5581 // Calling write() with a 0 length buffer, means that no more data will be written:
5582 // If no more buffers are pending, fill output track buffer to make sure it is started
5583 // by output mixer.
5584 if (frames == 0 && mBufferQueue.size() == 0) {
5585 if (mCblk->user < mCblk->frameCount) {
5586 frames = mCblk->frameCount - mCblk->user;
5587 pInBuffer = new Buffer;
5588 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5589 pInBuffer->frameCount = frames;
5590 pInBuffer->i16 = pInBuffer->mBuffer;
5591 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5592 mBufferQueue.add(pInBuffer);
5593 } else if (mActive) {
5594 stop();
5595 }
5596 }
5597
5598 return outputBufferFull;
5599}
5600
5601status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5602{
5603 int active;
5604 status_t result;
5605 audio_track_cblk_t* cblk = mCblk;
5606 uint32_t framesReq = buffer->frameCount;
5607
Steve Block3856b092011-10-20 11:56:00 +01005608// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005609 buffer->frameCount = 0;
5610
5611 uint32_t framesAvail = cblk->framesAvailable();
5612
5613
5614 if (framesAvail == 0) {
5615 Mutex::Autolock _l(cblk->lock);
5616 goto start_loop_here;
5617 while (framesAvail == 0) {
5618 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005619 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005620 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005621 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005622 }
5623 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5624 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005625 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005626 }
5627 // read the server count again
5628 start_loop_here:
5629 framesAvail = cblk->framesAvailable_l();
5630 }
5631 }
5632
5633// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005634// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005635// }
5636
5637 if (framesReq > framesAvail) {
5638 framesReq = framesAvail;
5639 }
5640
5641 uint32_t u = cblk->user;
5642 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5643
Marco Nelissena1472d92012-03-30 14:36:54 -07005644 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005645 framesReq = bufferEnd - u;
5646 }
5647
5648 buffer->frameCount = framesReq;
5649 buffer->raw = (void *)cblk->buffer(u);
5650 return NO_ERROR;
5651}
5652
5653
5654void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5655{
5656 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005657
5658 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005659 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005660 delete [] pBuffer->mBuffer;
5661 delete pBuffer;
5662 }
5663 mBufferQueue.clear();
5664}
5665
5666// ----------------------------------------------------------------------------
5667
5668AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5669 : RefBase(),
5670 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005671 // 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 -07005672 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005673 mPid(pid),
5674 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005675{
5676 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5677}
5678
5679// Client destructor must be called with AudioFlinger::mLock held
5680AudioFlinger::Client::~Client()
5681{
5682 mAudioFlinger->removeClient_l(mPid);
5683}
5684
Glenn Kasten435dbe62012-01-30 10:15:48 -08005685sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005686{
5687 return mMemoryDealer;
5688}
5689
John Grossman4ff14ba2012-02-08 16:37:41 -08005690// Reserve one of the limited slots for a timed audio track associated
5691// with this client
5692bool AudioFlinger::Client::reserveTimedTrack()
5693{
5694 const int kMaxTimedTracksPerClient = 4;
5695
5696 Mutex::Autolock _l(mTimedTrackLock);
5697
5698 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5699 ALOGW("can not create timed track - pid %d has exceeded the limit",
5700 mPid);
5701 return false;
5702 }
5703
5704 mTimedTrackCount++;
5705 return true;
5706}
5707
5708// Release a slot for a timed audio track
5709void AudioFlinger::Client::releaseTimedTrack()
5710{
5711 Mutex::Autolock _l(mTimedTrackLock);
5712 mTimedTrackCount--;
5713}
5714
Mathias Agopian65ab4712010-07-14 17:59:35 -07005715// ----------------------------------------------------------------------------
5716
5717AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5718 const sp<IAudioFlingerClient>& client,
5719 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005720 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005721{
5722}
5723
5724AudioFlinger::NotificationClient::~NotificationClient()
5725{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005726}
5727
5728void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5729{
5730 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005731 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005732}
5733
5734// ----------------------------------------------------------------------------
5735
5736AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5737 : BnAudioTrack(),
5738 mTrack(track)
5739{
5740}
5741
5742AudioFlinger::TrackHandle::~TrackHandle() {
5743 // just stop the track on deletion, associated resources
5744 // will be freed from the main thread once all pending buffers have
5745 // been played. Unless it's not in the active track list, in which
5746 // case we free everything now...
5747 mTrack->destroy();
5748}
5749
Glenn Kasten90716c52012-01-26 13:40:12 -08005750sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5751 return mTrack->getCblk();
5752}
5753
Glenn Kasten3acbd052012-02-28 10:39:56 -08005754status_t AudioFlinger::TrackHandle::start() {
5755 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005756}
5757
5758void AudioFlinger::TrackHandle::stop() {
5759 mTrack->stop();
5760}
5761
5762void AudioFlinger::TrackHandle::flush() {
5763 mTrack->flush();
5764}
5765
5766void AudioFlinger::TrackHandle::mute(bool e) {
5767 mTrack->mute(e);
5768}
5769
5770void AudioFlinger::TrackHandle::pause() {
5771 mTrack->pause();
5772}
5773
Mathias Agopian65ab4712010-07-14 17:59:35 -07005774status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5775{
5776 return mTrack->attachAuxEffect(EffectId);
5777}
5778
John Grossman4ff14ba2012-02-08 16:37:41 -08005779status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5780 sp<IMemory>* buffer) {
5781 if (!mTrack->isTimedTrack())
5782 return INVALID_OPERATION;
5783
5784 PlaybackThread::TimedTrack* tt =
5785 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5786 return tt->allocateTimedBuffer(size, buffer);
5787}
5788
5789status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5790 int64_t pts) {
5791 if (!mTrack->isTimedTrack())
5792 return INVALID_OPERATION;
5793
5794 PlaybackThread::TimedTrack* tt =
5795 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5796 return tt->queueTimedBuffer(buffer, pts);
5797}
5798
5799status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5800 const LinearTransform& xform, int target) {
5801
5802 if (!mTrack->isTimedTrack())
5803 return INVALID_OPERATION;
5804
5805 PlaybackThread::TimedTrack* tt =
5806 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5807 return tt->setMediaTimeTransform(
5808 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5809}
5810
Mathias Agopian65ab4712010-07-14 17:59:35 -07005811status_t AudioFlinger::TrackHandle::onTransact(
5812 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5813{
5814 return BnAudioTrack::onTransact(code, data, reply, flags);
5815}
5816
5817// ----------------------------------------------------------------------------
5818
5819sp<IAudioRecord> AudioFlinger::openRecord(
5820 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005821 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005822 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005823 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005824 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005825 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005826 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07005827 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005828 int *sessionId,
5829 status_t *status)
5830{
5831 sp<RecordThread::RecordTrack> recordTrack;
5832 sp<RecordHandle> recordHandle;
5833 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005834 status_t lStatus;
5835 RecordThread *thread;
5836 size_t inFrameCount;
5837 int lSessionId;
5838
5839 // check calling permissions
5840 if (!recordingAllowed()) {
5841 lStatus = PERMISSION_DENIED;
5842 goto Exit;
5843 }
5844
5845 // add client to list
5846 { // scope for mLock
5847 Mutex::Autolock _l(mLock);
5848 thread = checkRecordThread_l(input);
5849 if (thread == NULL) {
5850 lStatus = BAD_VALUE;
5851 goto Exit;
5852 }
5853
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005854 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005855
5856 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005857 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005858 lSessionId = *sessionId;
5859 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005860 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005861 if (sessionId != NULL) {
5862 *sessionId = lSessionId;
5863 }
5864 }
5865 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07005866 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5867 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005868 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005869 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005870 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5871 // destructor is called by the TrackBase destructor with mLock held
5872 client.clear();
5873 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005874 goto Exit;
5875 }
5876
5877 // return to handle to client
5878 recordHandle = new RecordHandle(recordTrack);
5879 lStatus = NO_ERROR;
5880
5881Exit:
5882 if (status) {
5883 *status = lStatus;
5884 }
5885 return recordHandle;
5886}
5887
5888// ----------------------------------------------------------------------------
5889
5890AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5891 : BnAudioRecord(),
5892 mRecordTrack(recordTrack)
5893{
5894}
5895
5896AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005897 stop_nonvirtual();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005898}
5899
Glenn Kasten90716c52012-01-26 13:40:12 -08005900sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5901 return mRecordTrack->getCblk();
5902}
5903
Glenn Kasten0ec23ce2012-07-10 12:56:08 -07005904status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005905 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005906 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005907}
5908
5909void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005910 stop_nonvirtual();
5911}
5912
5913void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01005914 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005915 mRecordTrack->stop();
5916}
5917
Mathias Agopian65ab4712010-07-14 17:59:35 -07005918status_t AudioFlinger::RecordHandle::onTransact(
5919 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5920{
5921 return BnAudioRecord::onTransact(code, data, reply, flags);
5922}
5923
5924// ----------------------------------------------------------------------------
5925
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005926AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5927 AudioStreamIn *input,
5928 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07005929 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005930 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07005931 audio_devices_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005932 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005933 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
5934 // mRsmpInIndex and mInputBytes set by readInputParameters()
Glenn Kasten254af182012-07-03 14:59:05 -07005935 mReqChannelCount(popcount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005936 mReqSampleRate(sampleRate)
5937 // mBytesRead is only meaningful while active, and so is cleared in start()
5938 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005939{
Glenn Kasten480b4682012-02-28 12:30:08 -08005940 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005941
Mathias Agopian65ab4712010-07-14 17:59:35 -07005942 readInputParameters();
5943}
5944
5945
5946AudioFlinger::RecordThread::~RecordThread()
5947{
5948 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005949 delete mResampler;
5950 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005951}
5952
5953void AudioFlinger::RecordThread::onFirstRef()
5954{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005955 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005956}
5957
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005958status_t AudioFlinger::RecordThread::readyToRun()
5959{
5960 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005961 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005962 return status;
5963}
5964
Mathias Agopian65ab4712010-07-14 17:59:35 -07005965bool AudioFlinger::RecordThread::threadLoop()
5966{
5967 AudioBufferProvider::Buffer buffer;
5968 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005969 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005970
Eric Laurent44d98482010-09-30 16:12:31 -07005971 nsecs_t lastWarning = 0;
5972
Glenn Kastene4e2a372012-07-23 12:55:09 -07005973 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07005974 acquireWakeLock();
5975
Mathias Agopian65ab4712010-07-14 17:59:35 -07005976 // start recording
5977 while (!exitPending()) {
5978
5979 processConfigEvents();
5980
5981 { // scope for mLock
5982 Mutex::Autolock _l(mLock);
5983 checkForNewParameters_l();
5984 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07005985 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005986
5987 if (exitPending()) break;
5988
Eric Laurentfeb0db62011-07-22 09:04:31 -07005989 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005990 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005991 // go to sleep
5992 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005993 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005994 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005995 continue;
5996 }
5997 if (mActiveTrack != 0) {
5998 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07005999 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006000 mActiveTrack.clear();
6001 mStartStopCond.broadcast();
6002 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6003 if (mReqChannelCount != mActiveTrack->channelCount()) {
6004 mActiveTrack.clear();
6005 mStartStopCond.broadcast();
6006 } else if (mBytesRead != 0) {
6007 // record start succeeds only if first read from audio input
6008 // succeeds
6009 if (mBytesRead > 0) {
6010 mActiveTrack->mState = TrackBase::ACTIVE;
6011 } else {
6012 mActiveTrack.clear();
6013 }
6014 mStartStopCond.broadcast();
6015 }
6016 mStandby = false;
6017 }
6018 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006019 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006020 }
6021
6022 if (mActiveTrack != 0) {
6023 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6024 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006025 unlockEffectChains(effectChains);
6026 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006027 continue;
6028 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006029 for (size_t i = 0; i < effectChains.size(); i ++) {
6030 effectChains[i]->process_l();
6031 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006032
Mathias Agopian65ab4712010-07-14 17:59:35 -07006033 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006034 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006035 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006036 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006037 // no resampling
6038 while (framesOut) {
6039 size_t framesIn = mFrameCount - mRsmpInIndex;
6040 if (framesIn) {
6041 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6042 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6043 if (framesIn > framesOut)
6044 framesIn = framesOut;
6045 mRsmpInIndex += framesIn;
6046 framesOut -= framesIn;
6047 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006048 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006049 memcpy(dst, src, framesIn * mFrameSize);
6050 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006051 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006052 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6053 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006054 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006055 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6056 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006057 }
6058 }
6059 }
6060 if (framesOut && mFrameCount == mRsmpInIndex) {
6061 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006062 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006063 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006064 framesOut = 0;
6065 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006066 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006067 mRsmpInIndex = 0;
6068 }
6069 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006070 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006071 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6072 // Force input into standby so that it tries to
6073 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006074 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006075 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006076 }
6077 mRsmpInIndex = mFrameCount;
6078 framesOut = 0;
6079 buffer.frameCount = 0;
6080 }
6081 }
6082 }
6083 } else {
6084 // resampling
6085
6086 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6087 // alter output frame count as if we were expecting stereo samples
6088 if (mChannelCount == 1 && mReqChannelCount == 1) {
6089 framesOut >>= 1;
6090 }
6091 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6092 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6093 // are 32 bit aligned which should be always true.
6094 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006095 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006096 // the resampler always outputs stereo samples: do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006097 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6098 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006099 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006100 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006101 }
6102
6103 }
Eric Laurenta011e352012-03-29 15:51:43 -07006104 if (mFramestoDrop == 0) {
6105 mActiveTrack->releaseBuffer(&buffer);
6106 } else {
6107 if (mFramestoDrop > 0) {
6108 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006109 if (mFramestoDrop <= 0) {
6110 clearSyncStartEvent();
6111 }
6112 } else {
6113 mFramestoDrop += buffer.frameCount;
6114 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6115 mSyncStartEvent->isCancelled()) {
6116 ALOGW("Synced record %s, session %d, trigger session %d",
6117 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6118 mActiveTrack->sessionId(),
6119 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6120 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006121 }
6122 }
6123 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006124 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006125 }
6126 // client isn't retrieving buffers fast enough
6127 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006128 if (!mActiveTrack->setOverflow()) {
6129 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006130 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006131 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006132 lastWarning = now;
6133 }
6134 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006135 // Release the processor for a while before asking for a new buffer.
6136 // This will give the application more chance to read from the buffer and
6137 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006138 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006139 }
6140 }
Eric Laurentec437d82011-07-26 20:54:46 -07006141 // enable changes in effect chain
6142 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006143 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006144 }
6145
Glenn Kastene4e2a372012-07-23 12:55:09 -07006146 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006147
Glenn Kasten33e6e352012-07-16 15:56:57 -07006148 {
6149 Mutex::Autolock _l(mLock);
6150 mActiveTrack.clear();
6151 mStartStopCond.broadcast();
6152 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006153
Eric Laurentfeb0db62011-07-22 09:04:31 -07006154 releaseWakeLock();
6155
Steve Block3856b092011-10-20 11:56:00 +01006156 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006157 return false;
6158}
6159
Glenn Kastene4e2a372012-07-23 12:55:09 -07006160void AudioFlinger::RecordThread::standby()
6161{
6162 if (!mStandby) {
6163 inputStandBy();
6164 mStandby = true;
6165 }
6166}
6167
6168void AudioFlinger::RecordThread::inputStandBy()
6169{
6170 mInput->stream->common.standby(&mInput->stream->common);
6171}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006172
6173sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6174 const sp<AudioFlinger::Client>& client,
6175 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006176 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006177 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006178 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006179 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006180 IAudioFlinger::track_flags_t flags,
6181 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006182 status_t *status)
6183{
6184 sp<RecordTrack> track;
6185 status_t lStatus;
6186
6187 lStatus = initCheck();
6188 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006189 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006190 goto Exit;
6191 }
6192
Glenn Kasten1879fff2012-07-11 15:36:59 -07006193 // FIXME use flags and tid similar to createTrack_l()
6194
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006195 { // scope for mLock
6196 Mutex::Autolock _l(mLock);
6197
6198 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006199 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006200
Glenn Kasten7378ca52012-01-20 13:44:40 -08006201 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006202 lStatus = NO_MEMORY;
6203 goto Exit;
6204 }
6205
6206 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006207 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006208 bool suspend = audio_is_bluetooth_sco_device(mDevice & AUDIO_DEVICE_IN_ALL) &&
6209 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006210 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6211 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006212 }
6213 lStatus = NO_ERROR;
6214
6215Exit:
6216 if (status) {
6217 *status = lStatus;
6218 }
6219 return track;
6220}
6221
Eric Laurenta011e352012-03-29 15:51:43 -07006222status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006223 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006224 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006225{
Glenn Kasten58912562012-04-03 10:45:00 -07006226 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006227 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006228 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006229
6230 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006231 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006232 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6233 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6234 triggerSession,
6235 recordTrack->sessionId(),
6236 syncStartEventCallback,
6237 this);
Eric Laurent29864602012-05-08 18:57:51 -07006238 // Sync event can be cancelled by the trigger session if the track is not in a
6239 // compatible state in which case we start record immediately
6240 if (mSyncStartEvent->isCancelled()) {
6241 clearSyncStartEvent();
6242 } else {
6243 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6244 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6245 }
Eric Laurenta011e352012-03-29 15:51:43 -07006246 }
6247
Mathias Agopian65ab4712010-07-14 17:59:35 -07006248 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006249 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006250 if (mActiveTrack != 0) {
6251 if (recordTrack != mActiveTrack.get()) {
6252 status = -EBUSY;
6253 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6254 mActiveTrack->mState = TrackBase::ACTIVE;
6255 }
6256 return status;
6257 }
6258
6259 recordTrack->mState = TrackBase::IDLE;
6260 mActiveTrack = recordTrack;
6261 mLock.unlock();
6262 status_t status = AudioSystem::startInput(mId);
6263 mLock.lock();
6264 if (status != NO_ERROR) {
6265 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006266 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006267 return status;
6268 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006269 mRsmpInIndex = mFrameCount;
6270 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006271 if (mResampler != NULL) {
6272 mResampler->reset();
6273 }
6274 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006275 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006276 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006277 mWaitWorkCV.signal();
6278 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006279 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006280 mActiveTrack.clear();
6281 status = INVALID_OPERATION;
6282 goto startError;
6283 }
6284 mStartStopCond.wait(mLock);
6285 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006286 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006287 status = BAD_VALUE;
6288 goto startError;
6289 }
Steve Block3856b092011-10-20 11:56:00 +01006290 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006291 return status;
6292 }
6293startError:
6294 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006295 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006296 return status;
6297}
6298
Eric Laurenta011e352012-03-29 15:51:43 -07006299void AudioFlinger::RecordThread::clearSyncStartEvent()
6300{
6301 if (mSyncStartEvent != 0) {
6302 mSyncStartEvent->cancel();
6303 }
6304 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006305 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006306}
6307
6308void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6309{
6310 sp<SyncEvent> strongEvent = event.promote();
6311
6312 if (strongEvent != 0) {
6313 RecordThread *me = (RecordThread *)strongEvent->cookie();
6314 me->handleSyncStartEvent(strongEvent);
6315 }
6316}
6317
6318void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6319{
Eric Laurent29864602012-05-08 18:57:51 -07006320 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006321 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6322 // from audio HAL
6323 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006324 }
6325}
6326
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006327bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006328 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006329 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
6330 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006331 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006332 recordTrack->mState = TrackBase::PAUSING;
6333 // do not wait for mStartStopCond if exiting
6334 if (exitPending()) {
6335 return true;
6336 }
6337 mStartStopCond.wait(mLock);
6338 // if we have been restarted, recordTrack == mActiveTrack.get() here
6339 if (exitPending() || recordTrack != mActiveTrack.get()) {
6340 ALOGV("Record stopped OK");
6341 return true;
6342 }
6343 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006344}
6345
Eric Laurenta011e352012-03-29 15:51:43 -07006346bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6347{
6348 return false;
6349}
6350
6351status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6352{
6353 if (!isValidSyncEvent(event)) {
6354 return BAD_VALUE;
6355 }
6356
6357 Mutex::Autolock _l(mLock);
6358
6359 if (mTrack != NULL && event->triggerSession() == mTrack->sessionId()) {
6360 mTrack->setSyncEvent(event);
6361 return NO_ERROR;
6362 }
6363 return NAME_NOT_FOUND;
6364}
6365
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07006366void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006367{
6368 const size_t SIZE = 256;
6369 char buffer[SIZE];
6370 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006371
6372 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6373 result.append(buffer);
6374
6375 if (mActiveTrack != 0) {
6376 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006377 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006378 mActiveTrack->dump(buffer, SIZE);
6379 result.append(buffer);
6380
6381 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6382 result.append(buffer);
6383 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6384 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006385 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006386 result.append(buffer);
6387 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6388 result.append(buffer);
6389 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6390 result.append(buffer);
6391
6392
6393 } else {
6394 result.append("No record client\n");
6395 }
6396 write(fd, result.string(), result.size());
6397
6398 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07006399 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006400}
6401
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006402// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006403status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006404{
6405 size_t framesReq = buffer->frameCount;
6406 size_t framesReady = mFrameCount - mRsmpInIndex;
6407 int channelCount;
6408
6409 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006410 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006411 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006412 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006413 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6414 // Force input into standby so that it tries to
6415 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006416 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006417 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006418 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006419 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006420 buffer->frameCount = 0;
6421 return NOT_ENOUGH_DATA;
6422 }
6423 mRsmpInIndex = 0;
6424 framesReady = mFrameCount;
6425 }
6426
6427 if (framesReq > framesReady) {
6428 framesReq = framesReady;
6429 }
6430
6431 if (mChannelCount == 1 && mReqChannelCount == 2) {
6432 channelCount = 1;
6433 } else {
6434 channelCount = 2;
6435 }
6436 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6437 buffer->frameCount = framesReq;
6438 return NO_ERROR;
6439}
6440
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006441// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006442void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6443{
6444 mRsmpInIndex += buffer->frameCount;
6445 buffer->frameCount = 0;
6446}
6447
6448bool AudioFlinger::RecordThread::checkForNewParameters_l()
6449{
6450 bool reconfig = false;
6451
6452 while (!mNewParameters.isEmpty()) {
6453 status_t status = NO_ERROR;
6454 String8 keyValuePair = mNewParameters[0];
6455 AudioParameter param = AudioParameter(keyValuePair);
6456 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006457 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006458 int reqSamplingRate = mReqSampleRate;
6459 int reqChannelCount = mReqChannelCount;
6460
6461 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6462 reqSamplingRate = value;
6463 reconfig = true;
6464 }
6465 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006466 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006467 reconfig = true;
6468 }
6469 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006470 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006471 reconfig = true;
6472 }
6473 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6474 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006475 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006476 // if frame count is changed after track creation
6477 if (mActiveTrack != 0) {
6478 status = INVALID_OPERATION;
6479 } else {
6480 reconfig = true;
6481 }
6482 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006483 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6484 // forward device change to effects that have requested to be
6485 // aware of attached audio device.
6486 for (size_t i = 0; i < mEffectChains.size(); i++) {
6487 mEffectChains[i]->setDevice_l(value);
6488 }
6489 // store input device and output device but do not forward output device to audio HAL.
6490 // Note that status is ignored by the caller for output device
6491 // (see AudioFlinger::setParameters()
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006492 audio_devices_t newDevice = mDevice;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006493 if (value & AUDIO_DEVICE_OUT_ALL) {
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006494 newDevice &= ~(value & AUDIO_DEVICE_OUT_ALL);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006495 status = BAD_VALUE;
6496 } else {
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006497 newDevice &= ~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006498 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6499 if (mTrack != NULL) {
6500 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006501 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006502 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
6503 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
6504 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006505 }
Glenn Kasten01542f22012-07-02 12:46:15 -07006506 newDevice |= value;
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006507 mDevice = newDevice; // since mDevice is read by other threads, only write to it once
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006508 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006509 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006510 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006511 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006512 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006513 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6514 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006515 }
6516 if (reconfig) {
6517 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006518 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006519 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006520 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006521 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6522 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006523 status = NO_ERROR;
6524 }
6525 if (status == NO_ERROR) {
6526 readInputParameters();
6527 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6528 }
6529 }
6530 }
6531
6532 mNewParameters.removeAt(0);
6533
6534 mParamStatus = status;
6535 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006536 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6537 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006538 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006539 }
6540 return reconfig;
6541}
6542
6543String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6544{
Dima Zavinfce7a472011-04-19 22:30:36 -07006545 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006546 String8 out_s8 = String8();
6547
6548 Mutex::Autolock _l(mLock);
6549 if (initCheck() != NO_ERROR) {
6550 return out_s8;
6551 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006552
Dima Zavin799a70e2011-04-18 16:57:27 -07006553 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006554 out_s8 = String8(s);
6555 free(s);
6556 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006557}
6558
6559void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6560 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006561 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006562
6563 switch (event) {
6564 case AudioSystem::INPUT_OPENED:
6565 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006566 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006567 desc.samplingRate = mSampleRate;
6568 desc.format = mFormat;
6569 desc.frameCount = mFrameCount;
6570 desc.latency = 0;
6571 param2 = &desc;
6572 break;
6573
6574 case AudioSystem::INPUT_CLOSED:
6575 default:
6576 break;
6577 }
6578 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6579}
6580
6581void AudioFlinger::RecordThread::readInputParameters()
6582{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006583 delete mRsmpInBuffer;
6584 // mRsmpInBuffer is always assigned a new[] below
6585 delete mRsmpOutBuffer;
6586 mRsmpOutBuffer = NULL;
6587 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006588 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006589
Dima Zavin799a70e2011-04-18 16:57:27 -07006590 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006591 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6592 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006593 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006594 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006595 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006596 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006597 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006598 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6599
Glenn Kasten53d76db2012-03-08 12:32:47 -08006600 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006601 {
6602 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006603 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6604 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006605 if (mChannelCount == 1 && mReqChannelCount == 2) {
6606 channelCount = 1;
6607 } else {
6608 channelCount = 2;
6609 }
6610 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6611 mResampler->setSampleRate(mSampleRate);
6612 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6613 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6614
6615 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6616 if (mChannelCount == 1 && mReqChannelCount == 1) {
6617 mFrameCount >>= 1;
6618 }
6619
6620 }
6621 mRsmpInIndex = mFrameCount;
6622}
6623
6624unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6625{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006626 Mutex::Autolock _l(mLock);
6627 if (initCheck() != NO_ERROR) {
6628 return 0;
6629 }
6630
Dima Zavin799a70e2011-04-18 16:57:27 -07006631 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006632}
6633
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006634uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6635{
6636 Mutex::Autolock _l(mLock);
6637 uint32_t result = 0;
6638 if (getEffectChain_l(sessionId) != 0) {
6639 result = EFFECT_SESSION;
6640 }
6641
6642 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
6643 result |= TRACK_SESSION;
6644 }
6645
6646 return result;
6647}
6648
Eric Laurent59bd0da2011-08-01 09:52:20 -07006649AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
6650{
6651 Mutex::Autolock _l(mLock);
6652 return mTrack;
6653}
6654
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006655AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6656{
6657 Mutex::Autolock _l(mLock);
6658 AudioStreamIn *input = mInput;
6659 mInput = NULL;
6660 return input;
6661}
6662
6663// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006664audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006665{
6666 if (mInput == NULL) {
6667 return NULL;
6668 }
6669 return &mInput->stream->common;
6670}
6671
6672
Mathias Agopian65ab4712010-07-14 17:59:35 -07006673// ----------------------------------------------------------------------------
6674
Eric Laurenta4c5a552012-03-29 10:12:40 -07006675audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6676{
6677 if (!settingsAllowed()) {
6678 return 0;
6679 }
6680 Mutex::Autolock _l(mLock);
6681 return loadHwModule_l(name);
6682}
6683
6684// loadHwModule_l() must be called with AudioFlinger::mLock held
6685audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6686{
6687 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6688 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6689 ALOGW("loadHwModule() module %s already loaded", name);
6690 return mAudioHwDevs.keyAt(i);
6691 }
6692 }
6693
Eric Laurenta4c5a552012-03-29 10:12:40 -07006694 audio_hw_device_t *dev;
6695
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006696 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006697 if (rc) {
6698 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6699 return 0;
6700 }
6701
6702 mHardwareStatus = AUDIO_HW_INIT;
6703 rc = dev->init_check(dev);
6704 mHardwareStatus = AUDIO_HW_IDLE;
6705 if (rc) {
6706 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6707 return 0;
6708 }
6709
John Grossman93d90682012-07-23 17:05:46 -07006710 // Check and cache this HAL's level of support for master mute and master
6711 // volume. If this is the first HAL opened, and it supports the get
6712 // methods, use the initial values provided by the HAL as the current
6713 // master mute and volume settings.
6714
6715 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
6716 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07006717 AutoMutex lock(mHardwareLock);
John Grossman93d90682012-07-23 17:05:46 -07006718
6719 if (0 == mAudioHwDevs.size()) {
6720 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6721 if (NULL != dev->get_master_volume) {
6722 float mv;
6723 if (OK == dev->get_master_volume(dev, &mv)) {
6724 mMasterVolume = mv;
6725 }
6726 }
6727
6728 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
6729 if (NULL != dev->get_master_mute) {
6730 bool mm;
6731 if (OK == dev->get_master_mute(dev, &mm)) {
6732 mMasterMute = mm;
6733 }
6734 }
6735 }
6736
Eric Laurenta4c5a552012-03-29 10:12:40 -07006737 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossman93d90682012-07-23 17:05:46 -07006738 if ((NULL != dev->set_master_volume) &&
6739 (OK == dev->set_master_volume(dev, mMasterVolume))) {
6740 flags = static_cast<AudioHwDevice::Flags>(flags |
6741 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
6742 }
6743
6744 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
6745 if ((NULL != dev->set_master_mute) &&
6746 (OK == dev->set_master_mute(dev, mMasterMute))) {
6747 flags = static_cast<AudioHwDevice::Flags>(flags |
6748 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
6749 }
6750
Eric Laurenta4c5a552012-03-29 10:12:40 -07006751 mHardwareStatus = AUDIO_HW_IDLE;
6752 }
6753
6754 audio_module_handle_t handle = nextUniqueId();
John Grossman93d90682012-07-23 17:05:46 -07006755 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07006756
6757 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006758 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006759
6760 return handle;
6761
6762}
6763
6764audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6765 audio_devices_t *pDevices,
6766 uint32_t *pSamplingRate,
6767 audio_format_t *pFormat,
6768 audio_channel_mask_t *pChannelMask,
6769 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006770 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006771{
6772 status_t status;
6773 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006774 struct audio_config config = {
6775 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6776 channel_mask: pChannelMask ? *pChannelMask : 0,
6777 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6778 };
6779 audio_stream_out_t *outStream = NULL;
John Grossman93d90682012-07-23 17:05:46 -07006780 AudioHwDevice *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006781
Eric Laurenta4c5a552012-03-29 10:12:40 -07006782 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6783 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006784 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006785 config.sample_rate,
6786 config.format,
6787 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006788 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006789
6790 if (pDevices == NULL || *pDevices == 0) {
6791 return 0;
6792 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006793
Mathias Agopian65ab4712010-07-14 17:59:35 -07006794 Mutex::Autolock _l(mLock);
6795
Eric Laurenta4c5a552012-03-29 10:12:40 -07006796 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006797 if (outHwDev == NULL)
6798 return 0;
6799
John Grossman93d90682012-07-23 17:05:46 -07006800 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006801 audio_io_handle_t id = nextUniqueId();
6802
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006803 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006804
John Grossman93d90682012-07-23 17:05:46 -07006805 status = hwDevHal->open_output_stream(hwDevHal,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006806 id,
6807 *pDevices,
6808 (audio_output_flags_t)flags,
6809 &config,
6810 &outStream);
6811
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006812 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006813 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006814 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006815 config.sample_rate,
6816 config.format,
6817 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006818 status);
6819
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006820 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006821 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006822
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006823 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006824 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6825 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006826 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006827 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006828 } else {
6829 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006830 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006831 }
6832 mPlaybackThreads.add(id, thread);
6833
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006834 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6835 if (pFormat != NULL) *pFormat = config.format;
6836 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006837 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006838
6839 // notify client processes of the new output creation
6840 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006841
6842 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006843 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006844 ALOGI("Using module %d has the primary audio interface", module);
6845 mPrimaryHardwareDev = outHwDev;
6846
6847 AutoMutex lock(mHardwareLock);
6848 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossman93d90682012-07-23 17:05:46 -07006849 hwDevHal->set_mode(hwDevHal, mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006850 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006851 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006852 return id;
6853 }
6854
6855 return 0;
6856}
6857
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006858audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6859 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006860{
6861 Mutex::Autolock _l(mLock);
6862 MixerThread *thread1 = checkMixerThread_l(output1);
6863 MixerThread *thread2 = checkMixerThread_l(output2);
6864
6865 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006866 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006867 return 0;
6868 }
6869
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006870 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006871 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6872 thread->addOutputTrack(thread2);
6873 mPlaybackThreads.add(id, thread);
6874 // notify client processes of the new output creation
6875 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6876 return id;
6877}
6878
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006879status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006880{
Glenn Kastend96c5722012-04-25 13:44:49 -07006881 return closeOutput_nonvirtual(output);
6882}
6883
6884status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
6885{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006886 // keep strong reference on the playback thread so that
6887 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006888 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006889 {
6890 Mutex::Autolock _l(mLock);
6891 thread = checkPlaybackThread_l(output);
6892 if (thread == NULL) {
6893 return BAD_VALUE;
6894 }
6895
Steve Block3856b092011-10-20 11:56:00 +01006896 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006897
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006898 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006899 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006900 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006901 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6902 dupThread->removeOutputTrack((MixerThread *)thread.get());
6903 }
6904 }
6905 }
Glenn Kastena1117922012-01-26 10:53:32 -08006906 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006907 mPlaybackThreads.removeItem(output);
6908 }
6909 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006910 // The thread entity (active unit of execution) is no longer running here,
6911 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006912
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006913 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006914 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08006915 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006916 // from now on thread->mOutput is NULL
John Grossman93d90682012-07-23 17:05:46 -07006917 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006918 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006919 }
6920 return NO_ERROR;
6921}
6922
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006923status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006924{
6925 Mutex::Autolock _l(mLock);
6926 PlaybackThread *thread = checkPlaybackThread_l(output);
6927
6928 if (thread == NULL) {
6929 return BAD_VALUE;
6930 }
6931
Steve Block3856b092011-10-20 11:56:00 +01006932 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006933 thread->suspend();
6934
6935 return NO_ERROR;
6936}
6937
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006938status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006939{
6940 Mutex::Autolock _l(mLock);
6941 PlaybackThread *thread = checkPlaybackThread_l(output);
6942
6943 if (thread == NULL) {
6944 return BAD_VALUE;
6945 }
6946
Steve Block3856b092011-10-20 11:56:00 +01006947 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006948
6949 thread->restore();
6950
6951 return NO_ERROR;
6952}
6953
Eric Laurenta4c5a552012-03-29 10:12:40 -07006954audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
6955 audio_devices_t *pDevices,
6956 uint32_t *pSamplingRate,
6957 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07006958 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006959{
6960 status_t status;
6961 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006962 struct audio_config config = {
6963 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6964 channel_mask: pChannelMask ? *pChannelMask : 0,
6965 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6966 };
6967 uint32_t reqSamplingRate = config.sample_rate;
6968 audio_format_t reqFormat = config.format;
6969 audio_channel_mask_t reqChannels = config.channel_mask;
6970 audio_stream_in_t *inStream = NULL;
John Grossman93d90682012-07-23 17:05:46 -07006971 AudioHwDevice *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006972
6973 if (pDevices == NULL || *pDevices == 0) {
6974 return 0;
6975 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006976
Mathias Agopian65ab4712010-07-14 17:59:35 -07006977 Mutex::Autolock _l(mLock);
6978
Eric Laurenta4c5a552012-03-29 10:12:40 -07006979 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006980 if (inHwDev == NULL)
6981 return 0;
6982
John Grossman93d90682012-07-23 17:05:46 -07006983 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006984 audio_io_handle_t id = nextUniqueId();
6985
John Grossman93d90682012-07-23 17:05:46 -07006986 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07006987 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006988 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006989 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006990 config.sample_rate,
6991 config.format,
6992 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006993 status);
6994
6995 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
6996 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
6997 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006998 if (status == BAD_VALUE &&
6999 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7000 (config.sample_rate <= 2 * reqSamplingRate) &&
7001 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007002 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007003 inStream = NULL;
John Grossman93d90682012-07-23 17:05:46 -07007004 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007005 }
7006
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007007 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007008 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7009
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007010 // Start record thread
7011 // RecorThread require both input and output device indication to forward to audio
7012 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007013 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007014 thread = new RecordThread(this,
7015 input,
7016 reqSamplingRate,
7017 reqChannels,
7018 id,
7019 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007020 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007021 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007022 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007023 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007024 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007025
Mathias Agopian65ab4712010-07-14 17:59:35 -07007026 // notify client processes of the new input creation
7027 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7028 return id;
7029 }
7030
7031 return 0;
7032}
7033
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007034status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007035{
Glenn Kastend96c5722012-04-25 13:44:49 -07007036 return closeInput_nonvirtual(input);
7037}
7038
7039status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7040{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007041 // keep strong reference on the record thread so that
7042 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007043 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007044 {
7045 Mutex::Autolock _l(mLock);
7046 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007047 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007048 return BAD_VALUE;
7049 }
7050
Steve Block3856b092011-10-20 11:56:00 +01007051 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007052 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007053 mRecordThreads.removeItem(input);
7054 }
7055 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007056 // The thread entity (active unit of execution) is no longer running here,
7057 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007058
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007059 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007060 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007061 // from now on thread->mInput is NULL
John Grossman93d90682012-07-23 17:05:46 -07007062 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007063 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007064
7065 return NO_ERROR;
7066}
7067
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007068status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007069{
7070 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007071 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007072
7073 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7074 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007075 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007076 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007077
7078 return NO_ERROR;
7079}
7080
7081
7082int AudioFlinger::newAudioSessionId()
7083{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007084 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007085}
7086
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007087void AudioFlinger::acquireAudioSessionId(int audioSession)
7088{
7089 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007090 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007091 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007092 size_t num = mAudioSessionRefs.size();
7093 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007094 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007095 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7096 ref->mCnt++;
7097 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007098 return;
7099 }
7100 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007101 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7102 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007103}
7104
7105void AudioFlinger::releaseAudioSessionId(int audioSession)
7106{
7107 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007108 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007109 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007110 size_t num = mAudioSessionRefs.size();
7111 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007112 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007113 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7114 ref->mCnt--;
7115 ALOGV(" decremented refcount to %d", ref->mCnt);
7116 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007117 mAudioSessionRefs.removeAt(i);
7118 delete ref;
7119 purgeStaleEffects_l();
7120 }
7121 return;
7122 }
7123 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007124 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007125}
7126
7127void AudioFlinger::purgeStaleEffects_l() {
7128
Steve Block3856b092011-10-20 11:56:00 +01007129 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007130
7131 Vector< sp<EffectChain> > chains;
7132
7133 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7134 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7135 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7136 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007137 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7138 chains.push(ec);
7139 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007140 }
7141 }
7142 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7143 sp<RecordThread> t = mRecordThreads.valueAt(i);
7144 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7145 sp<EffectChain> ec = t->mEffectChains[j];
7146 chains.push(ec);
7147 }
7148 }
7149
7150 for (size_t i = 0; i < chains.size(); i++) {
7151 sp<EffectChain> ec = chains[i];
7152 int sessionid = ec->sessionId();
7153 sp<ThreadBase> t = ec->mThread.promote();
7154 if (t == 0) {
7155 continue;
7156 }
7157 size_t numsessionrefs = mAudioSessionRefs.size();
7158 bool found = false;
7159 for (size_t k = 0; k < numsessionrefs; k++) {
7160 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007161 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007162 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007163 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007164 found = true;
7165 break;
7166 }
7167 }
7168 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007169 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007170 // remove all effects from the chain
7171 while (ec->mEffects.size()) {
7172 sp<EffectModule> effect = ec->mEffects[0];
7173 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007174 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007175 if (effect->purgeHandles()) {
7176 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007177 }
7178 AudioSystem::unregisterEffect(effect->id());
7179 }
7180 }
7181 }
7182 return;
7183}
7184
Mathias Agopian65ab4712010-07-14 17:59:35 -07007185// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007186AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007187{
Glenn Kastena1117922012-01-26 10:53:32 -08007188 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007189}
7190
7191// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007192AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007193{
7194 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007195 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007196}
7197
7198// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007199AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007200{
Glenn Kastena1117922012-01-26 10:53:32 -08007201 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007202}
7203
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007204uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007205{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007206 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007207}
7208
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007209AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007210{
7211 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7212 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007213 AudioStreamOut *output = thread->getOutput();
John Grossman93d90682012-07-23 17:05:46 -07007214 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007215 return thread;
7216 }
7217 }
7218 return NULL;
7219}
7220
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007221audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007222{
7223 PlaybackThread *thread = primaryPlaybackThread_l();
7224
7225 if (thread == NULL) {
7226 return 0;
7227 }
7228
7229 return thread->device();
7230}
7231
Eric Laurenta011e352012-03-29 15:51:43 -07007232sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7233 int triggerSession,
7234 int listenerSession,
7235 sync_event_callback_t callBack,
7236 void *cookie)
7237{
7238 Mutex::Autolock _l(mLock);
7239
7240 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7241 status_t playStatus = NAME_NOT_FOUND;
7242 status_t recStatus = NAME_NOT_FOUND;
7243 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7244 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7245 if (playStatus == NO_ERROR) {
7246 return event;
7247 }
7248 }
7249 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7250 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7251 if (recStatus == NO_ERROR) {
7252 return event;
7253 }
7254 }
7255 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7256 mPendingSyncEvents.add(event);
7257 } else {
7258 ALOGV("createSyncEvent() invalid event %d", event->type());
7259 event.clear();
7260 }
7261 return event;
7262}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007263
Mathias Agopian65ab4712010-07-14 17:59:35 -07007264// ----------------------------------------------------------------------------
7265// Effect management
7266// ----------------------------------------------------------------------------
7267
7268
Glenn Kastenf587ba52012-01-26 16:25:10 -08007269status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007270{
7271 Mutex::Autolock _l(mLock);
7272 return EffectQueryNumberEffects(numEffects);
7273}
7274
Glenn Kastenf587ba52012-01-26 16:25:10 -08007275status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007276{
7277 Mutex::Autolock _l(mLock);
7278 return EffectQueryEffect(index, descriptor);
7279}
7280
Glenn Kasten5e92a782012-01-30 07:40:52 -08007281status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007282 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007283{
7284 Mutex::Autolock _l(mLock);
7285 return EffectGetDescriptor(pUuid, descriptor);
7286}
7287
7288
Mathias Agopian65ab4712010-07-14 17:59:35 -07007289sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7290 effect_descriptor_t *pDesc,
7291 const sp<IEffectClient>& effectClient,
7292 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007293 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007294 int sessionId,
7295 status_t *status,
7296 int *id,
7297 int *enabled)
7298{
7299 status_t lStatus = NO_ERROR;
7300 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007301 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007302
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007303 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007304 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007305
7306 if (pDesc == NULL) {
7307 lStatus = BAD_VALUE;
7308 goto Exit;
7309 }
7310
Eric Laurent84e9a102010-09-23 16:10:16 -07007311 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007312 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007313 lStatus = PERMISSION_DENIED;
7314 goto Exit;
7315 }
7316
Dima Zavinfce7a472011-04-19 22:30:36 -07007317 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007318 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007319 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007320 lStatus = PERMISSION_DENIED;
7321 goto Exit;
7322 }
7323
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007324 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007325 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007326 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007327 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007328 lStatus = BAD_VALUE;
7329 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007330 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007331 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007332 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007333 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007334 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007335 }
7336 }
7337
Mathias Agopian65ab4712010-07-14 17:59:35 -07007338 {
7339 Mutex::Autolock _l(mLock);
7340
Mathias Agopian65ab4712010-07-14 17:59:35 -07007341
7342 if (!EffectIsNullUuid(&pDesc->uuid)) {
7343 // if uuid is specified, request effect descriptor
7344 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7345 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007346 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007347 goto Exit;
7348 }
7349 } else {
7350 // if uuid is not specified, look for an available implementation
7351 // of the required type in effect factory
7352 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007353 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007354 lStatus = BAD_VALUE;
7355 goto Exit;
7356 }
7357 uint32_t numEffects = 0;
7358 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007359 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007360 bool found = false;
7361
7362 lStatus = EffectQueryNumberEffects(&numEffects);
7363 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007364 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007365 goto Exit;
7366 }
7367 for (uint32_t i = 0; i < numEffects; i++) {
7368 lStatus = EffectQueryEffect(i, &desc);
7369 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007370 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007371 continue;
7372 }
7373 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7374 // If matching type found save effect descriptor. If the session is
7375 // 0 and the effect is not auxiliary, continue enumeration in case
7376 // an auxiliary version of this effect type is available
7377 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08007378 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07007379 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007380 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7381 break;
7382 }
7383 }
7384 }
7385 if (!found) {
7386 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007387 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007388 goto Exit;
7389 }
7390 // For same effect type, chose auxiliary version over insert version if
7391 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007392 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007393 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08007394 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007395 }
7396 }
7397
7398 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007399 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007400 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7401 lStatus = INVALID_OPERATION;
7402 goto Exit;
7403 }
7404
Eric Laurent59255e42011-07-27 19:49:51 -07007405 // check recording permission for visualizer
7406 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7407 !recordingAllowed()) {
7408 lStatus = PERMISSION_DENIED;
7409 goto Exit;
7410 }
7411
Mathias Agopian65ab4712010-07-14 17:59:35 -07007412 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08007413 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007414
7415 // If output is not specified try to find a matching audio session ID in one of the
7416 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007417 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7418 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007419 // Note: io is never 0 when creating an effect on an input
7420 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007421 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007422 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7423 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007424 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007425 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007426 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007427 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007428 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007429 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7430 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7431 io = mRecordThreads.keyAt(i);
7432 break;
7433 }
7434 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007435 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007436 // If no output thread contains the requested session ID, default to
7437 // first output. The effect chain will be moved to the correct output
7438 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007439 if (io == 0 && mPlaybackThreads.size()) {
7440 io = mPlaybackThreads.keyAt(0);
7441 }
Steve Block3856b092011-10-20 11:56:00 +01007442 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007443 }
7444 ThreadBase *thread = checkRecordThread_l(io);
7445 if (thread == NULL) {
7446 thread = checkPlaybackThread_l(io);
7447 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007448 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007449 lStatus = BAD_VALUE;
7450 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007451 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007452 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007453
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007454 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007455
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007456 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007457 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7458 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007459 if (handle != 0 && id != NULL) {
7460 *id = handle->id();
7461 }
7462 }
7463
7464Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007465 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007466 *status = lStatus;
7467 }
7468 return handle;
7469}
7470
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007471status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7472 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007473{
Steve Block3856b092011-10-20 11:56:00 +01007474 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007475 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007476 Mutex::Autolock _l(mLock);
7477 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007478 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007479 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007480 }
Eric Laurentde070132010-07-13 04:45:46 -07007481 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7482 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007483 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007484 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007485 }
Eric Laurentde070132010-07-13 04:45:46 -07007486 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7487 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007488 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007489 return BAD_VALUE;
7490 }
7491
7492 Mutex::Autolock _dl(dstThread->mLock);
7493 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007494 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007495
Mathias Agopian65ab4712010-07-14 17:59:35 -07007496 return NO_ERROR;
7497}
7498
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007499// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007500status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007501 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007502 AudioFlinger::PlaybackThread *dstThread,
7503 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007504{
Steve Block3856b092011-10-20 11:56:00 +01007505 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007506 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007507
Eric Laurent59255e42011-07-27 19:49:51 -07007508 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007509 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007510 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007511 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007512 return INVALID_OPERATION;
7513 }
7514
Eric Laurent39e94f82010-07-28 01:32:47 -07007515 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007516 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007517 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007518 // removed.
7519 srcThread->removeEffectChain_l(chain);
7520
7521 // transfer all effects one by one so that new effect chain is created on new thread with
7522 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007523 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007524 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007525 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007526 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7527 while (effect != 0) {
7528 srcThread->removeEffect_l(effect);
7529 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007530 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7531 if (effect->state() == EffectModule::ACTIVE ||
7532 effect->state() == EffectModule::STOPPING) {
7533 effect->start();
7534 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007535 // if the move request is not received from audio policy manager, the effect must be
7536 // re-registered with the new strategy and output
7537 if (dstChain == 0) {
7538 dstChain = effect->chain().promote();
7539 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007540 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007541 srcThread->addEffect_l(effect);
7542 return NO_INIT;
7543 }
7544 strategy = dstChain->strategy();
7545 }
7546 if (reRegister) {
7547 AudioSystem::unregisterEffect(effect->id());
7548 AudioSystem::registerEffect(&effect->desc(),
7549 dstOutput,
7550 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007551 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007552 effect->id());
7553 }
Eric Laurentde070132010-07-13 04:45:46 -07007554 effect = chain->getEffectFromId_l(0);
7555 }
7556
7557 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007558}
7559
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007560
Mathias Agopian65ab4712010-07-14 17:59:35 -07007561// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007562sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007563 const sp<AudioFlinger::Client>& client,
7564 const sp<IEffectClient>& effectClient,
7565 int32_t priority,
7566 int sessionId,
7567 effect_descriptor_t *desc,
7568 int *enabled,
7569 status_t *status
7570 )
7571{
7572 sp<EffectModule> effect;
7573 sp<EffectHandle> handle;
7574 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007575 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007576 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007577 bool effectCreated = false;
7578 bool effectRegistered = false;
7579
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007580 lStatus = initCheck();
7581 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007582 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007583 goto Exit;
7584 }
7585
7586 // Do not allow effects with session ID 0 on direct output or duplicating threads
7587 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007588 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007589 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007590 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007591 lStatus = BAD_VALUE;
7592 goto Exit;
7593 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007594 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007595 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007596 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007597 desc->name, desc->flags, mType);
7598 lStatus = BAD_VALUE;
7599 goto Exit;
7600 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007601
Steve Block3856b092011-10-20 11:56:00 +01007602 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007603
7604 { // scope for mLock
7605 Mutex::Autolock _l(mLock);
7606
7607 // check for existing effect chain with the requested audio session
7608 chain = getEffectChain_l(sessionId);
7609 if (chain == 0) {
7610 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007611 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007612 chain = new EffectChain(this, sessionId);
7613 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007614 chain->setStrategy(getStrategyForSession_l(sessionId));
7615 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007616 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007617 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007618 }
7619
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007620 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007621
7622 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007623 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007624 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007625 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007626 if (lStatus != NO_ERROR) {
7627 goto Exit;
7628 }
7629 effectRegistered = true;
7630 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007631 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007632 lStatus = effect->status();
7633 if (lStatus != NO_ERROR) {
7634 goto Exit;
7635 }
Eric Laurentcab11242010-07-15 12:50:15 -07007636 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007637 if (lStatus != NO_ERROR) {
7638 goto Exit;
7639 }
7640 effectCreated = true;
7641
7642 effect->setDevice(mDevice);
7643 effect->setMode(mAudioFlinger->getMode());
7644 }
7645 // create effect handle and connect it to effect module
7646 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007647 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007648 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007649 *enabled = (int)effect->isEnabled();
7650 }
7651 }
7652
7653Exit:
7654 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007655 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007656 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007657 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007658 }
7659 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007660 AudioSystem::unregisterEffect(effect->id());
7661 }
7662 if (chainCreated) {
7663 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007664 }
7665 handle.clear();
7666 }
7667
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007668 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007669 *status = lStatus;
7670 }
7671 return handle;
7672}
7673
Eric Laurent717e1282012-06-29 16:36:52 -07007674sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7675{
7676 Mutex::Autolock _l(mLock);
7677 return getEffect_l(sessionId, effectId);
7678}
7679
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007680sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7681{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007682 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007683 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007684}
7685
Eric Laurentde070132010-07-13 04:45:46 -07007686// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7687// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007688status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007689{
7690 // check for existing effect chain with the requested audio session
7691 int sessionId = effect->sessionId();
7692 sp<EffectChain> chain = getEffectChain_l(sessionId);
7693 bool chainCreated = false;
7694
7695 if (chain == 0) {
7696 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007697 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007698 chain = new EffectChain(this, sessionId);
7699 addEffectChain_l(chain);
7700 chain->setStrategy(getStrategyForSession_l(sessionId));
7701 chainCreated = true;
7702 }
Steve Block3856b092011-10-20 11:56:00 +01007703 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007704
7705 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007706 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007707 this, effect->desc().name, chain.get());
7708 return BAD_VALUE;
7709 }
7710
7711 status_t status = chain->addEffect_l(effect);
7712 if (status != NO_ERROR) {
7713 if (chainCreated) {
7714 removeEffectChain_l(chain);
7715 }
7716 return status;
7717 }
7718
7719 effect->setDevice(mDevice);
7720 effect->setMode(mAudioFlinger->getMode());
7721 return NO_ERROR;
7722}
7723
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007724void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007725
Steve Block3856b092011-10-20 11:56:00 +01007726 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007727 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007728 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7729 detachAuxEffect_l(effect->id());
7730 }
7731
7732 sp<EffectChain> chain = effect->chain().promote();
7733 if (chain != 0) {
7734 // remove effect chain if removing last effect
7735 if (chain->removeEffect_l(effect) == 0) {
7736 removeEffectChain_l(chain);
7737 }
7738 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007739 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007740 }
7741}
7742
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007743void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007744 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007745{
7746 effectChains = mEffectChains;
7747 for (size_t i = 0; i < mEffectChains.size(); i++) {
7748 mEffectChains[i]->lock();
7749 }
7750}
7751
7752void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007753 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007754{
7755 for (size_t i = 0; i < effectChains.size(); i++) {
7756 effectChains[i]->unlock();
7757 }
7758}
7759
7760sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7761{
7762 Mutex::Autolock _l(mLock);
7763 return getEffectChain_l(sessionId);
7764}
7765
7766sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7767{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007768 size_t size = mEffectChains.size();
7769 for (size_t i = 0; i < size; i++) {
7770 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007771 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007772 }
7773 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007774 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007775}
7776
Glenn Kastenf78aee72012-01-04 11:00:47 -08007777void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007778{
7779 Mutex::Autolock _l(mLock);
7780 size_t size = mEffectChains.size();
7781 for (size_t i = 0; i < size; i++) {
7782 mEffectChains[i]->setMode_l(mode);
7783 }
7784}
7785
7786void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007787 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007788 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007789
Mathias Agopian65ab4712010-07-14 17:59:35 -07007790 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007791 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007792 // delete the effect module if removing last handle on it
7793 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007794 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007795 removeEffect_l(effect);
7796 AudioSystem::unregisterEffect(effect->id());
7797 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007798 }
7799}
7800
7801status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7802{
7803 int session = chain->sessionId();
7804 int16_t *buffer = mMixBuffer;
7805 bool ownsBuffer = false;
7806
Steve Block3856b092011-10-20 11:56:00 +01007807 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007808 if (session > 0) {
7809 // Only one effect chain can be present in direct output thread and it uses
7810 // the mix buffer as input
7811 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007812 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007813 buffer = new int16_t[numSamples];
7814 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007815 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007816 ownsBuffer = true;
7817 }
7818
7819 // Attach all tracks with same session ID to this chain.
7820 for (size_t i = 0; i < mTracks.size(); ++i) {
7821 sp<Track> track = mTracks[i];
7822 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007823 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007824 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007825 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007826 }
7827 }
7828
7829 // indicate all active tracks in the chain
7830 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7831 sp<Track> track = mActiveTracks[i].promote();
7832 if (track == 0) continue;
7833 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007834 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007835 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007836 }
7837 }
7838 }
7839
7840 chain->setInBuffer(buffer, ownsBuffer);
7841 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007842 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007843 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007844 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7845 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007846 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007847 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7848 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007849 // Effect chain for other sessions are inserted at beginning of effect
7850 // chains list to be processed before output mix effects. Relative order between other
7851 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007852 size_t size = mEffectChains.size();
7853 size_t i = 0;
7854 for (i = 0; i < size; i++) {
7855 if (mEffectChains[i]->sessionId() < session) break;
7856 }
7857 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007858 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007859
7860 return NO_ERROR;
7861}
7862
7863size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7864{
7865 int session = chain->sessionId();
7866
Steve Block3856b092011-10-20 11:56:00 +01007867 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007868
7869 for (size_t i = 0; i < mEffectChains.size(); i++) {
7870 if (chain == mEffectChains[i]) {
7871 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007872 // detach all active tracks from the chain
7873 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7874 sp<Track> track = mActiveTracks[i].promote();
7875 if (track == 0) continue;
7876 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007877 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007878 chain.get(), session);
7879 chain->decActiveTrackCnt();
7880 }
7881 }
7882
Mathias Agopian65ab4712010-07-14 17:59:35 -07007883 // detach all tracks with same session ID from this chain
7884 for (size_t i = 0; i < mTracks.size(); ++i) {
7885 sp<Track> track = mTracks[i];
7886 if (session == track->sessionId()) {
7887 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007888 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007889 }
7890 }
Eric Laurentde070132010-07-13 04:45:46 -07007891 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007892 }
7893 }
7894 return mEffectChains.size();
7895}
7896
Eric Laurentde070132010-07-13 04:45:46 -07007897status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7898 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007899{
7900 Mutex::Autolock _l(mLock);
7901 return attachAuxEffect_l(track, EffectId);
7902}
7903
Eric Laurentde070132010-07-13 04:45:46 -07007904status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7905 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007906{
7907 status_t status = NO_ERROR;
7908
7909 if (EffectId == 0) {
7910 track->setAuxBuffer(0, NULL);
7911 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007912 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7913 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007914 if (effect != 0) {
7915 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7916 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
7917 } else {
7918 status = INVALID_OPERATION;
7919 }
7920 } else {
7921 status = BAD_VALUE;
7922 }
7923 }
7924 return status;
7925}
7926
7927void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
7928{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007929 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007930 sp<Track> track = mTracks[i];
7931 if (track->auxEffectId() == effectId) {
7932 attachAuxEffect_l(track, 0);
7933 }
7934 }
7935}
7936
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007937status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7938{
7939 // only one chain per input thread
7940 if (mEffectChains.size() != 0) {
7941 return INVALID_OPERATION;
7942 }
Steve Block3856b092011-10-20 11:56:00 +01007943 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007944
7945 chain->setInBuffer(NULL);
7946 chain->setOutBuffer(NULL);
7947
Eric Laurent59255e42011-07-27 19:49:51 -07007948 checkSuspendOnAddEffectChain_l(chain);
7949
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007950 mEffectChains.add(chain);
7951
7952 return NO_ERROR;
7953}
7954
7955size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7956{
Steve Block3856b092011-10-20 11:56:00 +01007957 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00007958 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007959 "removeEffectChain_l() %p invalid chain size %d on thread %p",
7960 chain.get(), mEffectChains.size(), this);
7961 if (mEffectChains.size() == 1) {
7962 mEffectChains.removeAt(0);
7963 }
7964 return 0;
7965}
7966
Mathias Agopian65ab4712010-07-14 17:59:35 -07007967// ----------------------------------------------------------------------------
7968// EffectModule implementation
7969// ----------------------------------------------------------------------------
7970
7971#undef LOG_TAG
7972#define LOG_TAG "AudioFlinger::EffectModule"
7973
Glenn Kasten9eaa5572012-01-20 13:32:16 -08007974AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007975 const wp<AudioFlinger::EffectChain>& chain,
7976 effect_descriptor_t *desc,
7977 int id,
7978 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07007979 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
7980 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07007981 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07007982 // mConfig is set by configure() and not used before then
7983 mEffectInterface(NULL),
7984 mStatus(NO_INIT), mState(IDLE),
7985 // mMaxDisableWaitCnt is set by configure() and not used before then
7986 // mDisableWaitCnt is set by process() and updateState() and not used before then
7987 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007988{
Steve Block3856b092011-10-20 11:56:00 +01007989 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007990 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007991
7992 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007993 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007994
7995 if (mStatus != NO_ERROR) {
7996 return;
7997 }
7998 lStatus = init();
7999 if (lStatus < 0) {
8000 mStatus = lStatus;
8001 goto Error;
8002 }
8003
Steve Block3856b092011-10-20 11:56:00 +01008004 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008005 return;
8006Error:
8007 EffectRelease(mEffectInterface);
8008 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008009 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008010}
8011
8012AudioFlinger::EffectModule::~EffectModule()
8013{
Steve Block3856b092011-10-20 11:56:00 +01008014 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008015 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008016 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8017 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8018 sp<ThreadBase> thread = mThread.promote();
8019 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008020 audio_stream_t *stream = thread->stream();
8021 if (stream != NULL) {
8022 stream->remove_audio_effect(stream, mEffectInterface);
8023 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008024 }
8025 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008026 // release effect engine
8027 EffectRelease(mEffectInterface);
8028 }
8029}
8030
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008031status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008032{
8033 status_t status;
8034
8035 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008036 int priority = handle->priority();
8037 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008038 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008039 size_t i;
8040 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008041 EffectHandle *h = mHandles[i];
8042 if (h == NULL || h->destroyed_l()) continue;
8043 // first non destroyed handle is considered in control
8044 if (controlHandle == NULL)
8045 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008046 if (h->priority() <= priority) break;
8047 }
8048 // if inserted in first place, move effect control from previous owner to this handle
8049 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008050 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008051 if (controlHandle != NULL) {
8052 enabled = controlHandle->enabled();
8053 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008054 }
Eric Laurent59255e42011-07-27 19:49:51 -07008055 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008056 status = NO_ERROR;
8057 } else {
8058 status = ALREADY_EXISTS;
8059 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008060 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008061 mHandles.insertAt(handle, i);
8062 return status;
8063}
8064
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008065size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008066{
8067 Mutex::Autolock _l(mLock);
8068 size_t size = mHandles.size();
8069 size_t i;
8070 for (i = 0; i < size; i++) {
8071 if (mHandles[i] == handle) break;
8072 }
8073 if (i == size) {
8074 return size;
8075 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008076 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008077
Mathias Agopian65ab4712010-07-14 17:59:35 -07008078 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008079 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008080 if (i == 0) {
8081 EffectHandle *h = controlHandle_l();
8082 if (h != NULL) {
8083 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008084 }
8085 }
8086
Eric Laurentec437d82011-07-26 20:54:46 -07008087 // Prevent calls to process() and other functions on effect interface from now on.
8088 // The effect engine will be released by the destructor when the last strong reference on
8089 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008090 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008091 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008092 }
8093
Eric Laurente65c8912012-07-20 15:57:23 -07008094 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008095}
8096
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008097// must be called with EffectModule::mLock held
8098AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008099{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008100 // the first valid handle in the list has control over the module
8101 for (size_t i = 0; i < mHandles.size(); i++) {
8102 EffectHandle *h = mHandles[i];
8103 if (h != NULL && !h->destroyed_l()) {
8104 return h;
8105 }
8106 }
8107
8108 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008109}
8110
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008111size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008112{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008113 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008114 // keep a strong reference on this EffectModule to avoid calling the
8115 // destructor before we exit
8116 sp<EffectModule> keep(this);
8117 {
8118 sp<ThreadBase> thread = mThread.promote();
8119 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008120 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008121 }
8122 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008123 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008124}
8125
8126void AudioFlinger::EffectModule::updateState() {
8127 Mutex::Autolock _l(mLock);
8128
8129 switch (mState) {
8130 case RESTART:
8131 reset_l();
8132 // FALL THROUGH
8133
8134 case STARTING:
8135 // clear auxiliary effect input buffer for next accumulation
8136 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8137 memset(mConfig.inputCfg.buffer.raw,
8138 0,
8139 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8140 }
8141 start_l();
8142 mState = ACTIVE;
8143 break;
8144 case STOPPING:
8145 stop_l();
8146 mDisableWaitCnt = mMaxDisableWaitCnt;
8147 mState = STOPPED;
8148 break;
8149 case STOPPED:
8150 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8151 // turn off sequence.
8152 if (--mDisableWaitCnt == 0) {
8153 reset_l();
8154 mState = IDLE;
8155 }
8156 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008157 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008158 break;
8159 }
8160}
8161
8162void AudioFlinger::EffectModule::process()
8163{
8164 Mutex::Autolock _l(mLock);
8165
Eric Laurentec437d82011-07-26 20:54:46 -07008166 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008167 mConfig.inputCfg.buffer.raw == NULL ||
8168 mConfig.outputCfg.buffer.raw == NULL) {
8169 return;
8170 }
8171
Eric Laurent8f45bd72010-08-31 13:50:07 -07008172 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008173 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8174 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008175 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008176 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008177 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008178 }
8179
8180 // do the actual processing in the effect engine
8181 int ret = (*mEffectInterface)->process(mEffectInterface,
8182 &mConfig.inputCfg.buffer,
8183 &mConfig.outputCfg.buffer);
8184
8185 // force transition to IDLE state when engine is ready
8186 if (mState == STOPPED && ret == -ENODATA) {
8187 mDisableWaitCnt = 1;
8188 }
8189
8190 // clear auxiliary effect input buffer for next accumulation
8191 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008192 memset(mConfig.inputCfg.buffer.raw, 0,
8193 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008194 }
8195 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008196 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8197 // If an insert effect is idle and input buffer is different from output buffer,
8198 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008199 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008200 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008201 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8202 int16_t *in = mConfig.inputCfg.buffer.s16;
8203 int16_t *out = mConfig.outputCfg.buffer.s16;
8204 for (size_t i = 0; i < frameCnt; i++) {
8205 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008206 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008207 }
8208 }
8209}
8210
8211void AudioFlinger::EffectModule::reset_l()
8212{
8213 if (mEffectInterface == NULL) {
8214 return;
8215 }
8216 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8217}
8218
8219status_t AudioFlinger::EffectModule::configure()
8220{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008221 if (mEffectInterface == NULL) {
8222 return NO_INIT;
8223 }
8224
8225 sp<ThreadBase> thread = mThread.promote();
8226 if (thread == 0) {
8227 return DEAD_OBJECT;
8228 }
8229
8230 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07008231 audio_channel_mask_t channelMask = thread->channelMask();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008232
8233 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008234 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008235 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07008236 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008237 }
Glenn Kasten254af182012-07-03 14:59:05 -07008238 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07008239 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8240 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008241 mConfig.inputCfg.samplingRate = thread->sampleRate();
8242 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8243 mConfig.inputCfg.bufferProvider.cookie = NULL;
8244 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8245 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8246 mConfig.outputCfg.bufferProvider.cookie = NULL;
8247 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8248 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8249 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8250 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008251 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008252 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008253 // - in other sessions:
8254 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8255 // other effect: overwrites output buffer: input buffer == output buffer
8256 // Auxiliary effect:
8257 // accumulates in output buffer: input buffer != output buffer
8258 // Therefore: accumulate <=> input buffer != output buffer
8259 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8260 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8261 } else {
8262 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8263 }
8264 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8265 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8266 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8267 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8268
Steve Block3856b092011-10-20 11:56:00 +01008269 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008270 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8271
Mathias Agopian65ab4712010-07-14 17:59:35 -07008272 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008273 uint32_t size = sizeof(int);
8274 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008275 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008276 sizeof(effect_config_t),
8277 &mConfig,
8278 &size,
8279 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008280 if (status == 0) {
8281 status = cmdStatus;
8282 }
8283
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008284 if (status == 0 &&
8285 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8286 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8287 effect_param_t *p = (effect_param_t *)buf32;
8288
8289 p->psize = sizeof(uint32_t);
8290 p->vsize = sizeof(uint32_t);
8291 size = sizeof(int);
8292 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8293
8294 uint32_t latency = 0;
8295 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8296 if (pbt != NULL) {
8297 latency = pbt->latency_l();
8298 }
8299
8300 *((int32_t *)p->data + 1)= latency;
8301 (*mEffectInterface)->command(mEffectInterface,
8302 EFFECT_CMD_SET_PARAM,
8303 sizeof(effect_param_t) + 8,
8304 &buf32,
8305 &size,
8306 &cmdStatus);
8307 }
8308
Mathias Agopian65ab4712010-07-14 17:59:35 -07008309 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8310 (1000 * mConfig.outputCfg.buffer.frameCount);
8311
8312 return status;
8313}
8314
8315status_t AudioFlinger::EffectModule::init()
8316{
8317 Mutex::Autolock _l(mLock);
8318 if (mEffectInterface == NULL) {
8319 return NO_INIT;
8320 }
8321 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008322 uint32_t size = sizeof(status_t);
8323 status_t status = (*mEffectInterface)->command(mEffectInterface,
8324 EFFECT_CMD_INIT,
8325 0,
8326 NULL,
8327 &size,
8328 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008329 if (status == 0) {
8330 status = cmdStatus;
8331 }
8332 return status;
8333}
8334
Eric Laurentec35a142011-10-05 17:42:25 -07008335status_t AudioFlinger::EffectModule::start()
8336{
8337 Mutex::Autolock _l(mLock);
8338 return start_l();
8339}
8340
Mathias Agopian65ab4712010-07-14 17:59:35 -07008341status_t AudioFlinger::EffectModule::start_l()
8342{
8343 if (mEffectInterface == NULL) {
8344 return NO_INIT;
8345 }
8346 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008347 uint32_t size = sizeof(status_t);
8348 status_t status = (*mEffectInterface)->command(mEffectInterface,
8349 EFFECT_CMD_ENABLE,
8350 0,
8351 NULL,
8352 &size,
8353 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008354 if (status == 0) {
8355 status = cmdStatus;
8356 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008357 if (status == 0 &&
8358 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8359 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8360 sp<ThreadBase> thread = mThread.promote();
8361 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008362 audio_stream_t *stream = thread->stream();
8363 if (stream != NULL) {
8364 stream->add_audio_effect(stream, mEffectInterface);
8365 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008366 }
8367 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008368 return status;
8369}
8370
Eric Laurentec437d82011-07-26 20:54:46 -07008371status_t AudioFlinger::EffectModule::stop()
8372{
8373 Mutex::Autolock _l(mLock);
8374 return stop_l();
8375}
8376
Mathias Agopian65ab4712010-07-14 17:59:35 -07008377status_t AudioFlinger::EffectModule::stop_l()
8378{
8379 if (mEffectInterface == NULL) {
8380 return NO_INIT;
8381 }
8382 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008383 uint32_t size = sizeof(status_t);
8384 status_t status = (*mEffectInterface)->command(mEffectInterface,
8385 EFFECT_CMD_DISABLE,
8386 0,
8387 NULL,
8388 &size,
8389 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008390 if (status == 0) {
8391 status = cmdStatus;
8392 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008393 if (status == 0 &&
8394 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8395 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8396 sp<ThreadBase> thread = mThread.promote();
8397 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008398 audio_stream_t *stream = thread->stream();
8399 if (stream != NULL) {
8400 stream->remove_audio_effect(stream, mEffectInterface);
8401 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008402 }
8403 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008404 return status;
8405}
8406
Eric Laurent25f43952010-07-28 05:40:18 -07008407status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8408 uint32_t cmdSize,
8409 void *pCmdData,
8410 uint32_t *replySize,
8411 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008412{
8413 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008414// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008415
Eric Laurentec437d82011-07-26 20:54:46 -07008416 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008417 return NO_INIT;
8418 }
Eric Laurent25f43952010-07-28 05:40:18 -07008419 status_t status = (*mEffectInterface)->command(mEffectInterface,
8420 cmdCode,
8421 cmdSize,
8422 pCmdData,
8423 replySize,
8424 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008425 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008426 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008427 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008428 EffectHandle *h = mHandles[i];
8429 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008430 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8431 }
8432 }
8433 }
8434 return status;
8435}
8436
8437status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8438{
8439 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008440 return setEnabled_l(enabled);
8441}
8442
8443// must be called with EffectModule::mLock held
8444status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8445{
8446
Steve Block3856b092011-10-20 11:56:00 +01008447 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008448
8449 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008450 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8451 if (enabled && status != NO_ERROR) {
8452 return status;
8453 }
8454
Mathias Agopian65ab4712010-07-14 17:59:35 -07008455 switch (mState) {
8456 // going from disabled to enabled
8457 case IDLE:
8458 mState = STARTING;
8459 break;
8460 case STOPPED:
8461 mState = RESTART;
8462 break;
8463 case STOPPING:
8464 mState = ACTIVE;
8465 break;
8466
8467 // going from enabled to disabled
8468 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008469 mState = STOPPED;
8470 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008471 case STARTING:
8472 mState = IDLE;
8473 break;
8474 case ACTIVE:
8475 mState = STOPPING;
8476 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008477 case DESTROYED:
8478 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008479 }
8480 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008481 EffectHandle *h = mHandles[i];
8482 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008483 h->setEnabled(enabled);
8484 }
8485 }
8486 }
8487 return NO_ERROR;
8488}
8489
Glenn Kastenc59c0042012-02-02 14:06:11 -08008490bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008491{
8492 switch (mState) {
8493 case RESTART:
8494 case STARTING:
8495 case ACTIVE:
8496 return true;
8497 case IDLE:
8498 case STOPPING:
8499 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008500 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008501 default:
8502 return false;
8503 }
8504}
8505
Glenn Kastenc59c0042012-02-02 14:06:11 -08008506bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008507{
8508 switch (mState) {
8509 case RESTART:
8510 case ACTIVE:
8511 case STOPPING:
8512 case STOPPED:
8513 return true;
8514 case IDLE:
8515 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008516 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008517 default:
8518 return false;
8519 }
8520}
8521
Mathias Agopian65ab4712010-07-14 17:59:35 -07008522status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8523{
8524 Mutex::Autolock _l(mLock);
8525 status_t status = NO_ERROR;
8526
8527 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8528 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008529 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008530 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8531 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008532 status_t cmdStatus;
8533 uint32_t volume[2];
8534 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008535 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008536 volume[0] = *left;
8537 volume[1] = *right;
8538 if (controller) {
8539 pVolume = volume;
8540 }
Eric Laurent25f43952010-07-28 05:40:18 -07008541 status = (*mEffectInterface)->command(mEffectInterface,
8542 EFFECT_CMD_SET_VOLUME,
8543 size,
8544 volume,
8545 &size,
8546 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008547 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8548 *left = volume[0];
8549 *right = volume[1];
8550 }
8551 }
8552 return status;
8553}
8554
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008555status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008556{
8557 Mutex::Autolock _l(mLock);
8558 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008559 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8560 // audio pre processing modules on RecordThread can receive both output and
8561 // input device indication in the same call
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008562 audio_devices_t dev = device & AUDIO_DEVICE_OUT_ALL;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008563 if (dev) {
8564 status_t cmdStatus;
8565 uint32_t size = sizeof(status_t);
8566
8567 status = (*mEffectInterface)->command(mEffectInterface,
8568 EFFECT_CMD_SET_DEVICE,
8569 sizeof(uint32_t),
8570 &dev,
8571 &size,
8572 &cmdStatus);
8573 if (status == NO_ERROR) {
8574 status = cmdStatus;
8575 }
8576 }
8577 dev = device & AUDIO_DEVICE_IN_ALL;
8578 if (dev) {
8579 status_t cmdStatus;
8580 uint32_t size = sizeof(status_t);
8581
8582 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8583 EFFECT_CMD_SET_INPUT_DEVICE,
8584 sizeof(uint32_t),
8585 &dev,
8586 &size,
8587 &cmdStatus);
8588 if (status2 == NO_ERROR) {
8589 status2 = cmdStatus;
8590 }
8591 if (status == NO_ERROR) {
8592 status = status2;
8593 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008594 }
8595 }
8596 return status;
8597}
8598
Glenn Kastenf78aee72012-01-04 11:00:47 -08008599status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008600{
8601 Mutex::Autolock _l(mLock);
8602 status_t status = NO_ERROR;
8603 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008604 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008605 uint32_t size = sizeof(status_t);
8606 status = (*mEffectInterface)->command(mEffectInterface,
8607 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008608 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008609 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008610 &size,
8611 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008612 if (status == NO_ERROR) {
8613 status = cmdStatus;
8614 }
8615 }
8616 return status;
8617}
8618
Eric Laurent59255e42011-07-27 19:49:51 -07008619void AudioFlinger::EffectModule::setSuspended(bool suspended)
8620{
8621 Mutex::Autolock _l(mLock);
8622 mSuspended = suspended;
8623}
Glenn Kastena3a85482012-01-04 11:01:11 -08008624
8625bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008626{
8627 Mutex::Autolock _l(mLock);
8628 return mSuspended;
8629}
8630
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008631bool AudioFlinger::EffectModule::purgeHandles()
8632{
8633 bool enabled = false;
8634 Mutex::Autolock _l(mLock);
8635 for (size_t i = 0; i < mHandles.size(); i++) {
8636 EffectHandle *handle = mHandles[i];
8637 if (handle != NULL && !handle->destroyed_l()) {
8638 handle->effect().clear();
8639 if (handle->hasControl()) {
8640 enabled = handle->enabled();
8641 }
8642 }
8643 }
8644 return enabled;
8645}
8646
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07008647void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008648{
8649 const size_t SIZE = 256;
8650 char buffer[SIZE];
8651 String8 result;
8652
8653 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8654 result.append(buffer);
8655
8656 bool locked = tryLock(mLock);
8657 // failed to lock - AudioFlinger is probably deadlocked
8658 if (!locked) {
8659 result.append("\t\tCould not lock Fx mutex:\n");
8660 }
8661
8662 result.append("\t\tSession Status State Engine:\n");
8663 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8664 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8665 result.append(buffer);
8666
8667 result.append("\t\tDescriptor:\n");
8668 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8669 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8670 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8671 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8672 result.append(buffer);
8673 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8674 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8675 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8676 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8677 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008678 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008679 mDescriptor.apiVersion,
8680 mDescriptor.flags);
8681 result.append(buffer);
8682 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8683 mDescriptor.name);
8684 result.append(buffer);
8685 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8686 mDescriptor.implementor);
8687 result.append(buffer);
8688
8689 result.append("\t\t- Input configuration:\n");
8690 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8691 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8692 (uint32_t)mConfig.inputCfg.buffer.raw,
8693 mConfig.inputCfg.buffer.frameCount,
8694 mConfig.inputCfg.samplingRate,
8695 mConfig.inputCfg.channels,
8696 mConfig.inputCfg.format);
8697 result.append(buffer);
8698
8699 result.append("\t\t- Output configuration:\n");
8700 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8701 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8702 (uint32_t)mConfig.outputCfg.buffer.raw,
8703 mConfig.outputCfg.buffer.frameCount,
8704 mConfig.outputCfg.samplingRate,
8705 mConfig.outputCfg.channels,
8706 mConfig.outputCfg.format);
8707 result.append(buffer);
8708
8709 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8710 result.append(buffer);
8711 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8712 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008713 EffectHandle *handle = mHandles[i];
8714 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008715 handle->dump(buffer, SIZE);
8716 result.append(buffer);
8717 }
8718 }
8719
8720 result.append("\n");
8721
8722 write(fd, result.string(), result.length());
8723
8724 if (locked) {
8725 mLock.unlock();
8726 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008727}
8728
8729// ----------------------------------------------------------------------------
8730// EffectHandle implementation
8731// ----------------------------------------------------------------------------
8732
8733#undef LOG_TAG
8734#define LOG_TAG "AudioFlinger::EffectHandle"
8735
8736AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8737 const sp<AudioFlinger::Client>& client,
8738 const sp<IEffectClient>& effectClient,
8739 int32_t priority)
8740 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008741 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008742 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008743{
Steve Block3856b092011-10-20 11:56:00 +01008744 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008745
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008746 if (client == 0) {
8747 return;
8748 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008749 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8750 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8751 if (mCblkMemory != 0) {
8752 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8753
Glenn Kastena0d68332012-01-27 16:47:15 -08008754 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008755 new(mCblk) effect_param_cblk_t();
8756 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008757 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008758 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008759 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008760 return;
8761 }
8762}
8763
8764AudioFlinger::EffectHandle::~EffectHandle()
8765{
Steve Block3856b092011-10-20 11:56:00 +01008766 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008767
8768 if (mEffect == 0) {
8769 mDestroyed = true;
8770 return;
8771 }
8772 mEffect->lock();
8773 mDestroyed = true;
8774 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008775 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008776}
8777
8778status_t AudioFlinger::EffectHandle::enable()
8779{
Steve Block3856b092011-10-20 11:56:00 +01008780 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008781 if (!mHasControl) return INVALID_OPERATION;
8782 if (mEffect == 0) return DEAD_OBJECT;
8783
Eric Laurentdb7c0792011-08-10 10:37:50 -07008784 if (mEnabled) {
8785 return NO_ERROR;
8786 }
8787
Eric Laurent59255e42011-07-27 19:49:51 -07008788 mEnabled = true;
8789
8790 sp<ThreadBase> thread = mEffect->thread().promote();
8791 if (thread != 0) {
8792 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8793 }
8794
8795 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8796 if (mEffect->suspended()) {
8797 return NO_ERROR;
8798 }
8799
Eric Laurentdb7c0792011-08-10 10:37:50 -07008800 status_t status = mEffect->setEnabled(true);
8801 if (status != NO_ERROR) {
8802 if (thread != 0) {
8803 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8804 }
8805 mEnabled = false;
8806 }
8807 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008808}
8809
8810status_t AudioFlinger::EffectHandle::disable()
8811{
Steve Block3856b092011-10-20 11:56:00 +01008812 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008813 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008814 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008815
Eric Laurentdb7c0792011-08-10 10:37:50 -07008816 if (!mEnabled) {
8817 return NO_ERROR;
8818 }
Eric Laurent59255e42011-07-27 19:49:51 -07008819 mEnabled = false;
8820
8821 if (mEffect->suspended()) {
8822 return NO_ERROR;
8823 }
8824
8825 status_t status = mEffect->setEnabled(false);
8826
8827 sp<ThreadBase> thread = mEffect->thread().promote();
8828 if (thread != 0) {
8829 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8830 }
8831
8832 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008833}
8834
8835void AudioFlinger::EffectHandle::disconnect()
8836{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008837 disconnect(true);
8838}
8839
Glenn Kasten58123c32012-02-03 10:32:24 -08008840void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008841{
Glenn Kasten58123c32012-02-03 10:32:24 -08008842 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008843 if (mEffect == 0) {
8844 return;
8845 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008846 // restore suspended effects if the disconnected handle was enabled and the last one.
8847 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008848 sp<ThreadBase> thread = mEffect->thread().promote();
8849 if (thread != 0) {
8850 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8851 }
Eric Laurent59255e42011-07-27 19:49:51 -07008852 }
8853
Mathias Agopian65ab4712010-07-14 17:59:35 -07008854 // release sp on module => module destructor can be called now
8855 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008856 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008857 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008858 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008859 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8860 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008861 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008862 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008863 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8864 mClient.clear();
8865 }
8866}
8867
Eric Laurent25f43952010-07-28 05:40:18 -07008868status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8869 uint32_t cmdSize,
8870 void *pCmdData,
8871 uint32_t *replySize,
8872 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008873{
Steve Block3856b092011-10-20 11:56:00 +01008874// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008875// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008876
8877 // only get parameter command is permitted for applications not controlling the effect
8878 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8879 return INVALID_OPERATION;
8880 }
8881 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008882 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008883
8884 // handle commands that are not forwarded transparently to effect engine
8885 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8886 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8887 // no risk to block the whole media server process or mixer threads is we are stuck here
8888 Mutex::Autolock _l(mCblk->lock);
8889 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8890 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8891 mCblk->serverIndex = 0;
8892 mCblk->clientIndex = 0;
8893 return BAD_VALUE;
8894 }
8895 status_t status = NO_ERROR;
8896 while (mCblk->serverIndex < mCblk->clientIndex) {
8897 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008898 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008899 int *p = (int *)(mBuffer + mCblk->serverIndex);
8900 int size = *p++;
8901 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008902 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008903 break;
8904 }
8905 effect_param_t *param = (effect_param_t *)p;
8906 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008907 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008908 mCblk->serverIndex += size;
8909 continue;
8910 }
Eric Laurent25f43952010-07-28 05:40:18 -07008911 uint32_t psize = sizeof(effect_param_t) +
8912 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8913 param->vsize;
8914 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
8915 psize,
8916 p,
8917 &rsize,
8918 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07008919 // stop at first error encountered
8920 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008921 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07008922 *(int *)pReplyData = reply;
8923 break;
8924 } else if (reply != NO_ERROR) {
8925 *(int *)pReplyData = reply;
8926 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008927 }
8928 mCblk->serverIndex += size;
8929 }
8930 mCblk->serverIndex = 0;
8931 mCblk->clientIndex = 0;
8932 return status;
8933 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008934 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008935 return enable();
8936 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07008937 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008938 return disable();
8939 }
8940
8941 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8942}
8943
Eric Laurent59255e42011-07-27 19:49:51 -07008944void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008945{
Steve Block3856b092011-10-20 11:56:00 +01008946 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008947
8948 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07008949 mEnabled = enabled;
8950
Mathias Agopian65ab4712010-07-14 17:59:35 -07008951 if (signal && mEffectClient != 0) {
8952 mEffectClient->controlStatusChanged(hasControl);
8953 }
8954}
8955
Eric Laurent25f43952010-07-28 05:40:18 -07008956void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
8957 uint32_t cmdSize,
8958 void *pCmdData,
8959 uint32_t replySize,
8960 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008961{
8962 if (mEffectClient != 0) {
8963 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
8964 }
8965}
8966
8967
8968
8969void AudioFlinger::EffectHandle::setEnabled(bool enabled)
8970{
8971 if (mEffectClient != 0) {
8972 mEffectClient->enableStatusChanged(enabled);
8973 }
8974}
8975
8976status_t AudioFlinger::EffectHandle::onTransact(
8977 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8978{
8979 return BnEffect::onTransact(code, data, reply, flags);
8980}
8981
8982
8983void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
8984{
Glenn Kastena0d68332012-01-27 16:47:15 -08008985 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008986
8987 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08008988 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07008989 mPriority,
8990 mHasControl,
8991 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008992 mCblk ? mCblk->clientIndex : 0,
8993 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07008994 );
8995
8996 if (locked) {
8997 mCblk->lock.unlock();
8998 }
8999}
9000
9001#undef LOG_TAG
9002#define LOG_TAG "AudioFlinger::EffectChain"
9003
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009004AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009005 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009006 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07009007 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9008 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009009{
Dima Zavinfce7a472011-04-19 22:30:36 -07009010 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009011 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009012 return;
9013 }
9014 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9015 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009016}
9017
9018AudioFlinger::EffectChain::~EffectChain()
9019{
9020 if (mOwnInBuffer) {
9021 delete mInBuffer;
9022 }
9023
9024}
9025
Eric Laurent59255e42011-07-27 19:49:51 -07009026// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009027sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009028{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009029 size_t size = mEffects.size();
9030
9031 for (size_t i = 0; i < size; i++) {
9032 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009033 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009034 }
9035 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009036 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009037}
9038
Eric Laurent59255e42011-07-27 19:49:51 -07009039// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009040sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009041{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009042 size_t size = mEffects.size();
9043
9044 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009045 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9046 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009047 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009048 }
9049 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009050 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009051}
9052
Eric Laurent59255e42011-07-27 19:49:51 -07009053// getEffectFromType_l() must be called with ThreadBase::mLock held
9054sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9055 const effect_uuid_t *type)
9056{
Eric Laurent59255e42011-07-27 19:49:51 -07009057 size_t size = mEffects.size();
9058
9059 for (size_t i = 0; i < size; i++) {
9060 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009061 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009062 }
9063 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009064 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009065}
9066
Eric Laurent91b14c42012-05-30 12:30:29 -07009067void AudioFlinger::EffectChain::clearInputBuffer()
9068{
9069 Mutex::Autolock _l(mLock);
9070 sp<ThreadBase> thread = mThread.promote();
9071 if (thread == 0) {
9072 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9073 return;
9074 }
9075 clearInputBuffer_l(thread);
9076}
9077
9078// Must be called with EffectChain::mLock locked
9079void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9080{
9081 size_t numSamples = thread->frameCount() * thread->channelCount();
9082 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9083
9084}
9085
Mathias Agopian65ab4712010-07-14 17:59:35 -07009086// Must be called with EffectChain::mLock locked
9087void AudioFlinger::EffectChain::process_l()
9088{
Eric Laurentdac69112010-09-28 14:09:57 -07009089 sp<ThreadBase> thread = mThread.promote();
9090 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009091 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009092 return;
9093 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009094 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9095 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009096 // always process effects unless no more tracks are on the session and the effect tail
9097 // has been rendered
9098 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009099 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009100 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009101
Eric Laurent544fe9b2011-11-11 15:42:52 -08009102 if (!tracksOnSession && mTailBufferCount == 0) {
9103 doProcess = false;
9104 }
9105
9106 if (activeTrackCnt() == 0) {
9107 // if no track is active and the effect tail has not been rendered,
9108 // the input buffer must be cleared here as the mixer process will not do it
9109 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009110 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009111 if (mTailBufferCount > 0) {
9112 mTailBufferCount--;
9113 }
9114 }
9115 }
Eric Laurentdac69112010-09-28 14:09:57 -07009116 }
9117
Mathias Agopian65ab4712010-07-14 17:59:35 -07009118 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009119 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009120 for (size_t i = 0; i < size; i++) {
9121 mEffects[i]->process();
9122 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009123 }
9124 for (size_t i = 0; i < size; i++) {
9125 mEffects[i]->updateState();
9126 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009127}
9128
Eric Laurentcab11242010-07-15 12:50:15 -07009129// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009130status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009131{
9132 effect_descriptor_t desc = effect->desc();
9133 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9134
9135 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009136 effect->setChain(this);
9137 sp<ThreadBase> thread = mThread.promote();
9138 if (thread == 0) {
9139 return NO_INIT;
9140 }
9141 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009142
9143 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9144 // Auxiliary effects are inserted at the beginning of mEffects vector as
9145 // they are processed first and accumulated in chain input buffer
9146 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009147
Mathias Agopian65ab4712010-07-14 17:59:35 -07009148 // the input buffer for auxiliary effect contains mono samples in
9149 // 32 bit format. This is to avoid saturation in AudoMixer
9150 // accumulation stage. Saturation is done in EffectModule::process() before
9151 // calling the process in effect engine
9152 size_t numSamples = thread->frameCount();
9153 int32_t *buffer = new int32_t[numSamples];
9154 memset(buffer, 0, numSamples * sizeof(int32_t));
9155 effect->setInBuffer((int16_t *)buffer);
9156 // auxiliary effects output samples to chain input buffer for further processing
9157 // by insert effects
9158 effect->setOutBuffer(mInBuffer);
9159 } else {
9160 // Insert effects are inserted at the end of mEffects vector as they are processed
9161 // after track and auxiliary effects.
9162 // Insert effect order as a function of indicated preference:
9163 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9164 // another effect is present
9165 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9166 // last effect claiming first position
9167 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9168 // first effect claiming last position
9169 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9170 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9171 // already present
9172
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009173 size_t size = mEffects.size();
9174 size_t idx_insert = size;
9175 ssize_t idx_insert_first = -1;
9176 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009177
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009178 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009179 effect_descriptor_t d = mEffects[i]->desc();
9180 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9181 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9182 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9183 // check invalid effect chaining combinations
9184 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9185 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009186 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009187 return INVALID_OPERATION;
9188 }
9189 // remember position of first insert effect and by default
9190 // select this as insert position for new effect
9191 if (idx_insert == size) {
9192 idx_insert = i;
9193 }
9194 // remember position of last insert effect claiming
9195 // first position
9196 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9197 idx_insert_first = i;
9198 }
9199 // remember position of first insert effect claiming
9200 // last position
9201 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9202 idx_insert_last == -1) {
9203 idx_insert_last = i;
9204 }
9205 }
9206 }
9207
9208 // modify idx_insert from first position if needed
9209 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9210 if (idx_insert_last != -1) {
9211 idx_insert = idx_insert_last;
9212 } else {
9213 idx_insert = size;
9214 }
9215 } else {
9216 if (idx_insert_first != -1) {
9217 idx_insert = idx_insert_first + 1;
9218 }
9219 }
9220
9221 // always read samples from chain input buffer
9222 effect->setInBuffer(mInBuffer);
9223
9224 // if last effect in the chain, output samples to chain
9225 // output buffer, otherwise to chain input buffer
9226 if (idx_insert == size) {
9227 if (idx_insert != 0) {
9228 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9229 mEffects[idx_insert-1]->configure();
9230 }
9231 effect->setOutBuffer(mOutBuffer);
9232 } else {
9233 effect->setOutBuffer(mInBuffer);
9234 }
9235 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009236
Steve Block3856b092011-10-20 11:56:00 +01009237 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009238 }
9239 effect->configure();
9240 return NO_ERROR;
9241}
9242
Eric Laurentcab11242010-07-15 12:50:15 -07009243// removeEffect_l() must be called with PlaybackThread::mLock held
9244size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009245{
9246 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009247 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009248 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9249
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009250 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009251 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009252 // calling stop here will remove pre-processing effect from the audio HAL.
9253 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9254 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009255 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9256 mEffects[i]->state() == EffectModule::STOPPING) {
9257 mEffects[i]->stop();
9258 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009259 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9260 delete[] effect->inBuffer();
9261 } else {
9262 if (i == size - 1 && i != 0) {
9263 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9264 mEffects[i - 1]->configure();
9265 }
9266 }
9267 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009268 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009269 break;
9270 }
9271 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009272
9273 return mEffects.size();
9274}
9275
Eric Laurentcab11242010-07-15 12:50:15 -07009276// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009277void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009278{
9279 size_t size = mEffects.size();
9280 for (size_t i = 0; i < size; i++) {
9281 mEffects[i]->setDevice(device);
9282 }
9283}
9284
Eric Laurentcab11242010-07-15 12:50:15 -07009285// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009286void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009287{
9288 size_t size = mEffects.size();
9289 for (size_t i = 0; i < size; i++) {
9290 mEffects[i]->setMode(mode);
9291 }
9292}
9293
Eric Laurentcab11242010-07-15 12:50:15 -07009294// setVolume_l() must be called with PlaybackThread::mLock held
9295bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009296{
9297 uint32_t newLeft = *left;
9298 uint32_t newRight = *right;
9299 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009300 int ctrlIdx = -1;
9301 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009302
Eric Laurentcab11242010-07-15 12:50:15 -07009303 // first update volume controller
9304 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009305 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009306 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9307 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009308 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009309 break;
9310 }
9311 }
9312
9313 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009314 if (hasControl) {
9315 *left = mNewLeftVolume;
9316 *right = mNewRightVolume;
9317 }
9318 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009319 }
9320
9321 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009322 mLeftVolume = newLeft;
9323 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009324
9325 // second get volume update from volume controller
9326 if (ctrlIdx >= 0) {
9327 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009328 mNewLeftVolume = newLeft;
9329 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009330 }
9331 // then indicate volume to all other effects in chain.
9332 // Pass altered volume to effects before volume controller
9333 // and requested volume to effects after controller
9334 uint32_t lVol = newLeft;
9335 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009336
Mathias Agopian65ab4712010-07-14 17:59:35 -07009337 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009338 if ((int)i == ctrlIdx) continue;
9339 // this also works for ctrlIdx == -1 when there is no volume controller
9340 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009341 lVol = *left;
9342 rVol = *right;
9343 }
9344 mEffects[i]->setVolume(&lVol, &rVol, false);
9345 }
9346 *left = newLeft;
9347 *right = newRight;
9348
9349 return hasControl;
9350}
9351
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009352void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009353{
9354 const size_t SIZE = 256;
9355 char buffer[SIZE];
9356 String8 result;
9357
9358 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9359 result.append(buffer);
9360
9361 bool locked = tryLock(mLock);
9362 // failed to lock - AudioFlinger is probably deadlocked
9363 if (!locked) {
9364 result.append("\tCould not lock mutex:\n");
9365 }
9366
Eric Laurentcab11242010-07-15 12:50:15 -07009367 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9368 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009369 mEffects.size(),
9370 (uint32_t)mInBuffer,
9371 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009372 mActiveTrackCnt);
9373 result.append(buffer);
9374 write(fd, result.string(), result.size());
9375
9376 for (size_t i = 0; i < mEffects.size(); ++i) {
9377 sp<EffectModule> effect = mEffects[i];
9378 if (effect != 0) {
9379 effect->dump(fd, args);
9380 }
9381 }
9382
9383 if (locked) {
9384 mLock.unlock();
9385 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009386}
9387
Eric Laurent59255e42011-07-27 19:49:51 -07009388// must be called with ThreadBase::mLock held
9389void AudioFlinger::EffectChain::setEffectSuspended_l(
9390 const effect_uuid_t *type, bool suspend)
9391{
9392 sp<SuspendedEffectDesc> desc;
9393 // use effect type UUID timelow as key as there is no real risk of identical
9394 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009395 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009396 if (suspend) {
9397 if (index >= 0) {
9398 desc = mSuspendedEffects.valueAt(index);
9399 } else {
9400 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -08009401 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07009402 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009403 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009404 }
9405 if (desc->mRefCount++ == 0) {
9406 sp<EffectModule> effect = getEffectIfEnabled(type);
9407 if (effect != 0) {
9408 desc->mEffect = effect;
9409 effect->setSuspended(true);
9410 effect->setEnabled(false);
9411 }
9412 }
9413 } else {
9414 if (index < 0) {
9415 return;
9416 }
9417 desc = mSuspendedEffects.valueAt(index);
9418 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009419 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009420 desc->mRefCount = 1;
9421 }
9422 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009423 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009424 if (desc->mEffect != 0) {
9425 sp<EffectModule> effect = desc->mEffect.promote();
9426 if (effect != 0) {
9427 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009428 effect->lock();
9429 EffectHandle *handle = effect->controlHandle_l();
9430 if (handle != NULL && !handle->destroyed_l()) {
9431 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009432 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009433 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009434 }
9435 desc->mEffect.clear();
9436 }
9437 mSuspendedEffects.removeItemsAt(index);
9438 }
9439 }
9440}
9441
9442// must be called with ThreadBase::mLock held
9443void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9444{
9445 sp<SuspendedEffectDesc> desc;
9446
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009447 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009448 if (suspend) {
9449 if (index >= 0) {
9450 desc = mSuspendedEffects.valueAt(index);
9451 } else {
9452 desc = new SuspendedEffectDesc();
9453 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009454 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009455 }
9456 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009457 Vector< sp<EffectModule> > effects;
9458 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009459 for (size_t i = 0; i < effects.size(); i++) {
9460 setEffectSuspended_l(&effects[i]->desc().type, true);
9461 }
9462 }
9463 } else {
9464 if (index < 0) {
9465 return;
9466 }
9467 desc = mSuspendedEffects.valueAt(index);
9468 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009469 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009470 desc->mRefCount = 1;
9471 }
9472 if (--desc->mRefCount == 0) {
9473 Vector<const effect_uuid_t *> types;
9474 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9475 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9476 continue;
9477 }
9478 types.add(&mSuspendedEffects.valueAt(i)->mType);
9479 }
9480 for (size_t i = 0; i < types.size(); i++) {
9481 setEffectSuspended_l(types[i], false);
9482 }
Steve Block3856b092011-10-20 11:56:00 +01009483 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009484 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9485 }
9486 }
9487}
9488
Eric Laurent6bffdb82011-09-23 08:40:41 -07009489
9490// The volume effect is used for automated tests only
9491#ifndef OPENSL_ES_H_
9492static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9493 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9494const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9495#endif //OPENSL_ES_H_
9496
Eric Laurentdb7c0792011-08-10 10:37:50 -07009497bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9498{
9499 // auxiliary effects and visualizer are never suspended on output mix
9500 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9501 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009502 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9503 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009504 return false;
9505 }
9506 return true;
9507}
9508
Glenn Kastend0539712012-01-30 12:56:03 -08009509void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009510{
Glenn Kastend0539712012-01-30 12:56:03 -08009511 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009512 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009513 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9514 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009515 }
Eric Laurent59255e42011-07-27 19:49:51 -07009516 }
Eric Laurent59255e42011-07-27 19:49:51 -07009517}
9518
9519sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9520 const effect_uuid_t *type)
9521{
Glenn Kasten090f0192012-01-30 13:00:02 -08009522 sp<EffectModule> effect = getEffectFromType_l(type);
9523 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009524}
9525
9526void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9527 bool enabled)
9528{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009529 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009530 if (enabled) {
9531 if (index < 0) {
9532 // if the effect is not suspend check if all effects are suspended
9533 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9534 if (index < 0) {
9535 return;
9536 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009537 if (!isEffectEligibleForSuspend(effect->desc())) {
9538 return;
9539 }
Eric Laurent59255e42011-07-27 19:49:51 -07009540 setEffectSuspended_l(&effect->desc().type, enabled);
9541 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009542 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009543 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009544 return;
9545 }
Eric Laurent59255e42011-07-27 19:49:51 -07009546 }
Steve Block3856b092011-10-20 11:56:00 +01009547 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009548 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009549 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9550 // if effect is requested to suspended but was not yet enabled, supend it now.
9551 if (desc->mEffect == 0) {
9552 desc->mEffect = effect;
9553 effect->setEnabled(false);
9554 effect->setSuspended(true);
9555 }
9556 } else {
9557 if (index < 0) {
9558 return;
9559 }
Steve Block3856b092011-10-20 11:56:00 +01009560 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009561 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009562 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9563 desc->mEffect.clear();
9564 effect->setSuspended(false);
9565 }
9566}
9567
Mathias Agopian65ab4712010-07-14 17:59:35 -07009568#undef LOG_TAG
9569#define LOG_TAG "AudioFlinger"
9570
9571// ----------------------------------------------------------------------------
9572
9573status_t AudioFlinger::onTransact(
9574 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9575{
9576 return BnAudioFlinger::onTransact(code, data, reply, flags);
9577}
9578
Mathias Agopian65ab4712010-07-14 17:59:35 -07009579}; // namespace android