blob: 41ae70e3a9aed3d11d07e685a4895da8c4a5d393 [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),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700219 mMasterVolumeSW(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800220 mMasterVolumeSupportLvl(MVS_NONE),
221 mMasterMute(false),
John Grossmand8f178d2012-07-20 14:51:35 -0700222 mMasterMuteSW(false),
223 mMasterMuteSupportLvl(MMS_NONE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800224 mNextUniqueId(1),
225 mMode(AUDIO_MODE_INVALID),
226 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700227{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700228}
229
230void AudioFlinger::onFirstRef()
231{
Dima Zavin799a70e2011-04-18 16:57:27 -0700232 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700233
Eric Laurent93575202011-01-18 18:39:02 -0800234 Mutex::Autolock _l(mLock);
235
Dima Zavin799a70e2011-04-18 16:57:27 -0700236 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800237 char val_str[PROPERTY_VALUE_MAX] = { 0 };
238 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
239 uint32_t int_val;
240 if (1 == sscanf(val_str, "%u", &int_val)) {
241 mStandbyTimeInNsecs = milliseconds(int_val);
242 ALOGI("Using %u mSec as standby time.", int_val);
243 } else {
244 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
245 ALOGI("Using default %u mSec as standby time.",
246 (uint32_t)(mStandbyTimeInNsecs / 1000000));
247 }
248 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700249
Eric Laurenta4c5a552012-03-29 10:12:40 -0700250 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700251}
252
253AudioFlinger::~AudioFlinger()
254{
255 while (!mRecordThreads.isEmpty()) {
256 // closeInput() will remove first entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700257 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700258 }
259 while (!mPlaybackThreads.isEmpty()) {
260 // closeOutput() will remove first entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700261 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700262 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700263
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800264 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
265 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700266 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
267 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700268 }
269}
270
Eric Laurenta4c5a552012-03-29 10:12:40 -0700271static const char * const audio_interfaces[] = {
272 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
273 AUDIO_HARDWARE_MODULE_ID_A2DP,
274 AUDIO_HARDWARE_MODULE_ID_USB,
275};
276#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
277
Glenn Kastenbb4350d2012-07-03 15:56:38 -0700278audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(audio_module_handle_t module, audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700279{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700280 // if module is 0, the request comes from an old policy manager and we should load
281 // well known modules
282 if (module == 0) {
283 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
284 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
285 loadHwModule_l(audio_interfaces[i]);
286 }
287 } else {
288 // check a match for the requested module handle
289 AudioHwDevice *audioHwdevice = mAudioHwDevs.valueFor(module);
290 if (audioHwdevice != NULL) {
291 return audioHwdevice->hwDevice();
292 }
293 }
294 // then try to find a module supporting the requested device.
Dima Zavin799a70e2011-04-18 16:57:27 -0700295 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700296 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700297 if ((dev->get_supported_devices(dev) & devices) == devices)
298 return dev;
299 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700300
Dima Zavin799a70e2011-04-18 16:57:27 -0700301 return NULL;
302}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700303
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700304void AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700305{
306 const size_t SIZE = 256;
307 char buffer[SIZE];
308 String8 result;
309
310 result.append("Clients:\n");
311 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800312 sp<Client> client = mClients.valueAt(i).promote();
313 if (client != 0) {
314 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
315 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700316 }
317 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700318
319 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800320 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700321 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
322 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800323 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700324 result.append(buffer);
325 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700326 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700327}
328
329
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700330void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700331{
332 const size_t SIZE = 256;
333 char buffer[SIZE];
334 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800335 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700336
John Grossman4ff14ba2012-02-08 16:37:41 -0800337 snprintf(buffer, SIZE, "Hardware status: %d\n"
338 "Standby Time mSec: %u\n",
339 hardwareStatus,
340 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700341 result.append(buffer);
342 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700343}
344
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700345void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700346{
347 const size_t SIZE = 256;
348 char buffer[SIZE];
349 String8 result;
350 snprintf(buffer, SIZE, "Permission Denial: "
351 "can't dump AudioFlinger from pid=%d, uid=%d\n",
352 IPCThreadState::self()->getCallingPid(),
353 IPCThreadState::self()->getCallingUid());
354 result.append(buffer);
355 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700356}
357
358static bool tryLock(Mutex& mutex)
359{
360 bool locked = false;
361 for (int i = 0; i < kDumpLockRetries; ++i) {
362 if (mutex.tryLock() == NO_ERROR) {
363 locked = true;
364 break;
365 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800366 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700367 }
368 return locked;
369}
370
371status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
372{
Glenn Kasten44deb052012-02-05 18:09:08 -0800373 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700374 dumpPermissionDenial(fd, args);
375 } else {
376 // get state of hardware lock
377 bool hardwareLocked = tryLock(mHardwareLock);
378 if (!hardwareLocked) {
379 String8 result(kHardwareLockedString);
380 write(fd, result.string(), result.size());
381 } else {
382 mHardwareLock.unlock();
383 }
384
385 bool locked = tryLock(mLock);
386
387 // failed to lock - AudioFlinger is probably deadlocked
388 if (!locked) {
389 String8 result(kDeadlockedString);
390 write(fd, result.string(), result.size());
391 }
392
393 dumpClients(fd, args);
394 dumpInternals(fd, args);
395
396 // dump playback threads
397 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
398 mPlaybackThreads.valueAt(i)->dump(fd, args);
399 }
400
401 // dump record threads
402 for (size_t i = 0; i < mRecordThreads.size(); i++) {
403 mRecordThreads.valueAt(i)->dump(fd, args);
404 }
405
Dima Zavin799a70e2011-04-18 16:57:27 -0700406 // dump all hardware devs
407 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700408 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700409 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700410 }
411 if (locked) mLock.unlock();
412 }
413 return NO_ERROR;
414}
415
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800416sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
417{
418 // If pid is already in the mClients wp<> map, then use that entry
419 // (for which promote() is always != 0), otherwise create a new entry and Client.
420 sp<Client> client = mClients.valueFor(pid).promote();
421 if (client == 0) {
422 client = new Client(this, pid);
423 mClients.add(pid, client);
424 }
425
426 return client;
427}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700428
429// IAudioFlinger interface
430
431
432sp<IAudioTrack> AudioFlinger::createTrack(
433 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800434 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700435 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800436 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700437 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700438 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800439 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700440 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800441 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800442 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700443 int *sessionId,
444 status_t *status)
445{
446 sp<PlaybackThread::Track> track;
447 sp<TrackHandle> trackHandle;
448 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700449 status_t lStatus;
450 int lSessionId;
451
Glenn Kasten263709e2012-01-06 08:40:01 -0800452 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
453 // but if someone uses binder directly they could bypass that and cause us to crash
454 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000455 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700456 lStatus = BAD_VALUE;
457 goto Exit;
458 }
459
460 {
461 Mutex::Autolock _l(mLock);
462 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700463 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700464 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000465 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700466 lStatus = BAD_VALUE;
467 goto Exit;
468 }
469
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800470 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700471
Steve Block3856b092011-10-20 11:56:00 +0100472 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700473 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700474 // check if an effect chain with the same session ID is present on another
475 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700476 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700477 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
478 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700479 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700480 if (sessions & PlaybackThread::EFFECT_SESSION) {
481 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700482 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700483 }
Eric Laurentde070132010-07-13 04:45:46 -0700484 }
485 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700486 lSessionId = *sessionId;
487 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700488 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700489 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700490 if (sessionId != NULL) {
491 *sessionId = lSessionId;
492 }
493 }
Steve Block3856b092011-10-20 11:56:00 +0100494 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700495
496 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800497 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700498
499 // move effect chain to this output thread if an effect on same session was waiting
500 // for a track to be created
501 if (lStatus == NO_ERROR && effectThread != NULL) {
502 Mutex::Autolock _dl(thread->mLock);
503 Mutex::Autolock _sl(effectThread->mLock);
504 moveEffectChain_l(lSessionId, effectThread, thread, true);
505 }
Eric Laurenta011e352012-03-29 15:51:43 -0700506
507 // Look for sync events awaiting for a session to be used.
508 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
509 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
510 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700511 if (lStatus == NO_ERROR) {
512 track->setSyncEvent(mPendingSyncEvents[i]);
513 } else {
514 mPendingSyncEvents[i]->cancel();
515 }
Eric Laurenta011e352012-03-29 15:51:43 -0700516 mPendingSyncEvents.removeAt(i);
517 i--;
518 }
519 }
520 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700521 }
522 if (lStatus == NO_ERROR) {
523 trackHandle = new TrackHandle(track);
524 } else {
525 // remove local strong reference to Client before deleting the Track so that the Client
526 // destructor is called by the TrackBase destructor with mLock held
527 client.clear();
528 track.clear();
529 }
530
531Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700532 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700533 *status = lStatus;
534 }
535 return trackHandle;
536}
537
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800538uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700539{
540 Mutex::Autolock _l(mLock);
541 PlaybackThread *thread = checkPlaybackThread_l(output);
542 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000543 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700544 return 0;
545 }
546 return thread->sampleRate();
547}
548
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800549int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700550{
551 Mutex::Autolock _l(mLock);
552 PlaybackThread *thread = checkPlaybackThread_l(output);
553 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000554 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700555 return 0;
556 }
557 return thread->channelCount();
558}
559
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800560audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700561{
562 Mutex::Autolock _l(mLock);
563 PlaybackThread *thread = checkPlaybackThread_l(output);
564 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000565 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800566 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700567 }
568 return thread->format();
569}
570
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800571size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700572{
573 Mutex::Autolock _l(mLock);
574 PlaybackThread *thread = checkPlaybackThread_l(output);
575 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000576 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700577 return 0;
578 }
Glenn Kasten58912562012-04-03 10:45:00 -0700579 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
580 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700581 return thread->frameCount();
582}
583
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800584uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700585{
586 Mutex::Autolock _l(mLock);
587 PlaybackThread *thread = checkPlaybackThread_l(output);
588 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000589 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700590 return 0;
591 }
592 return thread->latency();
593}
594
595status_t AudioFlinger::setMasterVolume(float value)
596{
Eric Laurenta1884f92011-08-23 08:25:03 -0700597 status_t ret = initCheck();
598 if (ret != NO_ERROR) {
599 return ret;
600 }
601
Mathias Agopian65ab4712010-07-14 17:59:35 -0700602 // check calling permissions
603 if (!settingsAllowed()) {
604 return PERMISSION_DENIED;
605 }
606
John Grossman4ff14ba2012-02-08 16:37:41 -0800607 float swmv = value;
608
Eric Laurenta4c5a552012-03-29 10:12:40 -0700609 Mutex::Autolock _l(mLock);
610
Mathias Agopian65ab4712010-07-14 17:59:35 -0700611 // when hw supports master volume, don't scale in sw mixer
John Grossman4ff14ba2012-02-08 16:37:41 -0800612 if (MVS_NONE != mMasterVolumeSupportLvl) {
613 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
614 AutoMutex lock(mHardwareLock);
Eric Laurenta4c5a552012-03-29 10:12:40 -0700615 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
John Grossman4ff14ba2012-02-08 16:37:41 -0800616
617 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
618 if (NULL != dev->set_master_volume) {
619 dev->set_master_volume(dev, value);
620 }
621 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800622 }
John Grossman4ff14ba2012-02-08 16:37:41 -0800623
624 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700625 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700626
John Grossman4ff14ba2012-02-08 16:37:41 -0800627 mMasterVolume = value;
628 mMasterVolumeSW = swmv;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800629 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700630 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700631
632 return NO_ERROR;
633}
634
Glenn Kastenf78aee72012-01-04 11:00:47 -0800635status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700636{
Eric Laurenta1884f92011-08-23 08:25:03 -0700637 status_t ret = initCheck();
638 if (ret != NO_ERROR) {
639 return ret;
640 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700641
642 // check calling permissions
643 if (!settingsAllowed()) {
644 return PERMISSION_DENIED;
645 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800646 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000647 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700648 return BAD_VALUE;
649 }
650
651 { // scope for the lock
652 AutoMutex lock(mHardwareLock);
653 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700654 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700655 mHardwareStatus = AUDIO_HW_IDLE;
656 }
657
658 if (NO_ERROR == ret) {
659 Mutex::Autolock _l(mLock);
660 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800661 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700662 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700663 }
664
665 return ret;
666}
667
668status_t AudioFlinger::setMicMute(bool state)
669{
Eric Laurenta1884f92011-08-23 08:25:03 -0700670 status_t ret = initCheck();
671 if (ret != NO_ERROR) {
672 return ret;
673 }
674
Mathias Agopian65ab4712010-07-14 17:59:35 -0700675 // check calling permissions
676 if (!settingsAllowed()) {
677 return PERMISSION_DENIED;
678 }
679
680 AutoMutex lock(mHardwareLock);
681 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700682 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700683 mHardwareStatus = AUDIO_HW_IDLE;
684 return ret;
685}
686
687bool AudioFlinger::getMicMute() const
688{
Eric Laurenta1884f92011-08-23 08:25:03 -0700689 status_t ret = initCheck();
690 if (ret != NO_ERROR) {
691 return false;
692 }
693
Dima Zavinfce7a472011-04-19 22:30:36 -0700694 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800695 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700696 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700697 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700698 mHardwareStatus = AUDIO_HW_IDLE;
699 return state;
700}
701
702status_t AudioFlinger::setMasterMute(bool muted)
703{
John Grossmand8f178d2012-07-20 14:51:35 -0700704 status_t ret = initCheck();
705 if (ret != NO_ERROR) {
706 return ret;
707 }
708
Mathias Agopian65ab4712010-07-14 17:59:35 -0700709 // check calling permissions
710 if (!settingsAllowed()) {
711 return PERMISSION_DENIED;
712 }
713
John Grossmand8f178d2012-07-20 14:51:35 -0700714 bool swmm = muted;
715
716 // when hw supports master mute, don't mute in sw mixer
717 if (MMS_NONE != mMasterMuteSupportLvl) {
718 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
719 AutoMutex lock(mHardwareLock);
720 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
721
722 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
723 if (NULL != dev->set_master_mute) {
724 dev->set_master_mute(dev, muted);
725 }
726 mHardwareStatus = AUDIO_HW_IDLE;
727 }
728
729 swmm = false;
730 }
731
Eric Laurent93575202011-01-18 18:39:02 -0800732 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -0800733 // This is an optimization, so PlaybackThread doesn't have to look at the one from AudioFlinger
John Grossmand8f178d2012-07-20 14:51:35 -0700734 mMasterMute = muted;
735 mMasterMuteSW = swmm;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800736 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmand8f178d2012-07-20 14:51:35 -0700737 mPlaybackThreads.valueAt(i)->setMasterMute(swmm);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700738
739 return NO_ERROR;
740}
741
742float AudioFlinger::masterVolume() const
743{
Glenn Kasten98067102011-12-13 11:47:54 -0800744 Mutex::Autolock _l(mLock);
745 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700746}
747
John Grossman4ff14ba2012-02-08 16:37:41 -0800748float AudioFlinger::masterVolumeSW() const
749{
750 Mutex::Autolock _l(mLock);
751 return masterVolumeSW_l();
752}
753
Mathias Agopian65ab4712010-07-14 17:59:35 -0700754bool AudioFlinger::masterMute() const
755{
Glenn Kasten98067102011-12-13 11:47:54 -0800756 Mutex::Autolock _l(mLock);
757 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700758}
759
John Grossmand8f178d2012-07-20 14:51:35 -0700760bool AudioFlinger::masterMuteSW() const
761{
762 Mutex::Autolock _l(mLock);
763 return masterMuteSW_l();
764}
765
John Grossman4ff14ba2012-02-08 16:37:41 -0800766float AudioFlinger::masterVolume_l() const
767{
768 if (MVS_FULL == mMasterVolumeSupportLvl) {
769 float ret_val;
770 AutoMutex lock(mHardwareLock);
771
772 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
Glenn Kasten5798d4e2012-03-08 12:18:35 -0800773 ALOG_ASSERT((NULL != mPrimaryHardwareDev) &&
774 (NULL != mPrimaryHardwareDev->get_master_volume),
775 "can't get master volume");
John Grossman4ff14ba2012-02-08 16:37:41 -0800776
777 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
778 mHardwareStatus = AUDIO_HW_IDLE;
779 return ret_val;
780 }
781
782 return mMasterVolume;
783}
784
John Grossmand8f178d2012-07-20 14:51:35 -0700785bool AudioFlinger::masterMute_l() const
786{
787 if (MMS_FULL == mMasterMuteSupportLvl) {
788 bool ret_val;
789 AutoMutex lock(mHardwareLock);
790
791 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
792 assert(NULL != mPrimaryHardwareDev);
793 assert(NULL != mPrimaryHardwareDev->get_master_mute);
794
795 mPrimaryHardwareDev->get_master_mute(mPrimaryHardwareDev, &ret_val);
796 mHardwareStatus = AUDIO_HW_IDLE;
797 return ret_val;
798 }
799
800 return mMasterMute;
801}
802
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800803status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
804 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805{
806 // check calling permissions
807 if (!settingsAllowed()) {
808 return PERMISSION_DENIED;
809 }
810
Glenn Kasten263709e2012-01-06 08:40:01 -0800811 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000812 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700813 return BAD_VALUE;
814 }
815
816 AutoMutex lock(mLock);
817 PlaybackThread *thread = NULL;
818 if (output) {
819 thread = checkPlaybackThread_l(output);
820 if (thread == NULL) {
821 return BAD_VALUE;
822 }
823 }
824
825 mStreamTypes[stream].volume = value;
826
827 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800828 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700829 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700830 }
831 } else {
832 thread->setStreamVolume(stream, value);
833 }
834
835 return NO_ERROR;
836}
837
Glenn Kastenfff6d712012-01-12 16:38:12 -0800838status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700839{
840 // check calling permissions
841 if (!settingsAllowed()) {
842 return PERMISSION_DENIED;
843 }
844
Glenn Kasten263709e2012-01-06 08:40:01 -0800845 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700846 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000847 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700848 return BAD_VALUE;
849 }
850
Eric Laurent93575202011-01-18 18:39:02 -0800851 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700852 mStreamTypes[stream].mute = muted;
853 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700854 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700855
856 return NO_ERROR;
857}
858
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800859float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700860{
Glenn Kasten263709e2012-01-06 08:40:01 -0800861 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700862 return 0.0f;
863 }
864
865 AutoMutex lock(mLock);
866 float volume;
867 if (output) {
868 PlaybackThread *thread = checkPlaybackThread_l(output);
869 if (thread == NULL) {
870 return 0.0f;
871 }
872 volume = thread->streamVolume(stream);
873 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800874 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700875 }
876
877 return volume;
878}
879
Glenn Kastenfff6d712012-01-12 16:38:12 -0800880bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700881{
Glenn Kasten263709e2012-01-06 08:40:01 -0800882 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700883 return true;
884 }
885
Glenn Kasten6637baa2012-01-09 09:40:36 -0800886 AutoMutex lock(mLock);
887 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700888}
889
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800890status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700891{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800892 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700893 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
894 // check calling permissions
895 if (!settingsAllowed()) {
896 return PERMISSION_DENIED;
897 }
898
Mathias Agopian65ab4712010-07-14 17:59:35 -0700899 // ioHandle == 0 means the parameters are global to the audio hardware interface
900 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700901 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700902 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800903 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700904 AutoMutex lock(mHardwareLock);
905 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
906 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
907 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
908 status_t result = dev->set_parameters(dev, keyValuePairs.string());
909 final_result = result ?: final_result;
910 }
911 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800912 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700913 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
914 AudioParameter param = AudioParameter(keyValuePairs);
915 String8 value;
916 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700917 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
918 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700919 for (size_t i = 0; i < mRecordThreads.size(); i++) {
920 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Glenn Kasten510a3d62012-07-16 14:24:34 -0700921 audio_devices_t device = thread->device() & AUDIO_DEVICE_IN_ALL;
922 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
923 // collect all of the thread's session IDs
924 KeyedVector<int, bool> ids = thread->sessionIds();
925 // suspend effects associated with those session IDs
926 for (size_t j = 0; j < ids.size(); ++j) {
927 int sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700928 thread->setEffectSuspended(FX_IID_AEC,
929 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700930 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700931 thread->setEffectSuspended(FX_IID_NS,
932 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700933 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700934 }
935 }
Eric Laurentbee53372011-08-29 12:42:48 -0700936 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700937 }
938 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700939 String8 screenState;
940 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
941 bool isOff = screenState == "off";
942 if (isOff != (gScreenState & 1)) {
943 gScreenState = ((gScreenState & ~1) + 2) | isOff;
944 }
945 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700946 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700947 }
948
949 // hold a strong ref on thread in case closeOutput() or closeInput() is called
950 // and the thread is exited once the lock is released
951 sp<ThreadBase> thread;
952 {
953 Mutex::Autolock _l(mLock);
954 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -0700955 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700956 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800957 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700958 // indicate output device change to all input threads for pre processing
959 AudioParameter param = AudioParameter(keyValuePairs);
960 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700961 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
962 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700963 for (size_t i = 0; i < mRecordThreads.size(); i++) {
964 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
965 }
966 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700967 }
968 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800969 if (thread != 0) {
970 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700971 }
972 return BAD_VALUE;
973}
974
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800975String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700976{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800977// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700978// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
979
Eric Laurenta4c5a552012-03-29 10:12:40 -0700980 Mutex::Autolock _l(mLock);
981
Mathias Agopian65ab4712010-07-14 17:59:35 -0700982 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700983 String8 out_s8;
984
Dima Zavin799a70e2011-04-18 16:57:27 -0700985 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800986 char *s;
987 {
988 AutoMutex lock(mHardwareLock);
989 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700990 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800991 s = dev->get_parameters(dev, keys.string());
992 mHardwareStatus = AUDIO_HW_IDLE;
993 }
John Grossmanef7740b2012-02-09 11:28:36 -0800994 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700995 free(s);
996 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700997 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700998 }
999
Mathias Agopian65ab4712010-07-14 17:59:35 -07001000 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
1001 if (playbackThread != NULL) {
1002 return playbackThread->getParameters(keys);
1003 }
1004 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1005 if (recordThread != NULL) {
1006 return recordThread->getParameters(keys);
1007 }
1008 return String8("");
1009}
1010
Glenn Kastendd8104c2012-07-02 12:42:44 -07001011size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
1012 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001013{
Eric Laurenta1884f92011-08-23 08:25:03 -07001014 status_t ret = initCheck();
1015 if (ret != NO_ERROR) {
1016 return 0;
1017 }
1018
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001019 AutoMutex lock(mHardwareLock);
1020 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001021 struct audio_config config = {
1022 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -07001023 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001024 format: format,
1025 };
1026 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001027 mHardwareStatus = AUDIO_HW_IDLE;
1028 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001029}
1030
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001031unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001032{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001033 Mutex::Autolock _l(mLock);
1034
1035 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1036 if (recordThread != NULL) {
1037 return recordThread->getInputFramesLost();
1038 }
1039 return 0;
1040}
1041
1042status_t AudioFlinger::setVoiceVolume(float value)
1043{
Eric Laurenta1884f92011-08-23 08:25:03 -07001044 status_t ret = initCheck();
1045 if (ret != NO_ERROR) {
1046 return ret;
1047 }
1048
Mathias Agopian65ab4712010-07-14 17:59:35 -07001049 // check calling permissions
1050 if (!settingsAllowed()) {
1051 return PERMISSION_DENIED;
1052 }
1053
1054 AutoMutex lock(mHardwareLock);
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001055 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -07001056 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001057 mHardwareStatus = AUDIO_HW_IDLE;
1058
1059 return ret;
1060}
1061
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001062status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1063 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001064{
1065 status_t status;
1066
1067 Mutex::Autolock _l(mLock);
1068
1069 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1070 if (playbackThread != NULL) {
1071 return playbackThread->getRenderPosition(halFrames, dspFrames);
1072 }
1073
1074 return BAD_VALUE;
1075}
1076
1077void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1078{
1079
1080 Mutex::Autolock _l(mLock);
1081
Glenn Kastenbb001922012-02-03 11:10:26 -08001082 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001083 if (mNotificationClients.indexOfKey(pid) < 0) {
1084 sp<NotificationClient> notificationClient = new NotificationClient(this,
1085 client,
1086 pid);
Steve Block3856b092011-10-20 11:56:00 +01001087 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001088
1089 mNotificationClients.add(pid, notificationClient);
1090
1091 sp<IBinder> binder = client->asBinder();
1092 binder->linkToDeath(notificationClient);
1093
1094 // the config change is always sent from playback or record threads to avoid deadlock
1095 // with AudioSystem::gLock
1096 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1097 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1098 }
1099
1100 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1101 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1102 }
1103 }
1104}
1105
1106void AudioFlinger::removeNotificationClient(pid_t pid)
1107{
1108 Mutex::Autolock _l(mLock);
1109
Glenn Kastena3b09252012-01-20 09:19:01 -08001110 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001111
Steve Block3856b092011-10-20 11:56:00 +01001112 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001113 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001114 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001115 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001116 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001117 ALOGV(" pid %d @ %d", ref->mPid, i);
1118 if (ref->mPid == pid) {
1119 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001120 mAudioSessionRefs.removeAt(i);
1121 delete ref;
1122 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001123 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001124 } else {
1125 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001126 }
1127 }
1128 if (removed) {
1129 purgeStaleEffects_l();
1130 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001131}
1132
1133// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001134void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001135{
1136 size_t size = mNotificationClients.size();
1137 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001138 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1139 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001140 }
1141}
1142
1143// removeClient_l() must be called with AudioFlinger::mLock held
1144void AudioFlinger::removeClient_l(pid_t pid)
1145{
Steve Block3856b092011-10-20 11:56:00 +01001146 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001147 mClients.removeItem(pid);
1148}
1149
Eric Laurent717e1282012-06-29 16:36:52 -07001150// getEffectThread_l() must be called with AudioFlinger::mLock held
1151sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1152{
1153 sp<PlaybackThread> thread;
1154
1155 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1156 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1157 ALOG_ASSERT(thread == 0);
1158 thread = mPlaybackThreads.valueAt(i);
1159 }
1160 }
1161
1162 return thread;
1163}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001164
1165// ----------------------------------------------------------------------------
1166
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001167AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001168 audio_devices_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001169 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001170 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001171 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001172 // mChannelMask
1173 mChannelCount(0),
1174 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1175 mParamStatus(NO_ERROR),
Glenn Kasten5ad92f62012-07-19 10:02:15 -07001176 mStandby(false), mDevice(device), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001177 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001178{
1179}
1180
1181AudioFlinger::ThreadBase::~ThreadBase()
1182{
1183 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001184 // do not lock the mutex in destructor
1185 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001186 if (mPowerManager != 0) {
1187 sp<IBinder> binder = mPowerManager->asBinder();
1188 binder->unlinkToDeath(mDeathRecipient);
1189 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001190}
1191
1192void AudioFlinger::ThreadBase::exit()
1193{
Steve Block3856b092011-10-20 11:56:00 +01001194 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001195 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001196 // This lock prevents the following race in thread (uniprocessor for illustration):
1197 // if (!exitPending()) {
1198 // // context switch from here to exit()
1199 // // exit() calls requestExit(), what exitPending() observes
1200 // // exit() calls signal(), which is dropped since no waiters
1201 // // context switch back from exit() to here
1202 // mWaitWorkCV.wait(...);
1203 // // now thread is hung
1204 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001205 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001206 requestExit();
1207 mWaitWorkCV.signal();
1208 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001209 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1210 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001211 requestExitAndWait();
1212}
1213
Mathias Agopian65ab4712010-07-14 17:59:35 -07001214status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1215{
1216 status_t status;
1217
Steve Block3856b092011-10-20 11:56:00 +01001218 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001219 Mutex::Autolock _l(mLock);
1220
1221 mNewParameters.add(keyValuePairs);
1222 mWaitWorkCV.signal();
1223 // wait condition with timeout in case the thread loop has exited
1224 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001225 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001226 status = mParamStatus;
1227 mWaitWorkCV.signal();
1228 } else {
1229 status = TIMED_OUT;
1230 }
1231 return status;
1232}
1233
1234void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1235{
1236 Mutex::Autolock _l(mLock);
1237 sendConfigEvent_l(event, param);
1238}
1239
1240// sendConfigEvent_l() must be called with ThreadBase::mLock held
1241void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1242{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001243 ConfigEvent configEvent;
1244 configEvent.mEvent = event;
1245 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001246 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001247 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001248 mWaitWorkCV.signal();
1249}
1250
1251void AudioFlinger::ThreadBase::processConfigEvents()
1252{
1253 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001254 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001255 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001256 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001257 mConfigEvents.removeAt(0);
1258 // release mLock before locking AudioFlinger mLock: lock order is always
1259 // AudioFlinger then ThreadBase to avoid cross deadlock
1260 mLock.unlock();
1261 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001262 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001263 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001264 mLock.lock();
1265 }
1266 mLock.unlock();
1267}
1268
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001269void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001270{
1271 const size_t SIZE = 256;
1272 char buffer[SIZE];
1273 String8 result;
1274
1275 bool locked = tryLock(mLock);
1276 if (!locked) {
1277 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1278 write(fd, buffer, strlen(buffer));
1279 }
1280
Eric Laurent612bbb52012-03-14 15:03:26 -07001281 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1282 result.append(buffer);
1283 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1284 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001285 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1286 result.append(buffer);
1287 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1288 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001289 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1290 result.append(buffer);
1291 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001292 result.append(buffer);
1293 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1294 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001295 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1296 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001297 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1298 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001299 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001300 result.append(buffer);
1301
1302 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1303 result.append(buffer);
1304 result.append(" Index Command");
1305 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1306 snprintf(buffer, SIZE, "\n %02d ", i);
1307 result.append(buffer);
1308 result.append(mNewParameters[i]);
1309 }
1310
1311 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1312 result.append(buffer);
1313 snprintf(buffer, SIZE, " Index event param\n");
1314 result.append(buffer);
1315 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001316 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001317 result.append(buffer);
1318 }
1319 result.append("\n");
1320
1321 write(fd, result.string(), result.size());
1322
1323 if (locked) {
1324 mLock.unlock();
1325 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001326}
1327
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001328void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001329{
1330 const size_t SIZE = 256;
1331 char buffer[SIZE];
1332 String8 result;
1333
1334 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1335 write(fd, buffer, strlen(buffer));
1336
1337 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1338 sp<EffectChain> chain = mEffectChains[i];
1339 if (chain != 0) {
1340 chain->dump(fd, args);
1341 }
1342 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001343}
1344
Eric Laurentfeb0db62011-07-22 09:04:31 -07001345void AudioFlinger::ThreadBase::acquireWakeLock()
1346{
1347 Mutex::Autolock _l(mLock);
1348 acquireWakeLock_l();
1349}
1350
1351void AudioFlinger::ThreadBase::acquireWakeLock_l()
1352{
1353 if (mPowerManager == 0) {
1354 // use checkService() to avoid blocking if power service is not up yet
1355 sp<IBinder> binder =
1356 defaultServiceManager()->checkService(String16("power"));
1357 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001358 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001359 } else {
1360 mPowerManager = interface_cast<IPowerManager>(binder);
1361 binder->linkToDeath(mDeathRecipient);
1362 }
1363 }
1364 if (mPowerManager != 0) {
1365 sp<IBinder> binder = new BBinder();
1366 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1367 binder,
1368 String16(mName));
1369 if (status == NO_ERROR) {
1370 mWakeLockToken = binder;
1371 }
Steve Block3856b092011-10-20 11:56:00 +01001372 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001373 }
1374}
1375
1376void AudioFlinger::ThreadBase::releaseWakeLock()
1377{
1378 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001379 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001380}
1381
1382void AudioFlinger::ThreadBase::releaseWakeLock_l()
1383{
1384 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001385 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001386 if (mPowerManager != 0) {
1387 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1388 }
1389 mWakeLockToken.clear();
1390 }
1391}
1392
1393void AudioFlinger::ThreadBase::clearPowerManager()
1394{
1395 Mutex::Autolock _l(mLock);
1396 releaseWakeLock_l();
1397 mPowerManager.clear();
1398}
1399
1400void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1401{
1402 sp<ThreadBase> thread = mThread.promote();
1403 if (thread != 0) {
1404 thread->clearPowerManager();
1405 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001406 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001407}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001408
Eric Laurent59255e42011-07-27 19:49:51 -07001409void AudioFlinger::ThreadBase::setEffectSuspended(
1410 const effect_uuid_t *type, bool suspend, int sessionId)
1411{
1412 Mutex::Autolock _l(mLock);
1413 setEffectSuspended_l(type, suspend, sessionId);
1414}
1415
1416void AudioFlinger::ThreadBase::setEffectSuspended_l(
1417 const effect_uuid_t *type, bool suspend, int sessionId)
1418{
Glenn Kasten090f0192012-01-30 13:00:02 -08001419 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001420 if (chain != 0) {
1421 if (type != NULL) {
1422 chain->setEffectSuspended_l(type, suspend);
1423 } else {
1424 chain->setEffectSuspendedAll_l(suspend);
1425 }
1426 }
1427
1428 updateSuspendedSessions_l(type, suspend, sessionId);
1429}
1430
1431void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1432{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001433 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001434 if (index < 0) {
1435 return;
1436 }
1437
Glenn Kasten0a7af182012-07-09 16:09:19 -07001438 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1439 mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001440
1441 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001442 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001443 for (int j = 0; j < desc->mRefCount; j++) {
1444 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1445 chain->setEffectSuspendedAll_l(true);
1446 } else {
Steve Block3856b092011-10-20 11:56:00 +01001447 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001448 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001449 chain->setEffectSuspended_l(&desc->mType, true);
1450 }
1451 }
1452 }
1453}
1454
Eric Laurent59255e42011-07-27 19:49:51 -07001455void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1456 bool suspend,
1457 int sessionId)
1458{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001459 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001460
1461 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1462
1463 if (suspend) {
1464 if (index >= 0) {
Glenn Kasten0a7af182012-07-09 16:09:19 -07001465 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001466 } else {
1467 mSuspendedSessions.add(sessionId, sessionEffects);
1468 }
1469 } else {
1470 if (index < 0) {
1471 return;
1472 }
Glenn Kasten0a7af182012-07-09 16:09:19 -07001473 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001474 }
1475
1476
1477 int key = EffectChain::kKeyForSuspendAll;
1478 if (type != NULL) {
1479 key = type->timeLow;
1480 }
1481 index = sessionEffects.indexOfKey(key);
1482
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001483 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001484 if (suspend) {
1485 if (index >= 0) {
1486 desc = sessionEffects.valueAt(index);
1487 } else {
1488 desc = new SuspendedSessionDesc();
1489 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001490 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001491 }
1492 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001493 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001494 }
1495 desc->mRefCount++;
1496 } else {
1497 if (index < 0) {
1498 return;
1499 }
1500 desc = sessionEffects.valueAt(index);
1501 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001502 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001503 sessionEffects.removeItemsAt(index);
1504 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001505 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001506 sessionId);
1507 mSuspendedSessions.removeItem(sessionId);
1508 }
1509 }
1510 }
1511 if (!sessionEffects.isEmpty()) {
1512 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1513 }
1514}
1515
1516void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1517 bool enabled,
1518 int sessionId)
1519{
1520 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001521 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1522}
Eric Laurent59255e42011-07-27 19:49:51 -07001523
Eric Laurenta85a74a2011-10-19 11:44:54 -07001524void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1525 bool enabled,
1526 int sessionId)
1527{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001528 if (mType != RECORD) {
1529 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1530 // another session. This gives the priority to well behaved effect control panels
1531 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001532 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1533 // global effects
1534 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001535 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1536 }
1537 }
Eric Laurent59255e42011-07-27 19:49:51 -07001538
1539 sp<EffectChain> chain = getEffectChain_l(sessionId);
1540 if (chain != 0) {
1541 chain->checkSuspendOnEffectEnabled(effect, enabled);
1542 }
1543}
1544
Mathias Agopian65ab4712010-07-14 17:59:35 -07001545// ----------------------------------------------------------------------------
1546
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001547AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1548 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001549 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001550 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001551 type_t type)
1552 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001553 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1554 // Assumes constructor is called by AudioFlinger with it's mLock held,
1555 // but it would be safer to explicitly pass initial masterMute as parameter
John Grossmand8f178d2012-07-20 14:51:35 -07001556 mMasterMute(audioFlinger->masterMuteSW_l()),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001557 // mStreamTypes[] initialized in constructor body
1558 mOutput(output),
1559 // Assumes constructor is called by AudioFlinger with it's mLock held,
1560 // but it would be safer to explicitly pass initial masterVolume as parameter
John Grossman4ff14ba2012-02-08 16:37:41 -08001561 mMasterVolume(audioFlinger->masterVolumeSW_l()),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001562 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001563 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001564 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001565 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001566 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001567 // index 0 is reserved for normal mixer's submix
1568 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001569{
Glenn Kasten480b4682012-02-28 12:30:08 -08001570 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001571
Mathias Agopian65ab4712010-07-14 17:59:35 -07001572 readOutputParameters();
1573
Glenn Kasten263709e2012-01-06 08:40:01 -08001574 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001575 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1576 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1577 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001578 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1579 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001580 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001581 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1582 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001583}
1584
1585AudioFlinger::PlaybackThread::~PlaybackThread()
1586{
1587 delete [] mMixBuffer;
1588}
1589
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001590void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001591{
1592 dumpInternals(fd, args);
1593 dumpTracks(fd, args);
1594 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001595}
1596
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001597void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598{
1599 const size_t SIZE = 256;
1600 char buffer[SIZE];
1601 String8 result;
1602
Glenn Kasten58912562012-04-03 10:45:00 -07001603 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1604 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1605 const stream_type_t *st = &mStreamTypes[i];
1606 if (i > 0) {
1607 result.appendFormat(", ");
1608 }
1609 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1610 if (st->mute) {
1611 result.append("M");
1612 }
1613 }
1614 result.append("\n");
1615 write(fd, result.string(), result.length());
1616 result.clear();
1617
Mathias Agopian65ab4712010-07-14 17:59:35 -07001618 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1619 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001620 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001621 for (size_t i = 0; i < mTracks.size(); ++i) {
1622 sp<Track> track = mTracks[i];
1623 if (track != 0) {
1624 track->dump(buffer, SIZE);
1625 result.append(buffer);
1626 }
1627 }
1628
1629 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1630 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001631 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001632 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001633 sp<Track> track = mActiveTracks[i].promote();
1634 if (track != 0) {
1635 track->dump(buffer, SIZE);
1636 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001637 }
1638 }
1639 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001640
1641 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1642 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1643 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1644 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001645}
1646
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001647void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001648{
1649 const size_t SIZE = 256;
1650 char buffer[SIZE];
1651 String8 result;
1652
1653 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1654 result.append(buffer);
1655 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1656 result.append(buffer);
1657 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1658 result.append(buffer);
1659 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1660 result.append(buffer);
1661 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1662 result.append(buffer);
1663 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1664 result.append(buffer);
1665 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1666 result.append(buffer);
1667 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001668 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001669
1670 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001671}
1672
1673// Thread virtuals
1674status_t AudioFlinger::PlaybackThread::readyToRun()
1675{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001676 status_t status = initCheck();
1677 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001678 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001679 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001680 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001681 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001682 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001683}
1684
1685void AudioFlinger::PlaybackThread::onFirstRef()
1686{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001687 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001688}
1689
1690// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001691sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001692 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001693 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001694 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001695 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001696 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001697 int frameCount,
1698 const sp<IMemory>& sharedBuffer,
1699 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001700 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001701 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001702 status_t *status)
1703{
1704 sp<Track> track;
1705 status_t lStatus;
1706
Glenn Kasten73d22752012-03-19 13:38:30 -07001707 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1708
1709 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001710 if (flags & IAudioFlinger::TRACK_FAST) {
1711 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001712 // not timed
1713 (!isTimed) &&
1714 // either of these use cases:
1715 (
1716 // use case 1: shared buffer with any frame count
1717 (
1718 (sharedBuffer != 0)
1719 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001720 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001721 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001722 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001723 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001724 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001725 )
1726 ) &&
1727 // PCM data
1728 audio_is_linear_pcm(format) &&
1729 // mono or stereo
1730 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1731 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001732#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001733 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001734 (sampleRate == mSampleRate) &&
1735#endif
1736 // normal mixer has an associated fast mixer
1737 hasFastMixer() &&
1738 // there are sufficient fast track slots available
1739 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001740 // FIXME test that MixerThread for this fast track has a capable output HAL
1741 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001742 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001743 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1744 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001745 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001746 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001747 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001748 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001749 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001750 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07001751 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001752 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1753 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1754 audio_is_linear_pcm(format),
1755 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001756 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001757 // For compatibility with AudioTrack calculation, buffer depth is forced
1758 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1759 // This is probably too conservative, but legacy application code may depend on it.
1760 // If you change this calculation, also review the start threshold which is related.
1761 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1762 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1763 if (minBufCount < 2) {
1764 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001765 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001766 int minFrameCount = mNormalFrameCount * minBufCount;
1767 if (frameCount < minFrameCount) {
1768 frameCount = minFrameCount;
1769 }
1770 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001771 }
1772
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001774 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1775 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001776 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001777 "for output %p with format %d",
1778 sampleRate, format, channelMask, mOutput, mFormat);
1779 lStatus = BAD_VALUE;
1780 goto Exit;
1781 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001782 }
1783 } else {
1784 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1785 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001786 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001787 lStatus = BAD_VALUE;
1788 goto Exit;
1789 }
1790 }
1791
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001792 lStatus = initCheck();
1793 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001794 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001795 goto Exit;
1796 }
1797
1798 { // scope for mLock
1799 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001800
1801 // all tracks in same audio session must share the same routing strategy otherwise
1802 // conflicts will happen when tracks are moved from one output to another by audio policy
1803 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001804 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001805 for (size_t i = 0; i < mTracks.size(); ++i) {
1806 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001807 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001808 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001809 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001810 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001811 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001812 lStatus = BAD_VALUE;
1813 goto Exit;
1814 }
1815 }
1816 }
1817
John Grossman4ff14ba2012-02-08 16:37:41 -08001818 if (!isTimed) {
1819 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001820 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001821 } else {
1822 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1823 channelMask, frameCount, sharedBuffer, sessionId);
1824 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001825 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001826 lStatus = NO_MEMORY;
1827 goto Exit;
1828 }
1829 mTracks.add(track);
1830
1831 sp<EffectChain> chain = getEffectChain_l(sessionId);
1832 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001833 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001834 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001835 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001836 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001837 }
1838 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001839
Glenn Kasten3acbd052012-02-28 10:39:56 -08001840 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1841 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1842 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1843 // so ask activity manager to do this on our behalf
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07001844 int err = requestPriority(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001845 if (err != 0) {
1846 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07001847 kPriorityAudioApp, callingPid, tid, err);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001848 }
1849 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001850
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851 lStatus = NO_ERROR;
1852
1853Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001854 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855 *status = lStatus;
1856 }
1857 return track;
1858}
1859
Eric Laurente737cda2012-05-22 18:55:44 -07001860uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1861{
1862 if (mFastMixer != NULL) {
1863 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1864 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1865 }
1866 return latency;
1867}
1868
1869uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1870{
1871 return latency;
1872}
1873
Mathias Agopian65ab4712010-07-14 17:59:35 -07001874uint32_t AudioFlinger::PlaybackThread::latency() const
1875{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001876 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001877 return latency_l();
1878}
1879uint32_t AudioFlinger::PlaybackThread::latency_l() const
1880{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001881 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001882 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001883 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001884 return 0;
1885 }
1886}
1887
Glenn Kasten6637baa2012-01-09 09:40:36 -08001888void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001889{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001890 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001891 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001892}
1893
Glenn Kasten6637baa2012-01-09 09:40:36 -08001894void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001895{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001896 Mutex::Autolock _l(mLock);
1897 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001898}
1899
Glenn Kasten6637baa2012-01-09 09:40:36 -08001900void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001901{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001902 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001903 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001904}
1905
Glenn Kasten6637baa2012-01-09 09:40:36 -08001906void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001907{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001908 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001909 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001910}
1911
Glenn Kastenfff6d712012-01-12 16:38:12 -08001912float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001913{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001914 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001915 return mStreamTypes[stream].volume;
1916}
1917
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918// addTrack_l() must be called with ThreadBase::mLock held
1919status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1920{
1921 status_t status = ALREADY_EXISTS;
1922
1923 // set retry count for buffer fill
1924 track->mRetryCount = kMaxTrackStartupRetries;
1925 if (mActiveTracks.indexOf(track) < 0) {
1926 // the track is newly added, make sure it fills up all its
1927 // buffers before playing. This is to ensure the client will
1928 // effectively get the latency it requested.
1929 track->mFillingUpStatus = Track::FS_FILLING;
1930 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001931 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932 mActiveTracks.add(track);
1933 if (track->mainBuffer() != mMixBuffer) {
1934 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1935 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001936 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001937 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001938 }
1939 }
1940
1941 status = NO_ERROR;
1942 }
1943
Steve Block3856b092011-10-20 11:56:00 +01001944 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001945 mWaitWorkCV.broadcast();
1946
1947 return status;
1948}
1949
1950// destroyTrack_l() must be called with ThreadBase::mLock held
1951void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1952{
1953 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001954 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001955 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001956 removeTrack_l(track);
1957 }
1958}
1959
1960void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1961{
Eric Laurent29864602012-05-08 18:57:51 -07001962 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001963 mTracks.remove(track);
1964 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001965 // redundant as track is about to be destroyed, for dumpsys only
1966 track->mName = -1;
1967 if (track->isFastTrack()) {
1968 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001969 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001970 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1971 mFastTrackAvailMask |= 1 << index;
1972 // redundant as track is about to be destroyed, for dumpsys only
1973 track->mFastIndex = -1;
1974 }
Eric Laurentb469b942011-05-09 12:09:06 -07001975 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1976 if (chain != 0) {
1977 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001978 }
1979}
1980
1981String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1982{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001983 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001984 char *s;
1985
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001986 Mutex::Autolock _l(mLock);
1987 if (initCheck() != NO_ERROR) {
1988 return out_s8;
1989 }
1990
Dima Zavin799a70e2011-04-18 16:57:27 -07001991 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001992 out_s8 = String8(s);
1993 free(s);
1994 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001995}
1996
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001997// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001998void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1999 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08002000 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002001
Steve Block3856b092011-10-20 11:56:00 +01002002 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002003
2004 switch (event) {
2005 case AudioSystem::OUTPUT_OPENED:
2006 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002007 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002008 desc.samplingRate = mSampleRate;
2009 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07002010 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002011 desc.latency = latency();
2012 param2 = &desc;
2013 break;
2014
2015 case AudioSystem::STREAM_CONFIG_CHANGED:
2016 param2 = &param;
2017 case AudioSystem::OUTPUT_CLOSED:
2018 default:
2019 break;
2020 }
2021 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2022}
2023
2024void AudioFlinger::PlaybackThread::readOutputParameters()
2025{
Dima Zavin799a70e2011-04-18 16:57:27 -07002026 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002027 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2028 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07002029 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002030 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002031 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002032 if (mFrameCount & 15) {
2033 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2034 mFrameCount);
2035 }
2036
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002037 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002038 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002039 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002040 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002041 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2042 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2043 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2044 maxNormalFrameCount = maxNormalFrameCount & ~15;
2045 if (maxNormalFrameCount < minNormalFrameCount) {
2046 maxNormalFrameCount = minNormalFrameCount;
2047 }
2048 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2049 if (multiplier <= 1.0) {
2050 multiplier = 1.0;
2051 } else if (multiplier <= 2.0) {
2052 if (2 * mFrameCount <= maxNormalFrameCount) {
2053 multiplier = 2.0;
2054 } else {
2055 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2056 }
2057 } else {
2058 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2059 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2060 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2061 // FIXME this rounding up should not be done if no HAL SRC
2062 uint32_t truncMult = (uint32_t) multiplier;
2063 if ((truncMult & 1)) {
2064 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2065 ++truncMult;
2066 }
2067 }
2068 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002069 }
Glenn Kasten58912562012-04-03 10:45:00 -07002070 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002071 mNormalFrameCount = multiplier * mFrameCount;
2072 // round up to nearest 16 frames to satisfy AudioMixer
2073 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002074 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002075
Glenn Kastene9dd0172012-01-27 18:08:45 -08002076 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002077 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2078 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002079
Eric Laurentde070132010-07-13 04:45:46 -07002080 // force reconfiguration of effect chains and engines to take new buffer size and audio
2081 // parameters into account
2082 // Note that mLock is not held when readOutputParameters() is called from the constructor
2083 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2084 // matter.
2085 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2086 Vector< sp<EffectChain> > effectChains = mEffectChains;
2087 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002088 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002089 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002090}
2091
Eric Laurente737cda2012-05-22 18:55:44 -07002092
Mathias Agopian65ab4712010-07-14 17:59:35 -07002093status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2094{
Glenn Kastena0d68332012-01-27 16:47:15 -08002095 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002096 return BAD_VALUE;
2097 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002098 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002099 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002100 return INVALID_OPERATION;
2101 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002102 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002103
Dima Zavin799a70e2011-04-18 16:57:27 -07002104 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105}
2106
Eric Laurent39e94f82010-07-28 01:32:47 -07002107uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002108{
2109 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002110 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002111 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002112 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002113 }
2114
2115 for (size_t i = 0; i < mTracks.size(); ++i) {
2116 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002117 if (sessionId == track->sessionId() &&
2118 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002119 result |= TRACK_SESSION;
2120 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002121 }
2122 }
2123
Eric Laurent39e94f82010-07-28 01:32:47 -07002124 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002125}
2126
Eric Laurentde070132010-07-13 04:45:46 -07002127uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2128{
Dima Zavinfce7a472011-04-19 22:30:36 -07002129 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002130 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002131 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2132 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002133 }
2134 for (size_t i = 0; i < mTracks.size(); i++) {
2135 sp<Track> track = mTracks[i];
2136 if (sessionId == track->sessionId() &&
2137 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002138 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002139 }
2140 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002141 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002142}
2143
Mathias Agopian65ab4712010-07-14 17:59:35 -07002144
Glenn Kastenaed850d2012-01-26 09:46:34 -08002145AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002146{
2147 Mutex::Autolock _l(mLock);
2148 return mOutput;
2149}
2150
2151AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2152{
2153 Mutex::Autolock _l(mLock);
2154 AudioStreamOut *output = mOutput;
2155 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002156 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2157 // must push a NULL and wait for ack
2158 mOutputSink.clear();
2159 mPipeSink.clear();
2160 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002161 return output;
2162}
2163
2164// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002165audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002166{
2167 if (mOutput == NULL) {
2168 return NULL;
2169 }
2170 return &mOutput->stream->common;
2171}
2172
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002173uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002174{
Eric Laurentab9071b2012-06-04 13:45:29 -07002175 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002176}
2177
Eric Laurenta011e352012-03-29 15:51:43 -07002178status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2179{
2180 if (!isValidSyncEvent(event)) {
2181 return BAD_VALUE;
2182 }
2183
2184 Mutex::Autolock _l(mLock);
2185
2186 for (size_t i = 0; i < mTracks.size(); ++i) {
2187 sp<Track> track = mTracks[i];
2188 if (event->triggerSession() == track->sessionId()) {
2189 track->setSyncEvent(event);
2190 return NO_ERROR;
2191 }
2192 }
2193
2194 return NAME_NOT_FOUND;
2195}
2196
2197bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2198{
2199 switch (event->type()) {
2200 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2201 return true;
2202 default:
2203 break;
2204 }
2205 return false;
2206}
2207
Eric Laurent44a957f2012-05-15 15:26:05 -07002208void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2209{
2210 size_t count = tracksToRemove.size();
2211 if (CC_UNLIKELY(count)) {
2212 for (size_t i = 0 ; i < count ; i++) {
2213 const sp<Track>& track = tracksToRemove.itemAt(i);
2214 if ((track->sharedBuffer() != 0) &&
2215 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2216 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2217 }
2218 }
2219 }
2220
2221}
2222
Mathias Agopian65ab4712010-07-14 17:59:35 -07002223// ----------------------------------------------------------------------------
2224
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002225AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002226 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002227 : PlaybackThread(audioFlinger, output, id, device, type),
2228 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002229 // mFastMixer below
2230 mFastMixerFutex(0)
2231 // mOutputSink below
2232 // mPipeSink below
2233 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002234{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002235 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002236 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002237 "mFrameCount=%d, mNormalFrameCount=%d",
2238 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2239 mNormalFrameCount);
2240 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2241
Mathias Agopian65ab4712010-07-14 17:59:35 -07002242 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002243 if (mChannelCount != FCC_2) {
2244 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002245 }
Glenn Kasten58912562012-04-03 10:45:00 -07002246
2247 // create an NBAIO sink for the HAL output stream, and negotiate
2248 mOutputSink = new AudioStreamOutSink(output->stream);
2249 size_t numCounterOffers = 0;
2250 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2251 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2252 ALOG_ASSERT(index == 0);
2253
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002254 // initialize fast mixer depending on configuration
2255 bool initFastMixer;
2256 switch (kUseFastMixer) {
2257 case FastMixer_Never:
2258 initFastMixer = false;
2259 break;
2260 case FastMixer_Always:
2261 initFastMixer = true;
2262 break;
2263 case FastMixer_Static:
2264 case FastMixer_Dynamic:
2265 initFastMixer = mFrameCount < mNormalFrameCount;
2266 break;
2267 }
2268 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002269
2270 // create a MonoPipe to connect our submix to FastMixer
2271 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002272 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2273 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2274 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2275 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002276 const NBAIO_Format offers[1] = {format};
2277 size_t numCounterOffers = 0;
2278 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2279 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002280 monoPipe->setAvgFrames((mScreenState & 1) ?
2281 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002282 mPipeSink = monoPipe;
2283
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002284#ifdef TEE_SINK_FRAMES
2285 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2286 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2287 numCounterOffers = 0;
2288 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2289 ALOG_ASSERT(index == 0);
2290 mTeeSink = teeSink;
2291 PipeReader *teeSource = new PipeReader(*teeSink);
2292 numCounterOffers = 0;
2293 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2294 ALOG_ASSERT(index == 0);
2295 mTeeSource = teeSource;
2296#endif
2297
Glenn Kasten58912562012-04-03 10:45:00 -07002298 // create fast mixer and configure it initially with just one fast track for our submix
2299 mFastMixer = new FastMixer();
2300 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002301#ifdef STATE_QUEUE_DUMP
2302 sq->setObserverDump(&mStateQueueObserverDump);
2303 sq->setMutatorDump(&mStateQueueMutatorDump);
2304#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002305 FastMixerState *state = sq->begin();
2306 FastTrack *fastTrack = &state->mFastTracks[0];
2307 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2308 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2309 fastTrack->mVolumeProvider = NULL;
2310 fastTrack->mGeneration++;
2311 state->mFastTracksGen++;
2312 state->mTrackMask = 1;
2313 // fast mixer will use the HAL output sink
2314 state->mOutputSink = mOutputSink.get();
2315 state->mOutputSinkGen++;
2316 state->mFrameCount = mFrameCount;
2317 state->mCommand = FastMixerState::COLD_IDLE;
2318 // already done in constructor initialization list
2319 //mFastMixerFutex = 0;
2320 state->mColdFutexAddr = &mFastMixerFutex;
2321 state->mColdGen++;
2322 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002323 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002324 sq->end();
2325 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2326
2327 // start the fast mixer
2328 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002329 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002330 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002331 if (err != 0) {
2332 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002333 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002334 }
Glenn Kasten58912562012-04-03 10:45:00 -07002335
Glenn Kastenc15d6652012-05-30 14:52:57 -07002336#ifdef AUDIO_WATCHDOG
2337 // create and start the watchdog
2338 mAudioWatchdog = new AudioWatchdog();
2339 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2340 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2341 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002342 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002343 if (err != 0) {
2344 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002345 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002346 }
2347#endif
2348
Glenn Kasten58912562012-04-03 10:45:00 -07002349 } else {
2350 mFastMixer = NULL;
2351 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002352
2353 switch (kUseFastMixer) {
2354 case FastMixer_Never:
2355 case FastMixer_Dynamic:
2356 mNormalSink = mOutputSink;
2357 break;
2358 case FastMixer_Always:
2359 mNormalSink = mPipeSink;
2360 break;
2361 case FastMixer_Static:
2362 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2363 break;
2364 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002365}
2366
2367AudioFlinger::MixerThread::~MixerThread()
2368{
Glenn Kasten58912562012-04-03 10:45:00 -07002369 if (mFastMixer != NULL) {
2370 FastMixerStateQueue *sq = mFastMixer->sq();
2371 FastMixerState *state = sq->begin();
2372 if (state->mCommand == FastMixerState::COLD_IDLE) {
2373 int32_t old = android_atomic_inc(&mFastMixerFutex);
2374 if (old == -1) {
2375 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2376 }
2377 }
2378 state->mCommand = FastMixerState::EXIT;
2379 sq->end();
2380 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2381 mFastMixer->join();
2382 // Though the fast mixer thread has exited, it's state queue is still valid.
2383 // We'll use that extract the final state which contains one remaining fast track
2384 // corresponding to our sub-mix.
2385 state = sq->begin();
2386 ALOG_ASSERT(state->mTrackMask == 1);
2387 FastTrack *fastTrack = &state->mFastTracks[0];
2388 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2389 delete fastTrack->mBufferProvider;
2390 sq->end(false /*didModify*/);
2391 delete mFastMixer;
Glenn Kastenc15d6652012-05-30 14:52:57 -07002392 if (mAudioWatchdog != 0) {
2393 mAudioWatchdog->requestExit();
2394 mAudioWatchdog->requestExitAndWait();
2395 mAudioWatchdog.clear();
2396 }
Glenn Kasten58912562012-04-03 10:45:00 -07002397 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002398 delete mAudioMixer;
2399}
2400
Glenn Kasten83efdd02012-02-24 07:21:32 -08002401class CpuStats {
2402public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002403 CpuStats();
2404 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002405#ifdef DEBUG_CPU_USAGE
2406private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002407 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2408 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2409
2410 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2411
2412 int mCpuNum; // thread's current CPU number
2413 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002414#endif
2415};
2416
Glenn Kasten190a46f2012-03-06 11:27:10 -08002417CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002418#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002419 : mCpuNum(-1), mCpukHz(-1)
2420#endif
2421{
2422}
2423
2424void CpuStats::sample(const String8 &title) {
2425#ifdef DEBUG_CPU_USAGE
2426 // get current thread's delta CPU time in wall clock ns
2427 double wcNs;
2428 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2429
2430 // record sample for wall clock statistics
2431 if (valid) {
2432 mWcStats.sample(wcNs);
2433 }
2434
2435 // get the current CPU number
2436 int cpuNum = sched_getcpu();
2437
2438 // get the current CPU frequency in kHz
2439 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2440
2441 // check if either CPU number or frequency changed
2442 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2443 mCpuNum = cpuNum;
2444 mCpukHz = cpukHz;
2445 // ignore sample for purposes of cycles
2446 valid = false;
2447 }
2448
2449 // if no change in CPU number or frequency, then record sample for cycle statistics
2450 if (valid && mCpukHz > 0) {
2451 double cycles = wcNs * cpukHz * 0.000001;
2452 mHzStats.sample(cycles);
2453 }
2454
2455 unsigned n = mWcStats.n();
2456 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002457 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002458 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002459 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2460 double perLoop = elapsed / (double) n;
2461 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002462 double perLoop1k = perLoop * 0.001;
2463 double mean = mWcStats.mean();
2464 double stddev = mWcStats.stddev();
2465 double minimum = mWcStats.minimum();
2466 double maximum = mWcStats.maximum();
2467 double meanCycles = mHzStats.mean();
2468 double stddevCycles = mHzStats.stddev();
2469 double minCycles = mHzStats.minimum();
2470 double maxCycles = mHzStats.maximum();
2471 mCpuUsage.resetElapsed();
2472 mWcStats.reset();
2473 mHzStats.reset();
2474 ALOGD("CPU usage for %s over past %.1f secs\n"
2475 " (%u mixer loops at %.1f mean ms per loop):\n"
2476 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2477 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2478 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2479 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002480 elapsed * .000000001, n, perLoop * .000001,
2481 mean * .001,
2482 stddev * .001,
2483 minimum * .001,
2484 maximum * .001,
2485 mean / perLoop100,
2486 stddev / perLoop100,
2487 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002488 maximum / perLoop100,
2489 meanCycles / perLoop1k,
2490 stddevCycles / perLoop1k,
2491 minCycles / perLoop1k,
2492 maxCycles / perLoop1k);
2493
Glenn Kasten83efdd02012-02-24 07:21:32 -08002494 }
2495 }
2496#endif
2497};
2498
Glenn Kasten37d825e2012-02-24 07:21:48 -08002499void AudioFlinger::PlaybackThread::checkSilentMode_l()
2500{
2501 if (!mMasterMute) {
2502 char value[PROPERTY_VALUE_MAX];
2503 if (property_get("ro.audio.silent", value, "0") > 0) {
2504 char *endptr;
2505 unsigned long ul = strtoul(value, &endptr, 0);
2506 if (*endptr == '\0' && ul != 0) {
2507 ALOGD("Silence is golden");
2508 // The setprop command will not allow a property to be changed after
2509 // the first time it is set, so we don't have to worry about un-muting.
2510 setMasterMute_l(true);
2511 }
2512 }
2513 }
2514}
2515
Glenn Kasten000f0e32012-03-01 17:10:56 -08002516bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002517{
2518 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002519
Glenn Kasten000f0e32012-03-01 17:10:56 -08002520 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002521
2522 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002523 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002524
Glenn Kasten000f0e32012-03-01 17:10:56 -08002525 // DUPLICATING
2526 // FIXME could this be made local to while loop?
2527 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002528
Glenn Kasten66fcab92012-02-24 14:59:21 -08002529 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002530 sleepTime = idleSleepTime;
2531
Glenn Kasten9f34a362012-03-20 16:46:41 -07002532 if (mType == MIXER) {
2533 sleepTimeShift = 0;
2534 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002535
Glenn Kasten83efdd02012-02-24 07:21:32 -08002536 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002537 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002538
Eric Laurentfeb0db62011-07-22 09:04:31 -07002539 acquireWakeLock();
2540
Mathias Agopian65ab4712010-07-14 17:59:35 -07002541 while (!exitPending())
2542 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002543 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002544
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002545 Vector< sp<EffectChain> > effectChains;
2546
Mathias Agopian65ab4712010-07-14 17:59:35 -07002547 processConfigEvents();
2548
Mathias Agopian65ab4712010-07-14 17:59:35 -07002549 { // scope for mLock
2550
2551 Mutex::Autolock _l(mLock);
2552
2553 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002554 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002555 }
2556
Glenn Kastenfa26a852012-03-06 11:28:04 -08002557 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002558
Mathias Agopian65ab4712010-07-14 17:59:35 -07002559 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002560 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002561 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002562 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002563
2564 threadLoop_standby();
2565
Mathias Agopian65ab4712010-07-14 17:59:35 -07002566 mStandby = true;
2567 mBytesWritten = 0;
2568 }
2569
Glenn Kasten3e074702012-02-28 18:40:35 -08002570 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002571 // we're about to wait, flush the binder command buffer
2572 IPCThreadState::self()->flushCommands();
2573
Glenn Kastenfa26a852012-03-06 11:28:04 -08002574 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002575
Mathias Agopian65ab4712010-07-14 17:59:35 -07002576 if (exitPending()) break;
2577
Eric Laurentfeb0db62011-07-22 09:04:31 -07002578 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002579 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002580 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002582 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002583 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002584
Eric Laurentda747442012-04-25 18:53:13 -07002585 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002586 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002587
Glenn Kasten37d825e2012-02-24 07:21:48 -08002588 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002589
Glenn Kasten000f0e32012-03-01 17:10:56 -08002590 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002591 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002592 if (mType == MIXER) {
2593 sleepTimeShift = 0;
2594 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002595
Mathias Agopian65ab4712010-07-14 17:59:35 -07002596 continue;
2597 }
2598 }
2599
Glenn Kasten81028042012-04-30 18:15:12 -07002600 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002601 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002602
2603 // prevent any changes in effect chain list and in each effect chain
2604 // during mixing and effect process as the audio buffers could be deleted
2605 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002606 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002607 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002608
Glenn Kastenfec279f2012-03-08 07:47:15 -08002609 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002610 threadLoop_mix();
2611 } else {
2612 threadLoop_sleepTime();
2613 }
2614
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002615 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002616 sleepTime = suspendSleepTimeUs();
2617 }
2618
2619 // only process effects if we're going to write
2620 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002621 for (size_t i = 0; i < effectChains.size(); i ++) {
2622 effectChains[i]->process_l();
2623 }
2624 }
2625
2626 // enable changes in effect chain
2627 unlockEffectChains(effectChains);
2628
2629 // sleepTime == 0 means we must write to audio hardware
2630 if (sleepTime == 0) {
2631
2632 threadLoop_write();
2633
2634if (mType == MIXER) {
2635 // write blocked detection
2636 nsecs_t now = systemTime();
2637 nsecs_t delta = now - mLastWriteTime;
2638 if (!mStandby && delta > maxPeriod) {
2639 mNumDelayedWrites++;
2640 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002641#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002642 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002643#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002644 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2645 ns2ms(delta), mNumDelayedWrites, this);
2646 lastWarning = now;
2647 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002648 }
2649}
2650
2651 mStandby = false;
2652 } else {
2653 usleep(sleepTime);
2654 }
2655
Glenn Kasten58912562012-04-03 10:45:00 -07002656 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002657 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002658 // same lock. This will also mutate and push a new fast mixer state.
2659 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002660 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002661
Glenn Kastenfa26a852012-03-06 11:28:04 -08002662 // FIXME I don't understand the need for this here;
2663 // it was in the original code but maybe the
2664 // assignment in saveOutputTracks() makes this unnecessary?
2665 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002666
2667 // Effect chains will be actually deleted here if they were removed from
2668 // mEffectChains list during mixing or effects processing
2669 effectChains.clear();
2670
2671 // FIXME Note that the above .clear() is no longer necessary since effectChains
2672 // is now local to this block, but will keep it for now (at least until merge done).
2673 }
2674
Glenn Kasten9f34a362012-03-20 16:46:41 -07002675 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2676 if (mType == MIXER || mType == DIRECT) {
2677 // put output stream into standby mode
2678 if (!mStandby) {
2679 mOutput->stream->common.standby(&mOutput->stream->common);
2680 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002681 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002682
2683 releaseWakeLock();
2684
2685 ALOGV("Thread %p type %d exiting", this, mType);
2686 return false;
2687}
2688
Glenn Kasten58912562012-04-03 10:45:00 -07002689void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2690{
Glenn Kasten58912562012-04-03 10:45:00 -07002691 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2692}
2693
2694void AudioFlinger::MixerThread::threadLoop_write()
2695{
2696 // FIXME we should only do one push per cycle; confirm this is true
2697 // Start the fast mixer if it's not already running
2698 if (mFastMixer != NULL) {
2699 FastMixerStateQueue *sq = mFastMixer->sq();
2700 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002701 if (state->mCommand != FastMixerState::MIX_WRITE &&
2702 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002703 if (state->mCommand == FastMixerState::COLD_IDLE) {
2704 int32_t old = android_atomic_inc(&mFastMixerFutex);
2705 if (old == -1) {
2706 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2707 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002708 if (mAudioWatchdog != 0) {
2709 mAudioWatchdog->resume();
2710 }
Glenn Kasten58912562012-04-03 10:45:00 -07002711 }
2712 state->mCommand = FastMixerState::MIX_WRITE;
2713 sq->end();
2714 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002715 if (kUseFastMixer == FastMixer_Dynamic) {
2716 mNormalSink = mPipeSink;
2717 }
Glenn Kasten58912562012-04-03 10:45:00 -07002718 } else {
2719 sq->end(false /*didModify*/);
2720 }
2721 }
2722 PlaybackThread::threadLoop_write();
2723}
2724
Glenn Kasten000f0e32012-03-01 17:10:56 -08002725// shared by MIXER and DIRECT, overridden by DUPLICATING
2726void AudioFlinger::PlaybackThread::threadLoop_write()
2727{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002728 // FIXME rewrite to reduce number of system calls
2729 mLastWriteTime = systemTime();
2730 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002731 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002732
Eric Laurent67c0a582012-05-01 19:31:12 -07002733 // If an NBAIO sink is present, use it to write the normal mixer's submix
2734 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002735#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002736 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002737#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002738 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002739#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002740 // update the setpoint when gScreenState changes
2741 uint32_t screenState = gScreenState;
2742 if (screenState != mScreenState) {
2743 mScreenState = screenState;
2744 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2745 if (pipe != NULL) {
2746 pipe->setAvgFrames((mScreenState & 1) ?
2747 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2748 }
2749 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002750 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002751#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002752 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002753#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002754 if (framesWritten > 0) {
2755 bytesWritten = framesWritten << mBitShift;
2756 } else {
2757 bytesWritten = framesWritten;
2758 }
2759 // otherwise use the HAL / AudioStreamOut directly
2760 } else {
2761 // Direct output thread.
2762 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002763 }
2764
Eric Laurent67c0a582012-05-01 19:31:12 -07002765 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002766 mNumWrites++;
2767 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002768}
2769
Glenn Kasten58912562012-04-03 10:45:00 -07002770void AudioFlinger::MixerThread::threadLoop_standby()
2771{
2772 // Idle the fast mixer if it's currently running
2773 if (mFastMixer != NULL) {
2774 FastMixerStateQueue *sq = mFastMixer->sq();
2775 FastMixerState *state = sq->begin();
2776 if (!(state->mCommand & FastMixerState::IDLE)) {
2777 state->mCommand = FastMixerState::COLD_IDLE;
2778 state->mColdFutexAddr = &mFastMixerFutex;
2779 state->mColdGen++;
2780 mFastMixerFutex = 0;
2781 sq->end();
2782 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2783 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002784 if (kUseFastMixer == FastMixer_Dynamic) {
2785 mNormalSink = mOutputSink;
2786 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002787 if (mAudioWatchdog != 0) {
2788 mAudioWatchdog->pause();
2789 }
Glenn Kasten58912562012-04-03 10:45:00 -07002790 } else {
2791 sq->end(false /*didModify*/);
2792 }
2793 }
2794 PlaybackThread::threadLoop_standby();
2795}
2796
Glenn Kasten000f0e32012-03-01 17:10:56 -08002797// shared by MIXER and DIRECT, overridden by DUPLICATING
2798void AudioFlinger::PlaybackThread::threadLoop_standby()
2799{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002800 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002801 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002802}
2803
2804void AudioFlinger::MixerThread::threadLoop_mix()
2805{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002806 // obtain the presentation timestamp of the next output buffer
2807 int64_t pts;
2808 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002809
Glenn Kasten952eeb22012-03-06 11:30:57 -08002810 if (NULL != mOutput->stream->get_next_write_timestamp) {
2811 status = mOutput->stream->get_next_write_timestamp(
2812 mOutput->stream, &pts);
2813 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002814
Glenn Kasten952eeb22012-03-06 11:30:57 -08002815 if (status != NO_ERROR) {
2816 pts = AudioBufferProvider::kInvalidPTS;
2817 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002818
Glenn Kasten952eeb22012-03-06 11:30:57 -08002819 // mix buffers...
2820 mAudioMixer->process(pts);
2821 // increase sleep time progressively when application underrun condition clears.
2822 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2823 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2824 // such that we would underrun the audio HAL.
2825 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2826 sleepTimeShift--;
2827 }
2828 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002829 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002830 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002831}
2832
2833void AudioFlinger::MixerThread::threadLoop_sleepTime()
2834{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002835 // If no tracks are ready, sleep once for the duration of an output
2836 // buffer size, then write 0s to the output
2837 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002838 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002839 sleepTime = activeSleepTime >> sleepTimeShift;
2840 if (sleepTime < kMinThreadSleepTimeUs) {
2841 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002842 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002843 // reduce sleep time in case of consecutive application underruns to avoid
2844 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2845 // duration we would end up writing less data than needed by the audio HAL if
2846 // the condition persists.
2847 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2848 sleepTimeShift++;
2849 }
2850 } else {
2851 sleepTime = idleSleepTime;
2852 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002853 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002854 memset (mMixBuffer, 0, mixBufferSize);
2855 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002856 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002857 }
2858 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002859}
2860
2861// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002862AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002863 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002864{
2865
Glenn Kasten29c23c32012-01-26 13:37:52 -08002866 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002867 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002868 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002869 size_t mixedTracks = 0;
2870 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002871 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002872 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002873 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002874
2875 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002876 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002877
Eric Laurent571d49c2010-08-11 05:20:11 -07002878 if (masterMute) {
2879 masterVolume = 0;
2880 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002881 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002882 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002883 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002884 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002885 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002886 masterVolume = (float)((v + (1 << 23)) >> 24);
2887 chain.clear();
2888 }
2889
Glenn Kasten288ed212012-04-25 17:52:27 -07002890 // prepare a new state to push
2891 FastMixerStateQueue *sq = NULL;
2892 FastMixerState *state = NULL;
2893 bool didModify = false;
2894 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2895 if (mFastMixer != NULL) {
2896 sq = mFastMixer->sq();
2897 state = sq->begin();
2898 }
2899
Mathias Agopian65ab4712010-07-14 17:59:35 -07002900 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002901 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002902 if (t == 0) continue;
2903
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002904 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002905 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002906
Glenn Kasten288ed212012-04-25 17:52:27 -07002907 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002908 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002909
2910 // It's theoretically possible (though unlikely) for a fast track to be created
2911 // and then removed within the same normal mix cycle. This is not a problem, as
2912 // the track never becomes active so it's fast mixer slot is never touched.
2913 // The converse, of removing an (active) track and then creating a new track
2914 // at the identical fast mixer slot within the same normal mix cycle,
2915 // is impossible because the slot isn't marked available until the end of each cycle.
2916 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002917 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2918 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002919 FastTrack *fastTrack = &state->mFastTracks[j];
2920
2921 // Determine whether the track is currently in underrun condition,
2922 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002923 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2924 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002925 uint32_t recentFull = (underruns.mBitFields.mFull -
2926 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2927 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2928 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2929 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2930 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2931 uint32_t recentUnderruns = recentPartial + recentEmpty;
2932 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002933 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002934 // or stopped which can occur when flush() is called while active
2935 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002936 track->mUnderrunCount += recentUnderruns;
2937 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002938
Glenn Kastend08f48c2012-05-01 18:14:02 -07002939 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002940 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002941 bool isActive = true;
2942 switch (track->mState) {
2943 case TrackBase::STOPPING_1:
2944 // track stays active in STOPPING_1 state until first underrun
2945 if (recentUnderruns > 0) {
2946 track->mState = TrackBase::STOPPING_2;
2947 }
2948 break;
2949 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002950 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002951 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002952 break;
2953 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002954 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002955 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002956 break;
2957 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002958 if (recentFull > 0 || recentPartial > 0) {
2959 // track has provided at least some frames recently: reset retry count
2960 track->mRetryCount = kMaxTrackRetries;
2961 }
2962 if (recentUnderruns == 0) {
2963 // no recent underruns: stay active
2964 break;
2965 }
2966 // there has recently been an underrun of some kind
2967 if (track->sharedBuffer() == 0) {
2968 // were any of the recent underruns "empty" (no frames available)?
2969 if (recentEmpty == 0) {
2970 // no, then ignore the partial underruns as they are allowed indefinitely
2971 break;
2972 }
2973 // there has recently been an "empty" underrun: decrement the retry counter
2974 if (--(track->mRetryCount) > 0) {
2975 break;
2976 }
2977 // indicate to client process that the track was disabled because of underrun;
2978 // it will then automatically call start() when data is available
2979 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2980 // remove from active list, but state remains ACTIVE [confusing but true]
2981 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002982 break;
2983 }
2984 // fall through
2985 case TrackBase::STOPPING_2:
2986 case TrackBase::PAUSED:
2987 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002988 case TrackBase::STOPPED:
2989 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002990 // Check for presentation complete if track is inactive
2991 // We have consumed all the buffers of this track.
2992 // This would be incomplete if we auto-paused on underrun
2993 {
2994 size_t audioHALFrames =
2995 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2996 size_t framesWritten =
2997 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2998 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2999 // track stays in active list until presentation is complete
3000 break;
3001 }
3002 }
3003 if (track->isStopping_2()) {
3004 track->mState = TrackBase::STOPPED;
3005 }
3006 if (track->isStopped()) {
3007 // Can't reset directly, as fast mixer is still polling this track
3008 // track->reset();
3009 // So instead mark this track as needing to be reset after push with ack
3010 resetMask |= 1 << i;
3011 }
3012 isActive = false;
3013 break;
3014 case TrackBase::IDLE:
3015 default:
3016 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003017 }
3018
3019 if (isActive) {
3020 // was it previously inactive?
3021 if (!(state->mTrackMask & (1 << j))) {
3022 ExtendedAudioBufferProvider *eabp = track;
3023 VolumeProvider *vp = track;
3024 fastTrack->mBufferProvider = eabp;
3025 fastTrack->mVolumeProvider = vp;
3026 fastTrack->mSampleRate = track->mSampleRate;
3027 fastTrack->mChannelMask = track->mChannelMask;
3028 fastTrack->mGeneration++;
3029 state->mTrackMask |= 1 << j;
3030 didModify = true;
3031 // no acknowledgement required for newly active tracks
3032 }
3033 // cache the combined master volume and stream type volume for fast mixer; this
3034 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3035 track->mCachedVolume = track->isMuted() ?
3036 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3037 ++fastTracks;
3038 } else {
3039 // was it previously active?
3040 if (state->mTrackMask & (1 << j)) {
3041 fastTrack->mBufferProvider = NULL;
3042 fastTrack->mGeneration++;
3043 state->mTrackMask &= ~(1 << j);
3044 didModify = true;
3045 // If any fast tracks were removed, we must wait for acknowledgement
3046 // because we're about to decrement the last sp<> on those tracks.
3047 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003048 } else {
3049 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003050 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003051 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003052 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003053 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003054 }
3055 continue;
3056 }
3057
3058 { // local variable scope to avoid goto warning
3059
Mathias Agopian65ab4712010-07-14 17:59:35 -07003060 audio_track_cblk_t* cblk = track->cblk();
3061
3062 // The first time a track is added we wait
3063 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003064 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003065 // make sure that we have enough frames to mix one full buffer.
3066 // enforce this condition only once to enable draining the buffer in case the client
3067 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003068 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003069 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003070 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003071 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003072 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003073 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003074 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003075 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003076 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003077 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003078 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003079 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003080 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3081 // the minimum track buffer size is normally twice the number of frames necessary
3082 // to fill one buffer and the resampler should not leave more than one buffer worth
3083 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003084 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003085 }
3086 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003087 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003088 !track->isPaused() && !track->isTerminated())
3089 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003090 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003091
3092 mixedTracks++;
3093
3094 // track->mainBuffer() != mMixBuffer means there is an effect chain
3095 // connected to the track
3096 chain.clear();
3097 if (track->mainBuffer() != mMixBuffer) {
3098 chain = getEffectChain_l(track->sessionId());
3099 // Delegate volume control to effect in track effect chain if needed
3100 if (chain != 0) {
3101 tracksWithEffect++;
3102 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003103 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003104 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003105 }
3106 }
3107
3108
3109 int param = AudioMixer::VOLUME;
3110 if (track->mFillingUpStatus == Track::FS_FILLED) {
3111 // no ramp for the first volume setting
3112 track->mFillingUpStatus = Track::FS_ACTIVE;
3113 if (track->mState == TrackBase::RESUMING) {
3114 track->mState = TrackBase::ACTIVE;
3115 param = AudioMixer::RAMP_VOLUME;
3116 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003117 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003118 } else if (cblk->server != 0) {
3119 // If the track is stopped before the first frame was mixed,
3120 // do not apply ramp
3121 param = AudioMixer::RAMP_VOLUME;
3122 }
3123
3124 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003125 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003126 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003127 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003128 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003129 if (track->isPausing()) {
3130 track->setPaused();
3131 }
3132 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003133
Mathias Agopian65ab4712010-07-14 17:59:35 -07003134 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003135 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003136 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003137 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003138 vl = vlr & 0xFFFF;
3139 vr = vlr >> 16;
3140 // track volumes come from shared memory, so can't be trusted and must be clamped
3141 if (vl > MAX_GAIN_INT) {
3142 ALOGV("Track left volume out of range: %04X", vl);
3143 vl = MAX_GAIN_INT;
3144 }
3145 if (vr > MAX_GAIN_INT) {
3146 ALOGV("Track right volume out of range: %04X", vr);
3147 vr = MAX_GAIN_INT;
3148 }
3149 // now apply the master volume and stream type volume
3150 vl = (uint32_t)(v * vl) << 12;
3151 vr = (uint32_t)(v * vr) << 12;
3152 // assuming master volume and stream type volume each go up to 1.0,
3153 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003154
Glenn Kasten05632a52012-01-03 14:22:33 -08003155 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3156 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003157 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003158 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003159 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003160 }
3161 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003162 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003163 // Delegate volume control to effect in track effect chain if needed
3164 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3165 // Do not ramp volume if volume is controlled by effect
3166 param = AudioMixer::VOLUME;
3167 track->mHasVolumeController = true;
3168 } else {
3169 // force no volume ramp when volume controller was just disabled or removed
3170 // from effect chain to avoid volume spike
3171 if (track->mHasVolumeController) {
3172 param = AudioMixer::VOLUME;
3173 }
3174 track->mHasVolumeController = false;
3175 }
3176
3177 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003178 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003179 vl = (vl + (1 << 11)) >> 12;
3180 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3181 vr = (vr + (1 << 11)) >> 12;
3182 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003183
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003184 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 -07003185
Mathias Agopian65ab4712010-07-14 17:59:35 -07003186 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003187 mAudioMixer->setBufferProvider(name, track);
3188 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003189
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003190 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3191 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3192 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003193 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003194 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003195 AudioMixer::TRACK,
3196 AudioMixer::FORMAT, (void *)track->format());
3197 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003198 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003199 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003200 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003201 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003202 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003203 AudioMixer::RESAMPLE,
3204 AudioMixer::SAMPLE_RATE,
3205 (void *)(cblk->sampleRate));
3206 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003207 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003208 AudioMixer::TRACK,
3209 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3210 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003211 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003212 AudioMixer::TRACK,
3213 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3214
3215 // reset retry count
3216 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003217
Eric Laurent27741442012-01-17 19:20:12 -08003218 // If one track is ready, set the mixer ready if:
3219 // - the mixer was not ready during previous round OR
3220 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003221 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003222 mixerStatus != MIXER_TRACKS_ENABLED) {
3223 mixerStatus = MIXER_TRACKS_READY;
3224 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003225 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003226 // clear effect chain input buffer if an active track underruns to avoid sending
3227 // previous audio buffer again to effects
3228 chain = getEffectChain_l(track->sessionId());
3229 if (chain != 0) {
3230 chain->clearInputBuffer();
3231 }
3232
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003233 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003234 if ((track->sharedBuffer() != 0) ||
Eric Laurent83faee02012-04-27 18:24:29 -07003235 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003236 // We have consumed all the buffers of this track.
3237 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003238 // TODO: use actual buffer filling status instead of latency when available from
3239 // audio HAL
3240 size_t audioHALFrames =
3241 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3242 size_t framesWritten =
3243 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3244 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003245 if (track->isStopped()) {
3246 track->reset();
3247 }
Eric Laurenta011e352012-03-29 15:51:43 -07003248 tracksToRemove->add(track);
3249 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003250 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003251 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003252 // No buffers for this track. Give it a few chances to
3253 // fill a buffer, then remove it from active list.
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003254 if (--(track->mRetryCount) <= 0 || track->isTerminated()) {
3255 ALOGV_IF(track->mRetryCount <= 0, "BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003256 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003257 // indicate to client process that the track was disabled because of underrun;
3258 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003259 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003260 // If one track is not ready, mark the mixer also not ready if:
3261 // - the mixer was ready during previous round OR
3262 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003263 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003264 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003265 mixerStatus = MIXER_TRACKS_ENABLED;
3266 }
3267 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003268 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003269 }
Glenn Kasten58912562012-04-03 10:45:00 -07003270
3271 } // local variable scope to avoid goto warning
3272track_is_ready: ;
3273
Mathias Agopian65ab4712010-07-14 17:59:35 -07003274 }
3275
Glenn Kasten288ed212012-04-25 17:52:27 -07003276 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003277 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003278 if (didModify) {
3279 state->mFastTracksGen++;
3280 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3281 if (kUseFastMixer == FastMixer_Dynamic &&
3282 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3283 state->mCommand = FastMixerState::COLD_IDLE;
3284 state->mColdFutexAddr = &mFastMixerFutex;
3285 state->mColdGen++;
3286 mFastMixerFutex = 0;
3287 if (kUseFastMixer == FastMixer_Dynamic) {
3288 mNormalSink = mOutputSink;
3289 }
3290 // If we go into cold idle, need to wait for acknowledgement
3291 // so that fast mixer stops doing I/O.
3292 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003293 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003294 }
3295 sq->end();
3296 }
3297 if (sq != NULL) {
3298 sq->end(didModify);
3299 sq->push(block);
3300 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07003301 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3302 mAudioWatchdog->pause();
3303 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003304
3305 // Now perform the deferred reset on fast tracks that have stopped
3306 while (resetMask != 0) {
3307 size_t i = __builtin_ctz(resetMask);
3308 ALOG_ASSERT(i < count);
3309 resetMask &= ~(1 << i);
3310 sp<Track> t = mActiveTracks[i].promote();
3311 if (t == 0) continue;
3312 Track* track = t.get();
3313 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3314 track->reset();
3315 }
Glenn Kasten58912562012-04-03 10:45:00 -07003316
Mathias Agopian65ab4712010-07-14 17:59:35 -07003317 // remove all the tracks that need to be...
3318 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003319 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003320 for (size_t i=0 ; i<count ; i++) {
3321 const sp<Track>& track = tracksToRemove->itemAt(i);
3322 mActiveTracks.remove(track);
3323 if (track->mainBuffer() != mMixBuffer) {
3324 chain = getEffectChain_l(track->sessionId());
3325 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003326 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003327 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003328 }
3329 }
3330 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003331 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332 }
3333 }
3334 }
3335
3336 // mix buffer must be cleared if all tracks are connected to an
3337 // effect chain as in this case the mixer will not write to
3338 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003339 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3340 // FIXME as a performance optimization, should remember previous zero status
3341 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003342 }
3343
Glenn Kasten58912562012-04-03 10:45:00 -07003344 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003345 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003346 if (fastTracks > 0) {
3347 mixerStatus = MIXER_TRACKS_READY;
3348 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003349 return mixerStatus;
3350}
3351
Glenn Kasten66fcab92012-02-24 14:59:21 -08003352/*
3353The derived values that are cached:
3354 - mixBufferSize from frame count * frame size
3355 - activeSleepTime from activeSleepTimeUs()
3356 - idleSleepTime from idleSleepTimeUs()
3357 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3358 - maxPeriod from frame count and sample rate (MIXER only)
3359
3360The parameters that affect these derived values are:
3361 - frame count
3362 - frame size
3363 - sample rate
3364 - device type: A2DP or not
3365 - device latency
3366 - format: PCM or not
3367 - active sleep time
3368 - idle sleep time
3369*/
3370
3371void AudioFlinger::PlaybackThread::cacheParameters_l()
3372{
Glenn Kasten58912562012-04-03 10:45:00 -07003373 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003374 activeSleepTime = activeSleepTimeUs();
3375 idleSleepTime = idleSleepTimeUs();
3376}
3377
Eric Laurent22167852012-06-20 12:26:32 -07003378void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003379{
Steve Block3856b092011-10-20 11:56:00 +01003380 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003381 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003382 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003383
Mathias Agopian65ab4712010-07-14 17:59:35 -07003384 size_t size = mTracks.size();
3385 for (size_t i = 0; i < size; i++) {
3386 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003387 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003388 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003389 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003390 }
3391 }
3392}
3393
Mathias Agopian65ab4712010-07-14 17:59:35 -07003394// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003395int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003396{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003397 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003398}
3399
3400// deleteTrackName_l() must be called with ThreadBase::mLock held
3401void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3402{
Steve Block3856b092011-10-20 11:56:00 +01003403 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003404 mAudioMixer->deleteTrackName(name);
3405}
3406
3407// checkForNewParameters_l() must be called with ThreadBase::mLock held
3408bool AudioFlinger::MixerThread::checkForNewParameters_l()
3409{
Glenn Kasten58912562012-04-03 10:45:00 -07003410 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3411 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003412 bool reconfig = false;
3413
3414 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003415
3416 if (mFastMixer != NULL) {
3417 FastMixerStateQueue *sq = mFastMixer->sq();
3418 FastMixerState *state = sq->begin();
3419 if (!(state->mCommand & FastMixerState::IDLE)) {
3420 previousCommand = state->mCommand;
3421 state->mCommand = FastMixerState::HOT_IDLE;
3422 sq->end();
3423 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3424 } else {
3425 sq->end(false /*didModify*/);
3426 }
3427 }
3428
Mathias Agopian65ab4712010-07-14 17:59:35 -07003429 status_t status = NO_ERROR;
3430 String8 keyValuePair = mNewParameters[0];
3431 AudioParameter param = AudioParameter(keyValuePair);
3432 int value;
3433
3434 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3435 reconfig = true;
3436 }
3437 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003438 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003439 status = BAD_VALUE;
3440 } else {
3441 reconfig = true;
3442 }
3443 }
3444 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003445 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003446 status = BAD_VALUE;
3447 } else {
3448 reconfig = true;
3449 }
3450 }
3451 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3452 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003453 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003454 // if frame count is changed after track creation
3455 if (!mTracks.isEmpty()) {
3456 status = INVALID_OPERATION;
3457 } else {
3458 reconfig = true;
3459 }
3460 }
3461 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003462#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003463 // when changing the audio output device, call addBatteryData to notify
3464 // the change
Glenn Kasten5ad92f62012-07-19 10:02:15 -07003465 if (mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003466 uint32_t params = 0;
3467 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003468 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003469 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3470 }
3471
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003472 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003473 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003474 // check if any other device (except speaker) is on
3475 if (value & deviceWithoutSpeaker ) {
3476 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3477 }
3478
3479 if (params != 0) {
3480 addBatteryData(params);
3481 }
3482 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003483#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003484
Mathias Agopian65ab4712010-07-14 17:59:35 -07003485 // forward device change to effects that have requested to be
3486 // aware of attached audio device.
Glenn Kasten5ad92f62012-07-19 10:02:15 -07003487 mDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003488 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003489 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003490 }
3491 }
3492
3493 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003494 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003495 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003496 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003497 mOutput->stream->common.standby(&mOutput->stream->common);
3498 mStandby = true;
3499 mBytesWritten = 0;
3500 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003501 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003502 }
3503 if (status == NO_ERROR && reconfig) {
3504 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003505 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3506 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003507 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003508 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003509 for (size_t i = 0; i < mTracks.size() ; i++) {
Glenn Kasten254af182012-07-03 14:59:05 -07003510 int name = getTrackName_l(mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003511 if (name < 0) break;
3512 mTracks[i]->mName = name;
3513 // limit track sample rate to 2 x new output sample rate
3514 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3515 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3516 }
3517 }
3518 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3519 }
3520 }
3521
3522 mNewParameters.removeAt(0);
3523
3524 mParamStatus = status;
3525 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003526 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3527 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003528 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003529 }
Glenn Kasten58912562012-04-03 10:45:00 -07003530
3531 if (!(previousCommand & FastMixerState::IDLE)) {
3532 ALOG_ASSERT(mFastMixer != NULL);
3533 FastMixerStateQueue *sq = mFastMixer->sq();
3534 FastMixerState *state = sq->begin();
3535 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3536 state->mCommand = previousCommand;
3537 sq->end();
3538 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3539 }
3540
Mathias Agopian65ab4712010-07-14 17:59:35 -07003541 return reconfig;
3542}
3543
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07003544void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003545{
3546 const size_t SIZE = 256;
3547 char buffer[SIZE];
3548 String8 result;
3549
3550 PlaybackThread::dumpInternals(fd, args);
3551
3552 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3553 result.append(buffer);
3554 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003555
3556 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3557 FastMixerDumpState copy = mFastMixerDumpState;
3558 copy.dump(fd);
3559
Glenn Kasten39993082012-05-31 13:40:27 -07003560#ifdef STATE_QUEUE_DUMP
3561 // Similar for state queue
3562 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3563 observerCopy.dump(fd);
3564 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3565 mutatorCopy.dump(fd);
3566#endif
3567
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003568 // Write the tee output to a .wav file
3569 NBAIO_Source *teeSource = mTeeSource.get();
3570 if (teeSource != NULL) {
3571 char teePath[64];
3572 struct timeval tv;
3573 gettimeofday(&tv, NULL);
3574 struct tm tm;
3575 localtime_r(&tv.tv_sec, &tm);
3576 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3577 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3578 if (teeFd >= 0) {
3579 char wavHeader[44];
3580 memcpy(wavHeader,
3581 "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",
3582 sizeof(wavHeader));
3583 NBAIO_Format format = teeSource->format();
3584 unsigned channelCount = Format_channelCount(format);
3585 ALOG_ASSERT(channelCount <= FCC_2);
3586 unsigned sampleRate = Format_sampleRate(format);
3587 wavHeader[22] = channelCount; // number of channels
3588 wavHeader[24] = sampleRate; // sample rate
3589 wavHeader[25] = sampleRate >> 8;
3590 wavHeader[32] = channelCount * 2; // block alignment
3591 write(teeFd, wavHeader, sizeof(wavHeader));
3592 size_t total = 0;
3593 bool firstRead = true;
3594 for (;;) {
3595#define TEE_SINK_READ 1024
3596 short buffer[TEE_SINK_READ * FCC_2];
3597 size_t count = TEE_SINK_READ;
3598 ssize_t actual = teeSource->read(buffer, count);
3599 bool wasFirstRead = firstRead;
3600 firstRead = false;
3601 if (actual <= 0) {
3602 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3603 continue;
3604 }
3605 break;
3606 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003607 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003608 write(teeFd, buffer, actual * channelCount * sizeof(short));
3609 total += actual;
3610 }
3611 lseek(teeFd, (off_t) 4, SEEK_SET);
3612 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3613 write(teeFd, &temp, sizeof(temp));
3614 lseek(teeFd, (off_t) 40, SEEK_SET);
3615 temp = total * channelCount * sizeof(short);
3616 write(teeFd, &temp, sizeof(temp));
3617 close(teeFd);
3618 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3619 } else {
3620 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3621 }
3622 }
3623
Glenn Kastenc15d6652012-05-30 14:52:57 -07003624 if (mAudioWatchdog != 0) {
3625 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3626 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3627 wdCopy.dump(fd);
3628 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003629}
3630
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003631uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003632{
Glenn Kasten58912562012-04-03 10:45:00 -07003633 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003634}
3635
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003636uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003637{
Glenn Kasten58912562012-04-03 10:45:00 -07003638 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003639}
3640
Glenn Kasten66fcab92012-02-24 14:59:21 -08003641void AudioFlinger::MixerThread::cacheParameters_l()
3642{
3643 PlaybackThread::cacheParameters_l();
3644
3645 // FIXME: Relaxed timing because of a certain device that can't meet latency
3646 // Should be reduced to 2x after the vendor fixes the driver issue
3647 // increase threshold again due to low power audio mode. The way this warning
3648 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003649 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003650}
3651
Mathias Agopian65ab4712010-07-14 17:59:35 -07003652// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003653AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003654 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003655 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003656 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003657{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003658}
3659
3660AudioFlinger::DirectOutputThread::~DirectOutputThread()
3661{
3662}
3663
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003664AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3665 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003666)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003667{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003668 sp<Track> trackToRemove;
3669
Glenn Kastenfec279f2012-03-08 07:47:15 -08003670 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003671
Glenn Kasten952eeb22012-03-06 11:30:57 -08003672 // find out which tracks need to be processed
3673 if (mActiveTracks.size() != 0) {
3674 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003675 // The track died recently
3676 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003677
Glenn Kasten952eeb22012-03-06 11:30:57 -08003678 Track* const track = t.get();
3679 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003680
Glenn Kasten952eeb22012-03-06 11:30:57 -08003681 // The first time a track is added we wait
3682 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003683 uint32_t minFrames;
3684 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3685 minFrames = mNormalFrameCount;
3686 } else {
3687 minFrames = 1;
3688 }
3689 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003690 !track->isPaused() && !track->isTerminated())
3691 {
3692 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003693
Glenn Kasten952eeb22012-03-06 11:30:57 -08003694 if (track->mFillingUpStatus == Track::FS_FILLED) {
3695 track->mFillingUpStatus = Track::FS_ACTIVE;
3696 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003697 if (track->mState == TrackBase::RESUMING) {
3698 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003699 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003700 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003701
Glenn Kasten952eeb22012-03-06 11:30:57 -08003702 // compute volume for this track
3703 float left, right;
3704 if (track->isMuted() || mMasterMute || track->isPausing() ||
3705 mStreamTypes[track->streamType()].mute) {
3706 left = right = 0;
3707 if (track->isPausing()) {
3708 track->setPaused();
3709 }
3710 } else {
3711 float typeVolume = mStreamTypes[track->streamType()].volume;
3712 float v = mMasterVolume * typeVolume;
3713 uint32_t vlr = cblk->getVolumeLR();
3714 float v_clamped = v * (vlr & 0xFFFF);
3715 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3716 left = v_clamped/MAX_GAIN;
3717 v_clamped = v * (vlr >> 16);
3718 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3719 right = v_clamped/MAX_GAIN;
3720 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003721
Glenn Kasten952eeb22012-03-06 11:30:57 -08003722 if (left != mLeftVolFloat || right != mRightVolFloat) {
3723 mLeftVolFloat = left;
3724 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003725
Glenn Kasten952eeb22012-03-06 11:30:57 -08003726 // Convert volumes from float to 8.24
3727 uint32_t vl = (uint32_t)(left * (1 << 24));
3728 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003729
Glenn Kasten952eeb22012-03-06 11:30:57 -08003730 // Delegate volume control to effect in track effect chain if needed
3731 // only one effect chain can be present on DirectOutputThread, so if
3732 // there is one, the track is connected to it
3733 if (!mEffectChains.isEmpty()) {
3734 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003735 mEffectChains[0]->setVolume_l(&vl, &vr);
3736 left = (float)vl / (1 << 24);
3737 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003738 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003739 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003740 }
3741
3742 // reset retry count
3743 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003744 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003745 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003746 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003747 // clear effect chain input buffer if an active track underruns to avoid sending
3748 // previous audio buffer again to effects
3749 if (!mEffectChains.isEmpty()) {
3750 mEffectChains[0]->clearInputBuffer();
3751 }
3752
Glenn Kasten952eeb22012-03-06 11:30:57 -08003753 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003754 if ((track->sharedBuffer() != 0) ||
Eric Laurent67c0a582012-05-01 19:31:12 -07003755 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003756 // We have consumed all the buffers of this track.
3757 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003758 // TODO: implement behavior for compressed audio
3759 size_t audioHALFrames =
3760 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3761 size_t framesWritten =
3762 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3763 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003764 if (track->isStopped()) {
3765 track->reset();
3766 }
Eric Laurenta011e352012-03-29 15:51:43 -07003767 trackToRemove = track;
3768 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003769 } else {
3770 // No buffers for this track. Give it a few chances to
3771 // fill a buffer, then remove it from active list.
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003772 if (--(track->mRetryCount) <= 0 || track->isTerminated()) {
3773 ALOGV_IF(track->mRetryCount <= 0, "BUFFER TIMEOUT: remove(%d) from active list", track->name());
Glenn Kasten952eeb22012-03-06 11:30:57 -08003774 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003775 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003776 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003777 }
3778 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003779 }
3780 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003781
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003782 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003783 // remove all the tracks that need to be...
3784 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003785 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003786 mActiveTracks.remove(trackToRemove);
3787 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003788 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003789 trackToRemove->sessionId());
3790 mEffectChains[0]->decActiveTrackCnt();
3791 }
3792 if (trackToRemove->isTerminated()) {
3793 removeTrack_l(trackToRemove);
3794 }
3795 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003796
Glenn Kastenfec279f2012-03-08 07:47:15 -08003797 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003798}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003799
Glenn Kasten000f0e32012-03-01 17:10:56 -08003800void AudioFlinger::DirectOutputThread::threadLoop_mix()
3801{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003802 AudioBufferProvider::Buffer buffer;
3803 size_t frameCount = mFrameCount;
3804 int8_t *curBuf = (int8_t *)mMixBuffer;
3805 // output audio to hardware
3806 while (frameCount) {
3807 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003808 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003809 if (CC_UNLIKELY(buffer.raw == NULL)) {
3810 memset(curBuf, 0, frameCount * mFrameSize);
3811 break;
3812 }
3813 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3814 frameCount -= buffer.frameCount;
3815 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003816 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003817 }
3818 sleepTime = 0;
3819 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003820 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003821
Glenn Kasten000f0e32012-03-01 17:10:56 -08003822}
3823
3824void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3825{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003826 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003827 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003828 sleepTime = activeSleepTime;
3829 } else {
3830 sleepTime = idleSleepTime;
3831 }
3832 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003833 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003834 sleepTime = 0;
3835 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003836}
3837
3838// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003839int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003840{
3841 return 0;
3842}
3843
3844// deleteTrackName_l() must be called with ThreadBase::mLock held
3845void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3846{
3847}
3848
3849// checkForNewParameters_l() must be called with ThreadBase::mLock held
3850bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3851{
3852 bool reconfig = false;
3853
3854 while (!mNewParameters.isEmpty()) {
3855 status_t status = NO_ERROR;
3856 String8 keyValuePair = mNewParameters[0];
3857 AudioParameter param = AudioParameter(keyValuePair);
3858 int value;
3859
3860 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3861 // do not accept frame count changes if tracks are open as the track buffer
3862 // size depends on frame count and correct behavior would not be garantied
3863 // if frame count is changed after track creation
3864 if (!mTracks.isEmpty()) {
3865 status = INVALID_OPERATION;
3866 } else {
3867 reconfig = true;
3868 }
3869 }
3870 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003871 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003872 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003873 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003874 mOutput->stream->common.standby(&mOutput->stream->common);
3875 mStandby = true;
3876 mBytesWritten = 0;
3877 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003878 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003879 }
3880 if (status == NO_ERROR && reconfig) {
3881 readOutputParameters();
3882 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3883 }
3884 }
3885
3886 mNewParameters.removeAt(0);
3887
3888 mParamStatus = status;
3889 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003890 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3891 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003892 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003893 }
3894 return reconfig;
3895}
3896
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003897uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003898{
3899 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003900 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003901 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003902 } else {
3903 time = 10000;
3904 }
3905 return time;
3906}
3907
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003908uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003909{
3910 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003911 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003912 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003913 } else {
3914 time = 10000;
3915 }
3916 return time;
3917}
3918
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003919uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003920{
3921 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003922 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003923 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3924 } else {
3925 time = 10000;
3926 }
3927 return time;
3928}
3929
Glenn Kasten66fcab92012-02-24 14:59:21 -08003930void AudioFlinger::DirectOutputThread::cacheParameters_l()
3931{
3932 PlaybackThread::cacheParameters_l();
3933
3934 // use shorter standby delay as on normal output to release
3935 // hardware resources as soon as possible
3936 standbyDelay = microseconds(activeSleepTime*2);
3937}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003938
Mathias Agopian65ab4712010-07-14 17:59:35 -07003939// ----------------------------------------------------------------------------
3940
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003941AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003942 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003943 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3944 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003945{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003946 addOutputTrack(mainThread);
3947}
3948
3949AudioFlinger::DuplicatingThread::~DuplicatingThread()
3950{
3951 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3952 mOutputTracks[i]->destroy();
3953 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003954}
3955
Glenn Kasten000f0e32012-03-01 17:10:56 -08003956void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003957{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003958 // mix buffers...
3959 if (outputsReady(outputTracks)) {
3960 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3961 } else {
3962 memset(mMixBuffer, 0, mixBufferSize);
3963 }
3964 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003965 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003966 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003967}
3968
3969void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3970{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003971 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003972 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003973 sleepTime = activeSleepTime;
3974 } else {
3975 sleepTime = idleSleepTime;
3976 }
3977 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003978 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3979 writeFrames = mNormalFrameCount;
3980 memset(mMixBuffer, 0, mixBufferSize);
3981 } else {
3982 // flush remaining overflow buffers in output tracks
3983 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003984 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003985 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003986 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003987}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003988
Glenn Kasten000f0e32012-03-01 17:10:56 -08003989void AudioFlinger::DuplicatingThread::threadLoop_write()
3990{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003991 for (size_t i = 0; i < outputTracks.size(); i++) {
3992 outputTracks[i]->write(mMixBuffer, writeFrames);
3993 }
3994 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003995}
Glenn Kasten688a6402012-02-29 07:57:06 -08003996
Glenn Kasten000f0e32012-03-01 17:10:56 -08003997void AudioFlinger::DuplicatingThread::threadLoop_standby()
3998{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003999 // DuplicatingThread implements standby by stopping all tracks
4000 for (size_t i = 0; i < outputTracks.size(); i++) {
4001 outputTracks[i]->stop();
4002 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004003}
4004
Glenn Kastenfa26a852012-03-06 11:28:04 -08004005void AudioFlinger::DuplicatingThread::saveOutputTracks()
4006{
4007 outputTracks = mOutputTracks;
4008}
4009
4010void AudioFlinger::DuplicatingThread::clearOutputTracks()
4011{
4012 outputTracks.clear();
4013}
4014
Mathias Agopian65ab4712010-07-14 17:59:35 -07004015void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4016{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004017 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004018 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004019 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004020 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004021 this,
4022 mSampleRate,
4023 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004024 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004025 frameCount);
4026 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004027 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004028 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004029 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004030 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004031 }
4032}
4033
4034void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4035{
4036 Mutex::Autolock _l(mLock);
4037 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004038 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004039 mOutputTracks[i]->destroy();
4040 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004041 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004042 return;
4043 }
4044 }
Steve Block3856b092011-10-20 11:56:00 +01004045 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004046}
4047
Glenn Kasten438b0362012-03-06 11:24:48 -08004048// caller must hold mLock
4049void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004050{
4051 mWaitTimeMs = UINT_MAX;
4052 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4053 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004054 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004055 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4056 if (waitTimeMs < mWaitTimeMs) {
4057 mWaitTimeMs = waitTimeMs;
4058 }
4059 }
4060 }
4061}
4062
4063
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004064bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004065{
4066 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004067 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004068 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004069 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004070 return false;
4071 }
4072 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004073 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004074 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004075 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004076 return false;
4077 }
4078 }
4079 return true;
4080}
4081
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004082uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004083{
4084 return (mWaitTimeMs * 1000) / 2;
4085}
4086
Glenn Kasten66fcab92012-02-24 14:59:21 -08004087void AudioFlinger::DuplicatingThread::cacheParameters_l()
4088{
4089 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4090 updateWaitTime_l();
4091
4092 MixerThread::cacheParameters_l();
4093}
4094
Mathias Agopian65ab4712010-07-14 17:59:35 -07004095// ----------------------------------------------------------------------------
4096
4097// TrackBase constructor must be called with AudioFlinger::mLock held
4098AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004099 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004100 const sp<Client>& client,
4101 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004102 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004103 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004104 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004105 const sp<IMemory>& sharedBuffer,
4106 int sessionId)
4107 : RefBase(),
4108 mThread(thread),
4109 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004110 mCblk(NULL),
4111 // mBuffer
4112 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004113 mFrameCount(0),
4114 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004115 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004116 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004117 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004118 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004119 // mChannelCount
4120 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004121{
Steve Block3856b092011-10-20 11:56:00 +01004122 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004123
Steve Blockb8a80522011-12-20 16:23:08 +00004124 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004125 size_t size = sizeof(audio_track_cblk_t);
4126 uint8_t channelCount = popcount(channelMask);
4127 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4128 if (sharedBuffer == 0) {
4129 size += bufferSize;
4130 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004131
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004132 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004133 mCblkMemory = client->heap()->allocate(size);
4134 if (mCblkMemory != 0) {
4135 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004136 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004137 new(mCblk) audio_track_cblk_t();
4138 // clear all buffers
4139 mCblk->frameCount = frameCount;
4140 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004141// uncomment the following lines to quickly test 32-bit wraparound
4142// mCblk->user = 0xffff0000;
4143// mCblk->server = 0xffff0000;
4144// mCblk->userBase = 0xffff0000;
4145// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004146 mChannelCount = channelCount;
4147 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004148 if (sharedBuffer == 0) {
4149 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4150 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4151 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004152 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004153 mCblk->flags = CBLK_UNDERRUN_ON;
4154 } else {
4155 mBuffer = sharedBuffer->pointer();
4156 }
4157 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4158 }
4159 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004160 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004161 client->heap()->dump("AudioTrack");
4162 return;
4163 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004164 } else {
4165 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004166 // construct the shared structure in-place.
4167 new(mCblk) audio_track_cblk_t();
4168 // clear all buffers
4169 mCblk->frameCount = frameCount;
4170 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004171// uncomment the following lines to quickly test 32-bit wraparound
4172// mCblk->user = 0xffff0000;
4173// mCblk->server = 0xffff0000;
4174// mCblk->userBase = 0xffff0000;
4175// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004176 mChannelCount = channelCount;
4177 mChannelMask = channelMask;
4178 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4179 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4180 // Force underrun condition to avoid false underrun callback until first data is
4181 // written to buffer (other flags are cleared)
4182 mCblk->flags = CBLK_UNDERRUN_ON;
4183 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004184 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004185}
4186
4187AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4188{
Glenn Kastena0d68332012-01-27 16:47:15 -08004189 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004190 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004191 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004192 } else {
4193 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004194 }
4195 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004196 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004197 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004198 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004199 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004200 // If the client's reference count drops to zero, the associated destructor
4201 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4202 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203 mClient.clear();
4204 }
4205}
4206
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004207// AudioBufferProvider interface
4208// getNextBuffer() = 0;
4209// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004210void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4211{
Glenn Kastene0feee32011-12-13 11:53:26 -08004212 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004213 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004214 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004215 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004216 buffer->frameCount = 0;
4217}
4218
4219bool AudioFlinger::ThreadBase::TrackBase::step() {
4220 bool result;
4221 audio_track_cblk_t* cblk = this->cblk();
4222
4223 result = cblk->stepServer(mFrameCount);
4224 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004225 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004226 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004227 }
4228 return result;
4229}
4230
4231void AudioFlinger::ThreadBase::TrackBase::reset() {
4232 audio_track_cblk_t* cblk = this->cblk();
4233
4234 cblk->user = 0;
4235 cblk->server = 0;
4236 cblk->userBase = 0;
4237 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004238 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004239 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004240}
4241
Mathias Agopian65ab4712010-07-14 17:59:35 -07004242int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4243 return (int)mCblk->sampleRate;
4244}
4245
Mathias Agopian65ab4712010-07-14 17:59:35 -07004246void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4247 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004248 size_t frameSize = cblk->frameSize;
4249 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4250 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004251
4252 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004253 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4254 "TrackBase::getBuffer buffer out of range:\n"
4255 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4256 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004257 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004258 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004259
4260 return bufferStart;
4261}
4262
Eric Laurenta011e352012-03-29 15:51:43 -07004263status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4264{
4265 mSyncEvents.add(event);
4266 return NO_ERROR;
4267}
4268
Mathias Agopian65ab4712010-07-14 17:59:35 -07004269// ----------------------------------------------------------------------------
4270
4271// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4272AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004273 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004274 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004275 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004276 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004277 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004278 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004279 int frameCount,
4280 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004281 int sessionId,
4282 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004283 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004284 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004285 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004286 // mRetryCount initialized later when needed
4287 mSharedBuffer(sharedBuffer),
4288 mStreamType(streamType),
4289 mName(-1), // see note below
4290 mMainBuffer(thread->mixBuffer()),
4291 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004292 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004293 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004294 mFlags(flags),
4295 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004296 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004297 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004298{
4299 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004300 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4301 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004302 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004303 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Glenn Kasten254af182012-07-03 14:59:05 -07004304 mName = thread->getTrackName_l(channelMask);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004305 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004306 if (mName < 0) {
4307 ALOGE("no more track names available");
4308 return;
4309 }
4310 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004311 if (flags & IAudioFlinger::TRACK_FAST) {
4312 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4313 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4314 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004315 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004316 // FIXME This is too eager. We allocate a fast track index before the
4317 // fast track becomes active. Since fast tracks are a scarce resource,
4318 // this means we are potentially denying other more important fast tracks from
4319 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004320 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004321 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004322 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004323 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004324 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004325 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004326 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004327 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004328}
4329
4330AudioFlinger::PlaybackThread::Track::~Track()
4331{
Steve Block3856b092011-10-20 11:56:00 +01004332 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004333}
4334
4335void AudioFlinger::PlaybackThread::Track::destroy()
4336{
4337 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4338 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004339 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004340 // we must acquire a strong reference on this Track before locking mLock
4341 // here so that the destructor is called only when exiting this function.
4342 // On the other hand, as long as Track::destroy() is only called by
4343 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4344 // this Track with its member mTrack.
4345 sp<Track> keep(this);
4346 { // scope for mLock
4347 sp<ThreadBase> thread = mThread.promote();
4348 if (thread != 0) {
4349 if (!isOutputTrack()) {
4350 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004351 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004352
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004353#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004354 // to track the speaker usage
4355 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004356#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004357 }
4358 AudioSystem::releaseOutput(thread->id());
4359 }
4360 Mutex::Autolock _l(thread->mLock);
4361 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4362 playbackThread->destroyTrack_l(this);
4363 }
4364 }
4365}
4366
Glenn Kasten288ed212012-04-25 17:52:27 -07004367/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4368{
Glenn Kastene213c862012-04-25 13:46:15 -07004369 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 -07004370 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004371}
4372
Mathias Agopian65ab4712010-07-14 17:59:35 -07004373void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4374{
Glenn Kasten83d86532012-01-17 14:39:34 -08004375 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004376 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004377 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004378 } else {
4379 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4380 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004381 track_state state = mState;
4382 char stateChar;
4383 switch (state) {
4384 case IDLE:
4385 stateChar = 'I';
4386 break;
4387 case TERMINATED:
4388 stateChar = 'T';
4389 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004390 case STOPPING_1:
4391 stateChar = 's';
4392 break;
4393 case STOPPING_2:
4394 stateChar = '5';
4395 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004396 case STOPPED:
4397 stateChar = 'S';
4398 break;
4399 case RESUMING:
4400 stateChar = 'R';
4401 break;
4402 case ACTIVE:
4403 stateChar = 'A';
4404 break;
4405 case PAUSING:
4406 stateChar = 'p';
4407 break;
4408 case PAUSED:
4409 stateChar = 'P';
4410 break;
Eric Laurent29864602012-05-08 18:57:51 -07004411 case FLUSHED:
4412 stateChar = 'F';
4413 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004414 default:
4415 stateChar = '?';
4416 break;
4417 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004418 char nowInUnderrun;
4419 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4420 case UNDERRUN_FULL:
4421 nowInUnderrun = ' ';
4422 break;
4423 case UNDERRUN_PARTIAL:
4424 nowInUnderrun = '<';
4425 break;
4426 case UNDERRUN_EMPTY:
4427 nowInUnderrun = '*';
4428 break;
4429 default:
4430 nowInUnderrun = '?';
4431 break;
4432 }
Glenn Kastene213c862012-04-25 13:46:15 -07004433 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4434 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004435 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004436 mStreamType,
4437 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004438 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004439 mSessionId,
4440 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004441 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004442 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004443 mMute,
4444 mFillingUpStatus,
4445 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004446 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4447 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004448 mCblk->server,
4449 mCblk->user,
4450 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004451 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004452 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004453 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004454 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004455}
4456
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004457// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004458status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004459 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004460{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004461 audio_track_cblk_t* cblk = this->cblk();
4462 uint32_t framesReady;
4463 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004464
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004465 // Check if last stepServer failed, try to step now
4466 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004467 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4468 // Since the fast mixer is higher priority than client callback thread,
4469 // it does not result in priority inversion for client.
4470 // But a non-blocking solution would be preferable to avoid
4471 // fast mixer being unable to tryLock(), and
4472 // to avoid the extra context switches if the client wakes up,
4473 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004474 if (!step()) goto getNextBuffer_exit;
4475 ALOGV("stepServer recovered");
4476 mStepServerFailed = false;
4477 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004478
Glenn Kasten288ed212012-04-25 17:52:27 -07004479 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004480 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004481
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004482 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004483 uint32_t s = cblk->server;
4484 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4485
4486 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4487 if (framesReq > framesReady) {
4488 framesReq = framesReady;
4489 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004490 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004491 framesReq = bufferEnd - s;
4492 }
4493
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004494 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004495 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004496 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004497 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004498
4499getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004500 buffer->raw = NULL;
4501 buffer->frameCount = 0;
4502 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4503 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004504}
4505
Glenn Kasten288ed212012-04-25 17:52:27 -07004506// Note that framesReady() takes a mutex on the control block using tryLock().
4507// This could result in priority inversion if framesReady() is called by the normal mixer,
4508// as the normal mixer thread runs at lower
4509// priority than the client's callback thread: there is a short window within framesReady()
4510// during which the normal mixer could be preempted, and the client callback would block.
4511// Another problem can occur if framesReady() is called by the fast mixer:
4512// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4513// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4514size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004515 return mCblk->framesReady();
4516}
4517
Glenn Kasten288ed212012-04-25 17:52:27 -07004518// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004519bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004520 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004521
John Grossman4ff14ba2012-02-08 16:37:41 -08004522 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004523 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4524 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004525 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004526 return true;
4527 }
4528 return false;
4529}
4530
Glenn Kasten3acbd052012-02-28 10:39:56 -08004531status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004532 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004533{
4534 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004535 ALOGV("start(%d), calling pid %d session %d",
4536 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004537
Mathias Agopian65ab4712010-07-14 17:59:35 -07004538 sp<ThreadBase> thread = mThread.promote();
4539 if (thread != 0) {
4540 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004541 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004542 // here the track could be either new, or restarted
4543 // in both cases "unstop" the track
4544 if (mState == PAUSED) {
4545 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004546 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004547 } else {
4548 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004549 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004550 }
4551
4552 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4553 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004554 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004555 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004556
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004557#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004558 // to track the speaker usage
4559 if (status == NO_ERROR) {
4560 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4561 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004562#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004563 }
4564 if (status == NO_ERROR) {
4565 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4566 playbackThread->addTrack_l(this);
4567 } else {
4568 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004569 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004570 }
4571 } else {
4572 status = BAD_VALUE;
4573 }
4574 return status;
4575}
4576
4577void AudioFlinger::PlaybackThread::Track::stop()
4578{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004579 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004580 sp<ThreadBase> thread = mThread.promote();
4581 if (thread != 0) {
4582 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004583 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004584 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004585 // If the track is not active (PAUSED and buffers full), flush buffers
4586 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4587 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4588 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004589 mState = STOPPED;
4590 } else if (!isFastTrack()) {
4591 mState = STOPPED;
4592 } else {
4593 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4594 // and then to STOPPED and reset() when presentation is complete
4595 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004596 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004597 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004598 }
4599 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4600 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004601 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004602 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004603
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004604#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004605 // to track the speaker usage
4606 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004607#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004608 }
4609 }
4610}
4611
4612void AudioFlinger::PlaybackThread::Track::pause()
4613{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004614 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004615 sp<ThreadBase> thread = mThread.promote();
4616 if (thread != 0) {
4617 Mutex::Autolock _l(thread->mLock);
4618 if (mState == ACTIVE || mState == RESUMING) {
4619 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004620 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004621 if (!isOutputTrack()) {
4622 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004623 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004624 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004625
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004626#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004627 // to track the speaker usage
4628 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004629#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004630 }
4631 }
4632 }
4633}
4634
4635void AudioFlinger::PlaybackThread::Track::flush()
4636{
Steve Block3856b092011-10-20 11:56:00 +01004637 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004638 sp<ThreadBase> thread = mThread.promote();
4639 if (thread != 0) {
4640 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004641 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4642 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004643 return;
4644 }
4645 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004646 // FLUSHED state
4647 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004648 // do not reset the track if it is still in the process of being stopped or paused.
4649 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004650 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004651 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004652 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4653 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4654 reset();
4655 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004656 }
4657}
4658
4659void AudioFlinger::PlaybackThread::Track::reset()
4660{
4661 // Do not reset twice to avoid discarding data written just after a flush and before
4662 // the audioflinger thread detects the track is stopped.
4663 if (!mResetDone) {
4664 TrackBase::reset();
4665 // Force underrun condition to avoid false underrun callback until first data is
4666 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004667 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4668 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004669 mFillingUpStatus = FS_FILLING;
4670 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004671 if (mState == FLUSHED) {
4672 mState = IDLE;
4673 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004674 }
4675}
4676
4677void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4678{
4679 mMute = muted;
4680}
4681
Mathias Agopian65ab4712010-07-14 17:59:35 -07004682status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4683{
4684 status_t status = DEAD_OBJECT;
4685 sp<ThreadBase> thread = mThread.promote();
4686 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004687 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004688 sp<AudioFlinger> af = mClient->audioFlinger();
4689
4690 Mutex::Autolock _l(af->mLock);
4691
4692 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004693
Eric Laurent109347d2012-07-02 12:31:03 -07004694 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004695 Mutex::Autolock _dl(playbackThread->mLock);
4696 Mutex::Autolock _sl(srcThread->mLock);
4697 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4698 if (chain == 0) {
4699 return INVALID_OPERATION;
4700 }
4701
4702 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4703 if (effect == 0) {
4704 return INVALID_OPERATION;
4705 }
4706 srcThread->removeEffect_l(effect);
4707 playbackThread->addEffect_l(effect);
4708 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4709 if (effect->state() == EffectModule::ACTIVE ||
4710 effect->state() == EffectModule::STOPPING) {
4711 effect->start();
4712 }
4713
4714 sp<EffectChain> dstChain = effect->chain().promote();
4715 if (dstChain == 0) {
4716 srcThread->addEffect_l(effect);
4717 return INVALID_OPERATION;
4718 }
4719 AudioSystem::unregisterEffect(effect->id());
4720 AudioSystem::registerEffect(&effect->desc(),
4721 srcThread->id(),
4722 dstChain->strategy(),
4723 AUDIO_SESSION_OUTPUT_MIX,
4724 effect->id());
4725 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004726 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004727 }
4728 return status;
4729}
4730
4731void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4732{
4733 mAuxEffectId = EffectId;
4734 mAuxBuffer = buffer;
4735}
4736
Eric Laurenta011e352012-03-29 15:51:43 -07004737bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4738 size_t audioHalFrames)
4739{
4740 // a track is considered presented when the total number of frames written to audio HAL
4741 // corresponds to the number of frames written when presentationComplete() is called for the
4742 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4743 if (mPresentationCompleteFrames == 0) {
4744 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4745 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4746 mPresentationCompleteFrames, audioHalFrames);
4747 }
4748 if (framesWritten >= mPresentationCompleteFrames) {
4749 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4750 mSessionId, framesWritten);
4751 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004752 return true;
4753 }
4754 return false;
4755}
4756
4757void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4758{
4759 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4760 if (mSyncEvents[i]->type() == type) {
4761 mSyncEvents[i]->trigger();
4762 mSyncEvents.removeAt(i);
4763 i--;
4764 }
4765 }
4766}
4767
Glenn Kasten58912562012-04-03 10:45:00 -07004768// implement VolumeBufferProvider interface
4769
4770uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4771{
4772 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4773 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4774 uint32_t vlr = mCblk->getVolumeLR();
4775 uint32_t vl = vlr & 0xFFFF;
4776 uint32_t vr = vlr >> 16;
4777 // track volumes come from shared memory, so can't be trusted and must be clamped
4778 if (vl > MAX_GAIN_INT) {
4779 vl = MAX_GAIN_INT;
4780 }
4781 if (vr > MAX_GAIN_INT) {
4782 vr = MAX_GAIN_INT;
4783 }
4784 // now apply the cached master volume and stream type volume;
4785 // this is trusted but lacks any synchronization or barrier so may be stale
4786 float v = mCachedVolume;
4787 vl *= v;
4788 vr *= v;
4789 // re-combine into U4.16
4790 vlr = (vr << 16) | (vl & 0xFFFF);
4791 // FIXME look at mute, pause, and stop flags
4792 return vlr;
4793}
Eric Laurenta011e352012-03-29 15:51:43 -07004794
Eric Laurent29864602012-05-08 18:57:51 -07004795status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4796{
4797 if (mState == TERMINATED || mState == PAUSED ||
4798 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4799 (mState == STOPPED)))) {
4800 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4801 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4802 event->cancel();
4803 return INVALID_OPERATION;
4804 }
4805 TrackBase::setSyncEvent(event);
4806 return NO_ERROR;
4807}
4808
John Grossman4ff14ba2012-02-08 16:37:41 -08004809// timed audio tracks
4810
4811sp<AudioFlinger::PlaybackThread::TimedTrack>
4812AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004813 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004814 const sp<Client>& client,
4815 audio_stream_type_t streamType,
4816 uint32_t sampleRate,
4817 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004818 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004819 int frameCount,
4820 const sp<IMemory>& sharedBuffer,
4821 int sessionId) {
4822 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004823 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004824
Glenn Kastena0356762012-03-19 10:38:51 -07004825 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004826 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4827 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004828}
4829
4830AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004831 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004832 const sp<Client>& client,
4833 audio_stream_type_t streamType,
4834 uint32_t sampleRate,
4835 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004836 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004837 int frameCount,
4838 const sp<IMemory>& sharedBuffer,
4839 int sessionId)
4840 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004841 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004842 mQueueHeadInFlight(false),
4843 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004844 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004845 mTimedSilenceBuffer(NULL),
4846 mTimedSilenceBufferSize(0),
4847 mTimedAudioOutputOnTime(false),
4848 mMediaTimeTransformValid(false)
4849{
4850 LocalClock lc;
4851 mLocalTimeFreq = lc.getLocalFreq();
4852
4853 mLocalTimeToSampleTransform.a_zero = 0;
4854 mLocalTimeToSampleTransform.b_zero = 0;
4855 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4856 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4857 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4858 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004859
4860 mMediaTimeToSampleTransform.a_zero = 0;
4861 mMediaTimeToSampleTransform.b_zero = 0;
4862 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4863 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4864 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4865 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004866}
4867
4868AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4869 mClient->releaseTimedTrack();
4870 delete [] mTimedSilenceBuffer;
4871}
4872
4873status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4874 size_t size, sp<IMemory>* buffer) {
4875
4876 Mutex::Autolock _l(mTimedBufferQueueLock);
4877
4878 trimTimedBufferQueue_l();
4879
4880 // lazily initialize the shared memory heap for timed buffers
4881 if (mTimedMemoryDealer == NULL) {
4882 const int kTimedBufferHeapSize = 512 << 10;
4883
4884 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4885 "AudioFlingerTimed");
4886 if (mTimedMemoryDealer == NULL)
4887 return NO_MEMORY;
4888 }
4889
4890 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4891 if (newBuffer == NULL) {
4892 newBuffer = mTimedMemoryDealer->allocate(size);
4893 if (newBuffer == NULL)
4894 return NO_MEMORY;
4895 }
4896
4897 *buffer = newBuffer;
4898 return NO_ERROR;
4899}
4900
4901// caller must hold mTimedBufferQueueLock
4902void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4903 int64_t mediaTimeNow;
4904 {
4905 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4906 if (!mMediaTimeTransformValid)
4907 return;
4908
4909 int64_t targetTimeNow;
4910 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4911 ? mCCHelper.getCommonTime(&targetTimeNow)
4912 : mCCHelper.getLocalTime(&targetTimeNow);
4913
4914 if (OK != res)
4915 return;
4916
4917 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4918 &mediaTimeNow)) {
4919 return;
4920 }
4921 }
4922
John Grossman1c345192012-03-27 14:00:17 -07004923 size_t trimEnd;
4924 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004925 int64_t bufEnd;
4926
John Grossmanc95cfbb2012-04-12 11:53:11 -07004927 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4928 // We have a next buffer. Just use its PTS as the PTS of the frame
4929 // following the last frame in this buffer. If the stream is sparse
4930 // (ie, there are deliberate gaps left in the stream which should be
4931 // filled with silence by the TimedAudioTrack), then this can result
4932 // in one extra buffer being left un-trimmed when it could have
4933 // been. In general, this is not typical, and we would rather
4934 // optimized away the TS calculation below for the more common case
4935 // where PTSes are contiguous.
4936 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4937 } else {
4938 // We have no next buffer. Compute the PTS of the frame following
4939 // the last frame in this buffer by computing the duration of of
4940 // this frame in media time units and adding it to the PTS of the
4941 // buffer.
4942 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4943 / mCblk->frameSize;
4944
4945 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4946 &bufEnd)) {
4947 ALOGE("Failed to convert frame count of %lld to media time"
4948 " duration" " (scale factor %d/%u) in %s",
4949 frameCount,
4950 mMediaTimeToSampleTransform.a_to_b_numer,
4951 mMediaTimeToSampleTransform.a_to_b_denom,
4952 __PRETTY_FUNCTION__);
4953 break;
4954 }
4955 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004956 }
John Grossman9fbdee12012-03-26 17:51:46 -07004957
4958 if (bufEnd > mediaTimeNow)
4959 break;
4960
4961 // Is the buffer we want to use in the middle of a mix operation right
4962 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4963 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004964 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004965 mTrimQueueHeadOnRelease = true;
4966 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004967 }
4968
John Grossman9fbdee12012-03-26 17:51:46 -07004969 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004970 if (trimStart < trimEnd) {
4971 // Update the bookkeeping for framesReady()
4972 for (size_t i = trimStart; i < trimEnd; ++i) {
4973 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4974 }
4975
4976 // Now actually remove the buffers from the queue.
4977 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004978 }
4979}
4980
John Grossman1c345192012-03-27 14:00:17 -07004981void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4982 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004983 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4984 "%s called (reason \"%s\"), but timed buffer queue has no"
4985 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004986
4987 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4988 mTimedBufferQueue.removeAt(0);
4989}
4990
4991void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4992 const TimedBuffer& buf,
4993 const char* logTag) {
4994 uint32_t bufBytes = buf.buffer()->size();
4995 uint32_t consumedAlready = buf.position();
4996
Eric Laurentb388e532012-04-14 13:32:48 -07004997 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004998 "Bad bookkeeping while updating frames pending. Timed buffer is"
4999 " only %u bytes long, but claims to have consumed %u"
5000 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07005001 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005002
5003 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07005004 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5005 "Bad bookkeeping while updating frames pending. Should have at"
5006 " least %u queued frames, but we think we have only %u. (update"
5007 " reason: \"%s\")",
5008 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005009
5010 mFramesPendingInQueue -= bufFrames;
5011}
5012
John Grossman4ff14ba2012-02-08 16:37:41 -08005013status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5014 const sp<IMemory>& buffer, int64_t pts) {
5015
5016 {
5017 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5018 if (!mMediaTimeTransformValid)
5019 return INVALID_OPERATION;
5020 }
5021
5022 Mutex::Autolock _l(mTimedBufferQueueLock);
5023
John Grossman1c345192012-03-27 14:00:17 -07005024 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5025 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005026 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5027
5028 return NO_ERROR;
5029}
5030
5031status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5032 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5033
John Grossman1c345192012-03-27 14:00:17 -07005034 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5035 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5036 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005037
5038 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5039 target == TimedAudioTrack::COMMON_TIME)) {
5040 return BAD_VALUE;
5041 }
5042
5043 Mutex::Autolock lock(mMediaTimeTransformLock);
5044 mMediaTimeTransform = xform;
5045 mMediaTimeTransformTarget = target;
5046 mMediaTimeTransformValid = true;
5047
5048 return NO_ERROR;
5049}
5050
5051#define min(a, b) ((a) < (b) ? (a) : (b))
5052
5053// implementation of getNextBuffer for tracks whose buffers have timestamps
5054status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5055 AudioBufferProvider::Buffer* buffer, int64_t pts)
5056{
5057 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005058 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005059 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005060 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005061 return INVALID_OPERATION;
5062 }
5063
John Grossman4ff14ba2012-02-08 16:37:41 -08005064 Mutex::Autolock _l(mTimedBufferQueueLock);
5065
John Grossman9fbdee12012-03-26 17:51:46 -07005066 ALOG_ASSERT(!mQueueHeadInFlight,
5067 "getNextBuffer called without releaseBuffer!");
5068
John Grossman4ff14ba2012-02-08 16:37:41 -08005069 while (true) {
5070
5071 // if we have no timed buffers, then fail
5072 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005073 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005074 buffer->frameCount = 0;
5075 return NOT_ENOUGH_DATA;
5076 }
5077
5078 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5079
5080 // calculate the PTS of the head of the timed buffer queue expressed in
5081 // local time
5082 int64_t headLocalPTS;
5083 {
5084 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5085
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005086 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005087
5088 if (mMediaTimeTransform.a_to_b_denom == 0) {
5089 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005090 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005091 return NO_ERROR;
5092 }
5093
5094 int64_t transformedPTS;
5095 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5096 &transformedPTS)) {
5097 // the transform failed. this shouldn't happen, but if it does
5098 // then just drop this buffer
5099 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005100 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005101 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005102 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005103 return NO_ERROR;
5104 }
5105
5106 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5107 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5108 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005109 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005110 buffer->frameCount = 0;
5111 return INVALID_OPERATION;
5112 }
5113 } else {
5114 headLocalPTS = transformedPTS;
5115 }
5116 }
5117
5118 // adjust the head buffer's PTS to reflect the portion of the head buffer
5119 // that has already been consumed
5120 int64_t effectivePTS = headLocalPTS +
5121 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5122
5123 // Calculate the delta in samples between the head of the input buffer
5124 // queue and the start of the next output buffer that will be written.
5125 // If the transformation fails because of over or underflow, it means
5126 // that the sample's position in the output stream is so far out of
5127 // whack that it should just be dropped.
5128 int64_t sampleDelta;
5129 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5130 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005131 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5132 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005133 continue;
5134 }
5135 if (!mLocalTimeToSampleTransform.doForwardTransform(
5136 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005137 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005138 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005139 continue;
5140 }
5141
John Grossman1c345192012-03-27 14:00:17 -07005142 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5143 " sampleDelta=[%d.%08x]",
5144 head.pts(), head.position(), pts,
5145 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5146 + (sampleDelta >> 32)),
5147 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005148
5149 // if the delta between the ideal placement for the next input sample and
5150 // the current output position is within this threshold, then we will
5151 // concatenate the next input samples to the previous output
5152 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005153 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005154
5155 // if this is the first buffer of audio that we're emitting from this track
5156 // then it should be almost exactly on time.
5157 const int64_t kSampleStartupThreshold = 1LL << 32;
5158
5159 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005160 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005161 // the next input is close enough to being on time, so concatenate it
5162 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005163 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005164
John Grossman1c345192012-03-27 14:00:17 -07005165 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5166 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005167 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005168 }
5169
5170 // Looks like our output is not on time. Reset our on timed status.
5171 // Next time we mix samples from our input queue, then should be within
5172 // the StartupThreshold.
5173 mTimedAudioOutputOnTime = false;
5174 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005175 // the gap between the current output position and the proper start of
5176 // the next input sample is too big, so fill it with silence
5177 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5178
John Grossman9fbdee12012-03-26 17:51:46 -07005179 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005180 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5181 return NO_ERROR;
5182 } else {
5183 // the next input sample is late
5184 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5185 size_t onTimeSamplePosition =
5186 head.position() + lateFrames * mCblk->frameSize;
5187
5188 if (onTimeSamplePosition > head.buffer()->size()) {
5189 // all the remaining samples in the head are too late, so
5190 // drop it and move on
5191 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005192 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005193 continue;
5194 } else {
5195 // skip over the late samples
5196 head.setPosition(onTimeSamplePosition);
5197
5198 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005199 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005200
5201 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5202 return NO_ERROR;
5203 }
5204 }
5205 }
5206}
5207
5208// Yield samples from the timed buffer queue head up to the given output
5209// buffer's capacity.
5210//
5211// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005212void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005213 AudioBufferProvider::Buffer* buffer) {
5214
5215 const TimedBuffer& head = mTimedBufferQueue[0];
5216
5217 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5218 head.position());
5219
5220 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5221 mCblk->frameSize);
5222 size_t framesRequested = buffer->frameCount;
5223 buffer->frameCount = min(framesLeftInHead, framesRequested);
5224
John Grossman9fbdee12012-03-26 17:51:46 -07005225 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005226 mTimedAudioOutputOnTime = true;
5227}
5228
5229// Yield samples of silence up to the given output buffer's capacity
5230//
5231// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005232void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005233 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5234
5235 // lazily allocate a buffer filled with silence
5236 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5237 delete [] mTimedSilenceBuffer;
5238 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5239 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5240 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5241 }
5242
5243 buffer->raw = mTimedSilenceBuffer;
5244 size_t framesRequested = buffer->frameCount;
5245 buffer->frameCount = min(numFrames, framesRequested);
5246
5247 mTimedAudioOutputOnTime = false;
5248}
5249
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005250// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005251void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5252 AudioBufferProvider::Buffer* buffer) {
5253
5254 Mutex::Autolock _l(mTimedBufferQueueLock);
5255
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005256 // If the buffer which was just released is part of the buffer at the head
5257 // of the queue, be sure to update the amt of the buffer which has been
5258 // consumed. If the buffer being returned is not part of the head of the
5259 // queue, its either because the buffer is part of the silence buffer, or
5260 // because the head of the timed queue was trimmed after the mixer called
5261 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005262 if (buffer->raw == mTimedSilenceBuffer) {
5263 ALOG_ASSERT(!mQueueHeadInFlight,
5264 "Queue head in flight during release of silence buffer!");
5265 goto done;
5266 }
5267
5268 ALOG_ASSERT(mQueueHeadInFlight,
5269 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5270 " head in flight.");
5271
5272 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005273 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005274
5275 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005276 void* end = reinterpret_cast<void*>(
5277 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5278 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005279
John Grossman9fbdee12012-03-26 17:51:46 -07005280 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5281 "released buffer not within the head of the timed buffer"
5282 " queue; qHead = [%p, %p], released buffer = %p",
5283 start, end, buffer->raw);
5284
5285 head.setPosition(head.position() +
5286 (buffer->frameCount * mCblk->frameSize));
5287 mQueueHeadInFlight = false;
5288
John Grossman1c345192012-03-27 14:00:17 -07005289 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5290 "Bad bookkeeping during releaseBuffer! Should have at"
5291 " least %u queued frames, but we think we have only %u",
5292 buffer->frameCount, mFramesPendingInQueue);
5293
5294 mFramesPendingInQueue -= buffer->frameCount;
5295
John Grossman9fbdee12012-03-26 17:51:46 -07005296 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5297 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005298 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005299 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005300 }
John Grossman9fbdee12012-03-26 17:51:46 -07005301 } else {
5302 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5303 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005304 }
5305
John Grossman9fbdee12012-03-26 17:51:46 -07005306done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005307 buffer->raw = 0;
5308 buffer->frameCount = 0;
5309}
5310
Glenn Kasten288ed212012-04-25 17:52:27 -07005311size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005312 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005313 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005314}
5315
5316AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5317 : mPTS(0), mPosition(0) {}
5318
5319AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5320 const sp<IMemory>& buffer, int64_t pts)
5321 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5322
Mathias Agopian65ab4712010-07-14 17:59:35 -07005323// ----------------------------------------------------------------------------
5324
5325// RecordTrack constructor must be called with AudioFlinger::mLock held
5326AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005327 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005328 const sp<Client>& client,
5329 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005330 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005331 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005332 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005333 int sessionId)
5334 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005335 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005336 mOverflow(false)
5337{
5338 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005339 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5340 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5341 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5342 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5343 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5344 } else {
5345 mCblk->frameSize = sizeof(int8_t);
5346 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005347 }
5348}
5349
5350AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5351{
Glenn Kasten510a3d62012-07-16 14:24:34 -07005352 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005353}
5354
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005355// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005356status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005357{
5358 audio_track_cblk_t* cblk = this->cblk();
5359 uint32_t framesAvail;
5360 uint32_t framesReq = buffer->frameCount;
5361
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005362 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005363 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005364 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005365 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005366 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005367 }
5368
5369 framesAvail = cblk->framesAvailable_l();
5370
Glenn Kastenf6b16782011-12-15 09:51:17 -08005371 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372 uint32_t s = cblk->server;
5373 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5374
5375 if (framesReq > framesAvail) {
5376 framesReq = framesAvail;
5377 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005378 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005379 framesReq = bufferEnd - s;
5380 }
5381
5382 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005383 buffer->frameCount = framesReq;
5384 return NO_ERROR;
5385 }
5386
5387getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005388 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005389 buffer->frameCount = 0;
5390 return NOT_ENOUGH_DATA;
5391}
5392
Glenn Kasten3acbd052012-02-28 10:39:56 -08005393status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005394 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005395{
5396 sp<ThreadBase> thread = mThread.promote();
5397 if (thread != 0) {
5398 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005399 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005400 } else {
5401 return BAD_VALUE;
5402 }
5403}
5404
5405void AudioFlinger::RecordThread::RecordTrack::stop()
5406{
5407 sp<ThreadBase> thread = mThread.promote();
5408 if (thread != 0) {
5409 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005410 recordThread->mLock.lock();
5411 bool doStop = recordThread->stop_l(this);
5412 if (doStop) {
5413 TrackBase::reset();
5414 // Force overrun condition to avoid false overrun callback until first data is
5415 // read from buffer
5416 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5417 }
5418 recordThread->mLock.unlock();
5419 if (doStop) {
5420 AudioSystem::stopInput(recordThread->id());
5421 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005422 }
5423}
5424
Glenn Kasten510a3d62012-07-16 14:24:34 -07005425/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
5426{
5427 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
5428}
5429
Mathias Agopian65ab4712010-07-14 17:59:35 -07005430void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5431{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005432 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005433 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005434 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005435 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005436 mSessionId,
5437 mFrameCount,
5438 mState,
5439 mCblk->sampleRate,
5440 mCblk->server,
5441 mCblk->user);
5442}
5443
5444
5445// ----------------------------------------------------------------------------
5446
5447AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005448 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005449 DuplicatingThread *sourceThread,
5450 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005451 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005452 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005453 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005454 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5455 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005456 mActive(false), mSourceThread(sourceThread)
5457{
5458
Mathias Agopian65ab4712010-07-14 17:59:35 -07005459 if (mCblk != NULL) {
5460 mCblk->flags |= CBLK_DIRECTION_OUT;
5461 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005462 mOutBuffer.frameCount = 0;
5463 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005464 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005465 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5466 mCblk, mBuffer, mCblk->buffers,
5467 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005468 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005469 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005470 }
5471}
5472
5473AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5474{
5475 clearBufferQueue();
5476}
5477
Glenn Kasten3acbd052012-02-28 10:39:56 -08005478status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005479 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005480{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005481 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005482 if (status != NO_ERROR) {
5483 return status;
5484 }
5485
5486 mActive = true;
5487 mRetryCount = 127;
5488 return status;
5489}
5490
5491void AudioFlinger::PlaybackThread::OutputTrack::stop()
5492{
5493 Track::stop();
5494 clearBufferQueue();
5495 mOutBuffer.frameCount = 0;
5496 mActive = false;
5497}
5498
5499bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5500{
5501 Buffer *pInBuffer;
5502 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005503 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005504 bool outputBufferFull = false;
5505 inBuffer.frameCount = frames;
5506 inBuffer.i16 = data;
5507
5508 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5509
5510 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005511 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005512 sp<ThreadBase> thread = mThread.promote();
5513 if (thread != 0) {
5514 MixerThread *mixerThread = (MixerThread *)thread.get();
5515 if (mCblk->frameCount > frames){
5516 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5517 uint32_t startFrames = (mCblk->frameCount - frames);
5518 pInBuffer = new Buffer;
5519 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5520 pInBuffer->frameCount = startFrames;
5521 pInBuffer->i16 = pInBuffer->mBuffer;
5522 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5523 mBufferQueue.add(pInBuffer);
5524 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005525 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005526 }
5527 }
5528 }
5529 }
5530
5531 while (waitTimeLeftMs) {
5532 // First write pending buffers, then new data
5533 if (mBufferQueue.size()) {
5534 pInBuffer = mBufferQueue.itemAt(0);
5535 } else {
5536 pInBuffer = &inBuffer;
5537 }
5538
5539 if (pInBuffer->frameCount == 0) {
5540 break;
5541 }
5542
5543 if (mOutBuffer.frameCount == 0) {
5544 mOutBuffer.frameCount = pInBuffer->frameCount;
5545 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005546 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005547 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005548 outputBufferFull = true;
5549 break;
5550 }
5551 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5552 if (waitTimeLeftMs >= waitTimeMs) {
5553 waitTimeLeftMs -= waitTimeMs;
5554 } else {
5555 waitTimeLeftMs = 0;
5556 }
5557 }
5558
5559 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5560 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5561 mCblk->stepUser(outFrames);
5562 pInBuffer->frameCount -= outFrames;
5563 pInBuffer->i16 += outFrames * channelCount;
5564 mOutBuffer.frameCount -= outFrames;
5565 mOutBuffer.i16 += outFrames * channelCount;
5566
5567 if (pInBuffer->frameCount == 0) {
5568 if (mBufferQueue.size()) {
5569 mBufferQueue.removeAt(0);
5570 delete [] pInBuffer->mBuffer;
5571 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005572 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005573 } else {
5574 break;
5575 }
5576 }
5577 }
5578
5579 // If we could not write all frames, allocate a buffer and queue it for next time.
5580 if (inBuffer.frameCount) {
5581 sp<ThreadBase> thread = mThread.promote();
5582 if (thread != 0 && !thread->standby()) {
5583 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5584 pInBuffer = new Buffer;
5585 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5586 pInBuffer->frameCount = inBuffer.frameCount;
5587 pInBuffer->i16 = pInBuffer->mBuffer;
5588 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5589 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005590 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005591 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005592 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005593 }
5594 }
5595 }
5596
5597 // Calling write() with a 0 length buffer, means that no more data will be written:
5598 // If no more buffers are pending, fill output track buffer to make sure it is started
5599 // by output mixer.
5600 if (frames == 0 && mBufferQueue.size() == 0) {
5601 if (mCblk->user < mCblk->frameCount) {
5602 frames = mCblk->frameCount - mCblk->user;
5603 pInBuffer = new Buffer;
5604 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5605 pInBuffer->frameCount = frames;
5606 pInBuffer->i16 = pInBuffer->mBuffer;
5607 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5608 mBufferQueue.add(pInBuffer);
5609 } else if (mActive) {
5610 stop();
5611 }
5612 }
5613
5614 return outputBufferFull;
5615}
5616
5617status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5618{
5619 int active;
5620 status_t result;
5621 audio_track_cblk_t* cblk = mCblk;
5622 uint32_t framesReq = buffer->frameCount;
5623
Steve Block3856b092011-10-20 11:56:00 +01005624// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005625 buffer->frameCount = 0;
5626
5627 uint32_t framesAvail = cblk->framesAvailable();
5628
5629
5630 if (framesAvail == 0) {
5631 Mutex::Autolock _l(cblk->lock);
5632 goto start_loop_here;
5633 while (framesAvail == 0) {
5634 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005635 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005636 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005637 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005638 }
5639 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5640 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005641 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005642 }
5643 // read the server count again
5644 start_loop_here:
5645 framesAvail = cblk->framesAvailable_l();
5646 }
5647 }
5648
5649// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005650// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005651// }
5652
5653 if (framesReq > framesAvail) {
5654 framesReq = framesAvail;
5655 }
5656
5657 uint32_t u = cblk->user;
5658 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5659
Marco Nelissena1472d92012-03-30 14:36:54 -07005660 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005661 framesReq = bufferEnd - u;
5662 }
5663
5664 buffer->frameCount = framesReq;
5665 buffer->raw = (void *)cblk->buffer(u);
5666 return NO_ERROR;
5667}
5668
5669
5670void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5671{
5672 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005673
5674 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005675 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005676 delete [] pBuffer->mBuffer;
5677 delete pBuffer;
5678 }
5679 mBufferQueue.clear();
5680}
5681
5682// ----------------------------------------------------------------------------
5683
5684AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5685 : RefBase(),
5686 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005687 // 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 -07005688 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005689 mPid(pid),
5690 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005691{
5692 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5693}
5694
5695// Client destructor must be called with AudioFlinger::mLock held
5696AudioFlinger::Client::~Client()
5697{
5698 mAudioFlinger->removeClient_l(mPid);
5699}
5700
Glenn Kasten435dbe62012-01-30 10:15:48 -08005701sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005702{
5703 return mMemoryDealer;
5704}
5705
John Grossman4ff14ba2012-02-08 16:37:41 -08005706// Reserve one of the limited slots for a timed audio track associated
5707// with this client
5708bool AudioFlinger::Client::reserveTimedTrack()
5709{
5710 const int kMaxTimedTracksPerClient = 4;
5711
5712 Mutex::Autolock _l(mTimedTrackLock);
5713
5714 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5715 ALOGW("can not create timed track - pid %d has exceeded the limit",
5716 mPid);
5717 return false;
5718 }
5719
5720 mTimedTrackCount++;
5721 return true;
5722}
5723
5724// Release a slot for a timed audio track
5725void AudioFlinger::Client::releaseTimedTrack()
5726{
5727 Mutex::Autolock _l(mTimedTrackLock);
5728 mTimedTrackCount--;
5729}
5730
Mathias Agopian65ab4712010-07-14 17:59:35 -07005731// ----------------------------------------------------------------------------
5732
5733AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5734 const sp<IAudioFlingerClient>& client,
5735 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005736 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005737{
5738}
5739
5740AudioFlinger::NotificationClient::~NotificationClient()
5741{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005742}
5743
5744void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5745{
5746 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005747 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005748}
5749
5750// ----------------------------------------------------------------------------
5751
5752AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5753 : BnAudioTrack(),
5754 mTrack(track)
5755{
5756}
5757
5758AudioFlinger::TrackHandle::~TrackHandle() {
5759 // just stop the track on deletion, associated resources
5760 // will be freed from the main thread once all pending buffers have
5761 // been played. Unless it's not in the active track list, in which
5762 // case we free everything now...
5763 mTrack->destroy();
5764}
5765
Glenn Kasten90716c52012-01-26 13:40:12 -08005766sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5767 return mTrack->getCblk();
5768}
5769
Glenn Kasten3acbd052012-02-28 10:39:56 -08005770status_t AudioFlinger::TrackHandle::start() {
5771 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005772}
5773
5774void AudioFlinger::TrackHandle::stop() {
5775 mTrack->stop();
5776}
5777
5778void AudioFlinger::TrackHandle::flush() {
5779 mTrack->flush();
5780}
5781
5782void AudioFlinger::TrackHandle::mute(bool e) {
5783 mTrack->mute(e);
5784}
5785
5786void AudioFlinger::TrackHandle::pause() {
5787 mTrack->pause();
5788}
5789
Mathias Agopian65ab4712010-07-14 17:59:35 -07005790status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5791{
5792 return mTrack->attachAuxEffect(EffectId);
5793}
5794
John Grossman4ff14ba2012-02-08 16:37:41 -08005795status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5796 sp<IMemory>* buffer) {
5797 if (!mTrack->isTimedTrack())
5798 return INVALID_OPERATION;
5799
5800 PlaybackThread::TimedTrack* tt =
5801 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5802 return tt->allocateTimedBuffer(size, buffer);
5803}
5804
5805status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5806 int64_t pts) {
5807 if (!mTrack->isTimedTrack())
5808 return INVALID_OPERATION;
5809
5810 PlaybackThread::TimedTrack* tt =
5811 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5812 return tt->queueTimedBuffer(buffer, pts);
5813}
5814
5815status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5816 const LinearTransform& xform, int target) {
5817
5818 if (!mTrack->isTimedTrack())
5819 return INVALID_OPERATION;
5820
5821 PlaybackThread::TimedTrack* tt =
5822 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5823 return tt->setMediaTimeTransform(
5824 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5825}
5826
Mathias Agopian65ab4712010-07-14 17:59:35 -07005827status_t AudioFlinger::TrackHandle::onTransact(
5828 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5829{
5830 return BnAudioTrack::onTransact(code, data, reply, flags);
5831}
5832
5833// ----------------------------------------------------------------------------
5834
5835sp<IAudioRecord> AudioFlinger::openRecord(
5836 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005837 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005838 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005839 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005840 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005841 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005842 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07005843 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005844 int *sessionId,
5845 status_t *status)
5846{
5847 sp<RecordThread::RecordTrack> recordTrack;
5848 sp<RecordHandle> recordHandle;
5849 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005850 status_t lStatus;
5851 RecordThread *thread;
5852 size_t inFrameCount;
5853 int lSessionId;
5854
5855 // check calling permissions
5856 if (!recordingAllowed()) {
5857 lStatus = PERMISSION_DENIED;
5858 goto Exit;
5859 }
5860
5861 // add client to list
5862 { // scope for mLock
5863 Mutex::Autolock _l(mLock);
5864 thread = checkRecordThread_l(input);
5865 if (thread == NULL) {
5866 lStatus = BAD_VALUE;
5867 goto Exit;
5868 }
5869
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005870 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005871
5872 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005873 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005874 lSessionId = *sessionId;
5875 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005876 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005877 if (sessionId != NULL) {
5878 *sessionId = lSessionId;
5879 }
5880 }
5881 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07005882 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5883 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005884 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005885 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005886 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5887 // destructor is called by the TrackBase destructor with mLock held
5888 client.clear();
5889 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005890 goto Exit;
5891 }
5892
5893 // return to handle to client
5894 recordHandle = new RecordHandle(recordTrack);
5895 lStatus = NO_ERROR;
5896
5897Exit:
5898 if (status) {
5899 *status = lStatus;
5900 }
5901 return recordHandle;
5902}
5903
5904// ----------------------------------------------------------------------------
5905
5906AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5907 : BnAudioRecord(),
5908 mRecordTrack(recordTrack)
5909{
5910}
5911
5912AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005913 stop_nonvirtual();
Glenn Kasten510a3d62012-07-16 14:24:34 -07005914 mRecordTrack->destroy();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005915}
5916
Glenn Kasten90716c52012-01-26 13:40:12 -08005917sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5918 return mRecordTrack->getCblk();
5919}
5920
Glenn Kasten0ec23ce2012-07-10 12:56:08 -07005921status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005922 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005923 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005924}
5925
5926void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005927 stop_nonvirtual();
5928}
5929
5930void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01005931 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005932 mRecordTrack->stop();
5933}
5934
Mathias Agopian65ab4712010-07-14 17:59:35 -07005935status_t AudioFlinger::RecordHandle::onTransact(
5936 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5937{
5938 return BnAudioRecord::onTransact(code, data, reply, flags);
5939}
5940
5941// ----------------------------------------------------------------------------
5942
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005943AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5944 AudioStreamIn *input,
5945 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07005946 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005947 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07005948 audio_devices_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005949 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten510a3d62012-07-16 14:24:34 -07005950 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005951 // mRsmpInIndex and mInputBytes set by readInputParameters()
Glenn Kasten254af182012-07-03 14:59:05 -07005952 mReqChannelCount(popcount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005953 mReqSampleRate(sampleRate)
5954 // mBytesRead is only meaningful while active, and so is cleared in start()
5955 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005956{
Glenn Kasten480b4682012-02-28 12:30:08 -08005957 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005958
Mathias Agopian65ab4712010-07-14 17:59:35 -07005959 readInputParameters();
5960}
5961
5962
5963AudioFlinger::RecordThread::~RecordThread()
5964{
5965 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005966 delete mResampler;
5967 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005968}
5969
5970void AudioFlinger::RecordThread::onFirstRef()
5971{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005972 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005973}
5974
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005975status_t AudioFlinger::RecordThread::readyToRun()
5976{
5977 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005978 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005979 return status;
5980}
5981
Mathias Agopian65ab4712010-07-14 17:59:35 -07005982bool AudioFlinger::RecordThread::threadLoop()
5983{
5984 AudioBufferProvider::Buffer buffer;
5985 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005986 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005987
Eric Laurent44d98482010-09-30 16:12:31 -07005988 nsecs_t lastWarning = 0;
5989
Glenn Kastene4e2a372012-07-23 12:55:09 -07005990 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07005991 acquireWakeLock();
5992
Mathias Agopian65ab4712010-07-14 17:59:35 -07005993 // start recording
5994 while (!exitPending()) {
5995
5996 processConfigEvents();
5997
5998 { // scope for mLock
5999 Mutex::Autolock _l(mLock);
6000 checkForNewParameters_l();
6001 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006002 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006003
6004 if (exitPending()) break;
6005
Eric Laurentfeb0db62011-07-22 09:04:31 -07006006 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01006007 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006008 // go to sleep
6009 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006010 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006011 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006012 continue;
6013 }
6014 if (mActiveTrack != 0) {
6015 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006016 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006017 mActiveTrack.clear();
6018 mStartStopCond.broadcast();
6019 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6020 if (mReqChannelCount != mActiveTrack->channelCount()) {
6021 mActiveTrack.clear();
6022 mStartStopCond.broadcast();
6023 } else if (mBytesRead != 0) {
6024 // record start succeeds only if first read from audio input
6025 // succeeds
6026 if (mBytesRead > 0) {
6027 mActiveTrack->mState = TrackBase::ACTIVE;
6028 } else {
6029 mActiveTrack.clear();
6030 }
6031 mStartStopCond.broadcast();
6032 }
6033 mStandby = false;
Glenn Kasten510a3d62012-07-16 14:24:34 -07006034 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
6035 removeTrack_l(mActiveTrack);
6036 mActiveTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006037 }
6038 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006039 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006040 }
6041
6042 if (mActiveTrack != 0) {
6043 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6044 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006045 unlockEffectChains(effectChains);
6046 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006047 continue;
6048 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006049 for (size_t i = 0; i < effectChains.size(); i ++) {
6050 effectChains[i]->process_l();
6051 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006052
Mathias Agopian65ab4712010-07-14 17:59:35 -07006053 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006054 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006055 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006056 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006057 // no resampling
6058 while (framesOut) {
6059 size_t framesIn = mFrameCount - mRsmpInIndex;
6060 if (framesIn) {
6061 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6062 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6063 if (framesIn > framesOut)
6064 framesIn = framesOut;
6065 mRsmpInIndex += framesIn;
6066 framesOut -= framesIn;
6067 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006068 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006069 memcpy(dst, src, framesIn * mFrameSize);
6070 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006071 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006072 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6073 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006075 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6076 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006077 }
6078 }
6079 }
6080 if (framesOut && mFrameCount == mRsmpInIndex) {
6081 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006082 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006083 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006084 framesOut = 0;
6085 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006086 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006087 mRsmpInIndex = 0;
6088 }
6089 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006090 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006091 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6092 // Force input into standby so that it tries to
6093 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006094 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006095 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006096 }
6097 mRsmpInIndex = mFrameCount;
6098 framesOut = 0;
6099 buffer.frameCount = 0;
6100 }
6101 }
6102 }
6103 } else {
6104 // resampling
6105
6106 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6107 // alter output frame count as if we were expecting stereo samples
6108 if (mChannelCount == 1 && mReqChannelCount == 1) {
6109 framesOut >>= 1;
6110 }
6111 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6112 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6113 // are 32 bit aligned which should be always true.
6114 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006115 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006116 // the resampler always outputs stereo samples: do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006117 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6118 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006119 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006120 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006121 }
6122
6123 }
Eric Laurenta011e352012-03-29 15:51:43 -07006124 if (mFramestoDrop == 0) {
6125 mActiveTrack->releaseBuffer(&buffer);
6126 } else {
6127 if (mFramestoDrop > 0) {
6128 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006129 if (mFramestoDrop <= 0) {
6130 clearSyncStartEvent();
6131 }
6132 } else {
6133 mFramestoDrop += buffer.frameCount;
6134 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6135 mSyncStartEvent->isCancelled()) {
6136 ALOGW("Synced record %s, session %d, trigger session %d",
6137 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6138 mActiveTrack->sessionId(),
6139 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6140 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006141 }
6142 }
6143 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006144 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006145 }
6146 // client isn't retrieving buffers fast enough
6147 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006148 if (!mActiveTrack->setOverflow()) {
6149 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006150 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006151 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006152 lastWarning = now;
6153 }
6154 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006155 // Release the processor for a while before asking for a new buffer.
6156 // This will give the application more chance to read from the buffer and
6157 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006158 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006159 }
6160 }
Eric Laurentec437d82011-07-26 20:54:46 -07006161 // enable changes in effect chain
6162 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006163 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006164 }
6165
Glenn Kastene4e2a372012-07-23 12:55:09 -07006166 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006167
Glenn Kasten33e6e352012-07-16 15:56:57 -07006168 {
6169 Mutex::Autolock _l(mLock);
6170 mActiveTrack.clear();
6171 mStartStopCond.broadcast();
6172 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006173
Eric Laurentfeb0db62011-07-22 09:04:31 -07006174 releaseWakeLock();
6175
Steve Block3856b092011-10-20 11:56:00 +01006176 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006177 return false;
6178}
6179
Glenn Kastene4e2a372012-07-23 12:55:09 -07006180void AudioFlinger::RecordThread::standby()
6181{
6182 if (!mStandby) {
6183 inputStandBy();
6184 mStandby = true;
6185 }
6186}
6187
6188void AudioFlinger::RecordThread::inputStandBy()
6189{
6190 mInput->stream->common.standby(&mInput->stream->common);
6191}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006192
6193sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6194 const sp<AudioFlinger::Client>& client,
6195 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006196 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006197 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006198 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006199 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006200 IAudioFlinger::track_flags_t flags,
6201 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006202 status_t *status)
6203{
6204 sp<RecordTrack> track;
6205 status_t lStatus;
6206
6207 lStatus = initCheck();
6208 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006209 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006210 goto Exit;
6211 }
6212
Glenn Kasten1879fff2012-07-11 15:36:59 -07006213 // FIXME use flags and tid similar to createTrack_l()
6214
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006215 { // scope for mLock
6216 Mutex::Autolock _l(mLock);
6217
6218 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006219 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006220
Glenn Kasten7378ca52012-01-20 13:44:40 -08006221 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006222 lStatus = NO_MEMORY;
6223 goto Exit;
6224 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006225 mTracks.add(track);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006226
Eric Laurent59bd0da2011-08-01 09:52:20 -07006227 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006228 bool suspend = audio_is_bluetooth_sco_device(mDevice & AUDIO_DEVICE_IN_ALL) &&
6229 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006230 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6231 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006232 }
6233 lStatus = NO_ERROR;
6234
6235Exit:
6236 if (status) {
6237 *status = lStatus;
6238 }
6239 return track;
6240}
6241
Eric Laurenta011e352012-03-29 15:51:43 -07006242status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006243 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006244 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006245{
Glenn Kasten58912562012-04-03 10:45:00 -07006246 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006247 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006248 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006249
6250 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006251 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006252 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6253 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6254 triggerSession,
6255 recordTrack->sessionId(),
6256 syncStartEventCallback,
6257 this);
Eric Laurent29864602012-05-08 18:57:51 -07006258 // Sync event can be cancelled by the trigger session if the track is not in a
6259 // compatible state in which case we start record immediately
6260 if (mSyncStartEvent->isCancelled()) {
6261 clearSyncStartEvent();
6262 } else {
6263 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6264 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6265 }
Eric Laurenta011e352012-03-29 15:51:43 -07006266 }
6267
Mathias Agopian65ab4712010-07-14 17:59:35 -07006268 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006269 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006270 if (mActiveTrack != 0) {
6271 if (recordTrack != mActiveTrack.get()) {
6272 status = -EBUSY;
6273 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6274 mActiveTrack->mState = TrackBase::ACTIVE;
6275 }
6276 return status;
6277 }
6278
6279 recordTrack->mState = TrackBase::IDLE;
6280 mActiveTrack = recordTrack;
6281 mLock.unlock();
6282 status_t status = AudioSystem::startInput(mId);
6283 mLock.lock();
6284 if (status != NO_ERROR) {
6285 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006286 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006287 return status;
6288 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006289 mRsmpInIndex = mFrameCount;
6290 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006291 if (mResampler != NULL) {
6292 mResampler->reset();
6293 }
6294 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006295 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006296 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006297 mWaitWorkCV.signal();
6298 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006299 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006300 mActiveTrack.clear();
6301 status = INVALID_OPERATION;
6302 goto startError;
6303 }
6304 mStartStopCond.wait(mLock);
6305 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006306 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006307 status = BAD_VALUE;
6308 goto startError;
6309 }
Steve Block3856b092011-10-20 11:56:00 +01006310 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006311 return status;
6312 }
6313startError:
6314 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006315 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006316 return status;
6317}
6318
Eric Laurenta011e352012-03-29 15:51:43 -07006319void AudioFlinger::RecordThread::clearSyncStartEvent()
6320{
6321 if (mSyncStartEvent != 0) {
6322 mSyncStartEvent->cancel();
6323 }
6324 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006325 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006326}
6327
6328void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6329{
6330 sp<SyncEvent> strongEvent = event.promote();
6331
6332 if (strongEvent != 0) {
6333 RecordThread *me = (RecordThread *)strongEvent->cookie();
6334 me->handleSyncStartEvent(strongEvent);
6335 }
6336}
6337
6338void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6339{
Eric Laurent29864602012-05-08 18:57:51 -07006340 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006341 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6342 // from audio HAL
6343 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006344 }
6345}
6346
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006347bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006348 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006349 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
6350 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006351 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006352 recordTrack->mState = TrackBase::PAUSING;
6353 // do not wait for mStartStopCond if exiting
6354 if (exitPending()) {
6355 return true;
6356 }
6357 mStartStopCond.wait(mLock);
6358 // if we have been restarted, recordTrack == mActiveTrack.get() here
6359 if (exitPending() || recordTrack != mActiveTrack.get()) {
6360 ALOGV("Record stopped OK");
6361 return true;
6362 }
6363 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006364}
6365
Eric Laurenta011e352012-03-29 15:51:43 -07006366bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6367{
6368 return false;
6369}
6370
6371status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6372{
6373 if (!isValidSyncEvent(event)) {
6374 return BAD_VALUE;
6375 }
6376
Glenn Kasten510a3d62012-07-16 14:24:34 -07006377 int eventSession = event->triggerSession();
6378 status_t ret = NAME_NOT_FOUND;
6379
Eric Laurenta011e352012-03-29 15:51:43 -07006380 Mutex::Autolock _l(mLock);
6381
Glenn Kasten510a3d62012-07-16 14:24:34 -07006382 for (size_t i = 0; i < mTracks.size(); i++) {
6383 sp<RecordTrack> track = mTracks[i];
6384 if (eventSession == track->sessionId()) {
6385 track->setSyncEvent(event);
6386 ret = NO_ERROR;
6387 }
Eric Laurenta011e352012-03-29 15:51:43 -07006388 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006389 return ret;
6390}
6391
6392void AudioFlinger::RecordThread::RecordTrack::destroy()
6393{
6394 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
6395 sp<RecordTrack> keep(this);
6396 {
6397 sp<ThreadBase> thread = mThread.promote();
6398 if (thread != 0) {
6399 if (mState == ACTIVE || mState == RESUMING) {
6400 AudioSystem::stopInput(thread->id());
6401 }
6402 AudioSystem::releaseInput(thread->id());
6403 Mutex::Autolock _l(thread->mLock);
6404 RecordThread *recordThread = (RecordThread *) thread.get();
6405 recordThread->destroyTrack_l(this);
6406 }
6407 }
6408}
6409
6410// destroyTrack_l() must be called with ThreadBase::mLock held
6411void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6412{
6413 track->mState = TrackBase::TERMINATED;
6414 // active tracks are removed by threadLoop()
6415 if (mActiveTrack != track) {
6416 removeTrack_l(track);
6417 }
6418}
6419
6420void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6421{
6422 mTracks.remove(track);
6423 // need anything related to effects here?
Eric Laurenta011e352012-03-29 15:51:43 -07006424}
6425
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07006426void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006427{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006428 dumpInternals(fd, args);
6429 dumpTracks(fd, args);
6430 dumpEffectChains(fd, args);
6431}
6432
6433void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6434{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006435 const size_t SIZE = 256;
6436 char buffer[SIZE];
6437 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006438
6439 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6440 result.append(buffer);
6441
6442 if (mActiveTrack != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006443 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6444 result.append(buffer);
6445 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6446 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006447 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006448 result.append(buffer);
6449 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6450 result.append(buffer);
6451 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6452 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006453 } else {
Glenn Kasten510a3d62012-07-16 14:24:34 -07006454 result.append("No active record client\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006455 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006456
Mathias Agopian65ab4712010-07-14 17:59:35 -07006457 write(fd, result.string(), result.size());
6458
6459 dumpBase(fd, args);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006460}
6461
6462void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
6463{
6464 const size_t SIZE = 256;
6465 char buffer[SIZE];
6466 String8 result;
6467
6468 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
6469 result.append(buffer);
6470 RecordTrack::appendDumpHeader(result);
6471 for (size_t i = 0; i < mTracks.size(); ++i) {
6472 sp<RecordTrack> track = mTracks[i];
6473 if (track != 0) {
6474 track->dump(buffer, SIZE);
6475 result.append(buffer);
6476 }
6477 }
6478
6479 if (mActiveTrack != 0) {
6480 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
6481 result.append(buffer);
6482 RecordTrack::appendDumpHeader(result);
6483 mActiveTrack->dump(buffer, SIZE);
6484 result.append(buffer);
6485
6486 }
6487 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006488}
6489
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006490// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006491status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006492{
6493 size_t framesReq = buffer->frameCount;
6494 size_t framesReady = mFrameCount - mRsmpInIndex;
6495 int channelCount;
6496
6497 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006498 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006499 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006500 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006501 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6502 // Force input into standby so that it tries to
6503 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006504 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006505 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006506 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006507 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006508 buffer->frameCount = 0;
6509 return NOT_ENOUGH_DATA;
6510 }
6511 mRsmpInIndex = 0;
6512 framesReady = mFrameCount;
6513 }
6514
6515 if (framesReq > framesReady) {
6516 framesReq = framesReady;
6517 }
6518
6519 if (mChannelCount == 1 && mReqChannelCount == 2) {
6520 channelCount = 1;
6521 } else {
6522 channelCount = 2;
6523 }
6524 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6525 buffer->frameCount = framesReq;
6526 return NO_ERROR;
6527}
6528
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006529// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006530void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6531{
6532 mRsmpInIndex += buffer->frameCount;
6533 buffer->frameCount = 0;
6534}
6535
6536bool AudioFlinger::RecordThread::checkForNewParameters_l()
6537{
6538 bool reconfig = false;
6539
6540 while (!mNewParameters.isEmpty()) {
6541 status_t status = NO_ERROR;
6542 String8 keyValuePair = mNewParameters[0];
6543 AudioParameter param = AudioParameter(keyValuePair);
6544 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006545 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006546 int reqSamplingRate = mReqSampleRate;
6547 int reqChannelCount = mReqChannelCount;
6548
6549 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6550 reqSamplingRate = value;
6551 reconfig = true;
6552 }
6553 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006554 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006555 reconfig = true;
6556 }
6557 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006558 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006559 reconfig = true;
6560 }
6561 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6562 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006563 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006564 // if frame count is changed after track creation
6565 if (mActiveTrack != 0) {
6566 status = INVALID_OPERATION;
6567 } else {
6568 reconfig = true;
6569 }
6570 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006571 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6572 // forward device change to effects that have requested to be
6573 // aware of attached audio device.
6574 for (size_t i = 0; i < mEffectChains.size(); i++) {
6575 mEffectChains[i]->setDevice_l(value);
6576 }
6577 // store input device and output device but do not forward output device to audio HAL.
6578 // Note that status is ignored by the caller for output device
6579 // (see AudioFlinger::setParameters()
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006580 audio_devices_t newDevice = mDevice;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006581 if (value & AUDIO_DEVICE_OUT_ALL) {
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006582 newDevice &= ~(value & AUDIO_DEVICE_OUT_ALL);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006583 status = BAD_VALUE;
6584 } else {
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006585 newDevice &= ~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006586 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kasten510a3d62012-07-16 14:24:34 -07006587 if (mTracks.size() > 0) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07006588 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006589 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006590 for (size_t i = 0; i < mTracks.size(); i++) {
6591 sp<RecordTrack> track = mTracks[i];
6592 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6593 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6594 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07006595 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006596 }
Glenn Kasten01542f22012-07-02 12:46:15 -07006597 newDevice |= value;
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006598 mDevice = newDevice; // since mDevice is read by other threads, only write to it once
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006599 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006600 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006601 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006602 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006603 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006604 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6605 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006606 }
6607 if (reconfig) {
6608 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006609 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006610 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006611 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006612 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6613 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006614 status = NO_ERROR;
6615 }
6616 if (status == NO_ERROR) {
6617 readInputParameters();
6618 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6619 }
6620 }
6621 }
6622
6623 mNewParameters.removeAt(0);
6624
6625 mParamStatus = status;
6626 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006627 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6628 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006629 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006630 }
6631 return reconfig;
6632}
6633
6634String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6635{
Dima Zavinfce7a472011-04-19 22:30:36 -07006636 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006637 String8 out_s8 = String8();
6638
6639 Mutex::Autolock _l(mLock);
6640 if (initCheck() != NO_ERROR) {
6641 return out_s8;
6642 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006643
Dima Zavin799a70e2011-04-18 16:57:27 -07006644 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006645 out_s8 = String8(s);
6646 free(s);
6647 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006648}
6649
6650void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6651 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006652 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006653
6654 switch (event) {
6655 case AudioSystem::INPUT_OPENED:
6656 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006657 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006658 desc.samplingRate = mSampleRate;
6659 desc.format = mFormat;
6660 desc.frameCount = mFrameCount;
6661 desc.latency = 0;
6662 param2 = &desc;
6663 break;
6664
6665 case AudioSystem::INPUT_CLOSED:
6666 default:
6667 break;
6668 }
6669 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6670}
6671
6672void AudioFlinger::RecordThread::readInputParameters()
6673{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006674 delete mRsmpInBuffer;
6675 // mRsmpInBuffer is always assigned a new[] below
6676 delete mRsmpOutBuffer;
6677 mRsmpOutBuffer = NULL;
6678 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006679 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006680
Dima Zavin799a70e2011-04-18 16:57:27 -07006681 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006682 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6683 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006684 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006685 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006686 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006687 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006688 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006689 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6690
Glenn Kasten53d76db2012-03-08 12:32:47 -08006691 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006692 {
6693 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006694 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6695 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006696 if (mChannelCount == 1 && mReqChannelCount == 2) {
6697 channelCount = 1;
6698 } else {
6699 channelCount = 2;
6700 }
6701 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6702 mResampler->setSampleRate(mSampleRate);
6703 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6704 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6705
6706 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6707 if (mChannelCount == 1 && mReqChannelCount == 1) {
6708 mFrameCount >>= 1;
6709 }
6710
6711 }
6712 mRsmpInIndex = mFrameCount;
6713}
6714
6715unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6716{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006717 Mutex::Autolock _l(mLock);
6718 if (initCheck() != NO_ERROR) {
6719 return 0;
6720 }
6721
Dima Zavin799a70e2011-04-18 16:57:27 -07006722 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006723}
6724
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006725uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6726{
6727 Mutex::Autolock _l(mLock);
6728 uint32_t result = 0;
6729 if (getEffectChain_l(sessionId) != 0) {
6730 result = EFFECT_SESSION;
6731 }
6732
Glenn Kasten510a3d62012-07-16 14:24:34 -07006733 for (size_t i = 0; i < mTracks.size(); ++i) {
6734 if (sessionId == mTracks[i]->sessionId()) {
6735 result |= TRACK_SESSION;
6736 break;
6737 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006738 }
6739
6740 return result;
6741}
6742
Glenn Kasten510a3d62012-07-16 14:24:34 -07006743KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds()
Eric Laurent59bd0da2011-08-01 09:52:20 -07006744{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006745 KeyedVector<int, bool> ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006746 Mutex::Autolock _l(mLock);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006747 for (size_t j = 0; j < mTracks.size(); ++j) {
6748 sp<RecordThread::RecordTrack> track = mTracks[j];
6749 int sessionId = track->sessionId();
6750 if (ids.indexOfKey(sessionId) < 0) {
6751 ids.add(sessionId, true);
6752 }
6753 }
6754 return ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006755}
6756
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006757AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6758{
6759 Mutex::Autolock _l(mLock);
6760 AudioStreamIn *input = mInput;
6761 mInput = NULL;
6762 return input;
6763}
6764
6765// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006766audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006767{
6768 if (mInput == NULL) {
6769 return NULL;
6770 }
6771 return &mInput->stream->common;
6772}
6773
6774
Mathias Agopian65ab4712010-07-14 17:59:35 -07006775// ----------------------------------------------------------------------------
6776
Eric Laurenta4c5a552012-03-29 10:12:40 -07006777audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6778{
6779 if (!settingsAllowed()) {
6780 return 0;
6781 }
6782 Mutex::Autolock _l(mLock);
6783 return loadHwModule_l(name);
6784}
6785
6786// loadHwModule_l() must be called with AudioFlinger::mLock held
6787audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6788{
6789 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6790 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6791 ALOGW("loadHwModule() module %s already loaded", name);
6792 return mAudioHwDevs.keyAt(i);
6793 }
6794 }
6795
Eric Laurenta4c5a552012-03-29 10:12:40 -07006796 audio_hw_device_t *dev;
6797
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006798 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006799 if (rc) {
6800 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6801 return 0;
6802 }
6803
6804 mHardwareStatus = AUDIO_HW_INIT;
6805 rc = dev->init_check(dev);
6806 mHardwareStatus = AUDIO_HW_IDLE;
6807 if (rc) {
6808 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6809 return 0;
6810 }
6811
6812 if ((mMasterVolumeSupportLvl != MVS_NONE) &&
6813 (NULL != dev->set_master_volume)) {
6814 AutoMutex lock(mHardwareLock);
6815 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6816 dev->set_master_volume(dev, mMasterVolume);
6817 mHardwareStatus = AUDIO_HW_IDLE;
6818 }
6819
6820 audio_module_handle_t handle = nextUniqueId();
6821 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));
6822
6823 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006824 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006825
6826 return handle;
6827
6828}
6829
6830audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6831 audio_devices_t *pDevices,
6832 uint32_t *pSamplingRate,
6833 audio_format_t *pFormat,
6834 audio_channel_mask_t *pChannelMask,
6835 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006836 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006837{
6838 status_t status;
6839 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006840 struct audio_config config = {
6841 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6842 channel_mask: pChannelMask ? *pChannelMask : 0,
6843 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6844 };
6845 audio_stream_out_t *outStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07006846 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006847
Eric Laurenta4c5a552012-03-29 10:12:40 -07006848 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6849 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006850 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006851 config.sample_rate,
6852 config.format,
6853 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006854 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006855
6856 if (pDevices == NULL || *pDevices == 0) {
6857 return 0;
6858 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006859
Mathias Agopian65ab4712010-07-14 17:59:35 -07006860 Mutex::Autolock _l(mLock);
6861
Eric Laurenta4c5a552012-03-29 10:12:40 -07006862 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006863 if (outHwDev == NULL)
6864 return 0;
6865
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006866 audio_io_handle_t id = nextUniqueId();
6867
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006868 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006869
6870 status = outHwDev->open_output_stream(outHwDev,
6871 id,
6872 *pDevices,
6873 (audio_output_flags_t)flags,
6874 &config,
6875 &outStream);
6876
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006877 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006878 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006879 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006880 config.sample_rate,
6881 config.format,
6882 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006883 status);
6884
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006885 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006886 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006887
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006888 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006889 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6890 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006891 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006892 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006893 } else {
6894 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006895 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006896 }
6897 mPlaybackThreads.add(id, thread);
6898
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006899 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6900 if (pFormat != NULL) *pFormat = config.format;
6901 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006902 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006903
6904 // notify client processes of the new output creation
6905 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006906
6907 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006908 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006909 ALOGI("Using module %d has the primary audio interface", module);
6910 mPrimaryHardwareDev = outHwDev;
6911
6912 AutoMutex lock(mHardwareLock);
6913 mHardwareStatus = AUDIO_HW_SET_MODE;
6914 outHwDev->set_mode(outHwDev, mMode);
6915
John Grossmand8f178d2012-07-20 14:51:35 -07006916 // Determine the level of master volume/master mute support the primary
6917 // audio HAL has, and set the initial master volume/mute state at the same
6918 // time.
Eric Laurenta4c5a552012-03-29 10:12:40 -07006919 float initialVolume = 1.0;
John Grossmand8f178d2012-07-20 14:51:35 -07006920 bool initialMute = false;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006921 mMasterVolumeSupportLvl = MVS_NONE;
John Grossmand8f178d2012-07-20 14:51:35 -07006922 mMasterMuteSupportLvl = MMS_NONE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006923
6924 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6925 if ((NULL != outHwDev->get_master_volume) &&
6926 (NO_ERROR == outHwDev->get_master_volume(outHwDev, &initialVolume))) {
6927 mMasterVolumeSupportLvl = MVS_FULL;
6928 } else {
6929 mMasterVolumeSupportLvl = MVS_SETONLY;
6930 initialVolume = 1.0;
6931 }
6932
6933 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
6934 if ((NULL == outHwDev->set_master_volume) ||
6935 (NO_ERROR != outHwDev->set_master_volume(outHwDev, initialVolume))) {
6936 mMasterVolumeSupportLvl = MVS_NONE;
6937 }
John Grossmand8f178d2012-07-20 14:51:35 -07006938
6939 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
6940 if ((NULL != outHwDev->get_master_mute) &&
6941 (NO_ERROR == outHwDev->get_master_mute(outHwDev, &initialMute))) {
6942 mMasterMuteSupportLvl = MMS_FULL;
6943 } else {
6944 mMasterMuteSupportLvl = MMS_SETONLY;
6945 initialMute = 0;
6946 }
6947
6948 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
6949 if ((NULL == outHwDev->set_master_mute) ||
6950 (NO_ERROR != outHwDev->set_master_mute(outHwDev, initialMute))) {
6951 mMasterMuteSupportLvl = MMS_NONE;
6952 }
6953
6954 // now that we have a primary device, initialize master volume/mute
6955 // on other devices
Eric Laurenta4c5a552012-03-29 10:12:40 -07006956 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6957 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
6958
6959 if ((dev != mPrimaryHardwareDev) &&
6960 (NULL != dev->set_master_volume)) {
John Grossmand8f178d2012-07-20 14:51:35 -07006961 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006962 dev->set_master_volume(dev, initialVolume);
6963 }
John Grossmand8f178d2012-07-20 14:51:35 -07006964
6965 if (NULL != dev->set_master_mute) {
6966 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
6967 dev->set_master_mute(dev, initialMute);
6968 }
Eric Laurenta4c5a552012-03-29 10:12:40 -07006969 }
John Grossmand8f178d2012-07-20 14:51:35 -07006970
Eric Laurenta4c5a552012-03-29 10:12:40 -07006971 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -07006972 mMasterVolumeSW = initialVolume;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006973 mMasterVolume = initialVolume;
John Grossmand8f178d2012-07-20 14:51:35 -07006974 mMasterMuteSW = initialMute;
6975 mMasterMute = initialMute;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006976 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006977 return id;
6978 }
6979
6980 return 0;
6981}
6982
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006983audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6984 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006985{
6986 Mutex::Autolock _l(mLock);
6987 MixerThread *thread1 = checkMixerThread_l(output1);
6988 MixerThread *thread2 = checkMixerThread_l(output2);
6989
6990 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006991 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006992 return 0;
6993 }
6994
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006995 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006996 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6997 thread->addOutputTrack(thread2);
6998 mPlaybackThreads.add(id, thread);
6999 // notify client processes of the new output creation
7000 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7001 return id;
7002}
7003
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007004status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007005{
Glenn Kastend96c5722012-04-25 13:44:49 -07007006 return closeOutput_nonvirtual(output);
7007}
7008
7009status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
7010{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007011 // keep strong reference on the playback thread so that
7012 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007013 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007014 {
7015 Mutex::Autolock _l(mLock);
7016 thread = checkPlaybackThread_l(output);
7017 if (thread == NULL) {
7018 return BAD_VALUE;
7019 }
7020
Steve Block3856b092011-10-20 11:56:00 +01007021 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007022
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007023 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007024 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007025 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007026 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
7027 dupThread->removeOutputTrack((MixerThread *)thread.get());
7028 }
7029 }
7030 }
Glenn Kastena1117922012-01-26 10:53:32 -08007031 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007032 mPlaybackThreads.removeItem(output);
7033 }
7034 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007035 // The thread entity (active unit of execution) is no longer running here,
7036 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007037
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007038 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007039 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007040 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007041 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07007042 out->hwDev->close_output_stream(out->hwDev, out->stream);
7043 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007044 }
7045 return NO_ERROR;
7046}
7047
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007048status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007049{
7050 Mutex::Autolock _l(mLock);
7051 PlaybackThread *thread = checkPlaybackThread_l(output);
7052
7053 if (thread == NULL) {
7054 return BAD_VALUE;
7055 }
7056
Steve Block3856b092011-10-20 11:56:00 +01007057 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007058 thread->suspend();
7059
7060 return NO_ERROR;
7061}
7062
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007063status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007064{
7065 Mutex::Autolock _l(mLock);
7066 PlaybackThread *thread = checkPlaybackThread_l(output);
7067
7068 if (thread == NULL) {
7069 return BAD_VALUE;
7070 }
7071
Steve Block3856b092011-10-20 11:56:00 +01007072 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007073
7074 thread->restore();
7075
7076 return NO_ERROR;
7077}
7078
Eric Laurenta4c5a552012-03-29 10:12:40 -07007079audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
7080 audio_devices_t *pDevices,
7081 uint32_t *pSamplingRate,
7082 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07007083 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007084{
7085 status_t status;
7086 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007087 struct audio_config config = {
7088 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7089 channel_mask: pChannelMask ? *pChannelMask : 0,
7090 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7091 };
7092 uint32_t reqSamplingRate = config.sample_rate;
7093 audio_format_t reqFormat = config.format;
7094 audio_channel_mask_t reqChannels = config.channel_mask;
7095 audio_stream_in_t *inStream = NULL;
Dima Zavin799a70e2011-04-18 16:57:27 -07007096 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007097
7098 if (pDevices == NULL || *pDevices == 0) {
7099 return 0;
7100 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007101
Mathias Agopian65ab4712010-07-14 17:59:35 -07007102 Mutex::Autolock _l(mLock);
7103
Eric Laurenta4c5a552012-03-29 10:12:40 -07007104 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007105 if (inHwDev == NULL)
7106 return 0;
7107
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007108 audio_io_handle_t id = nextUniqueId();
7109
7110 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007111 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007112 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007113 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007114 config.sample_rate,
7115 config.format,
7116 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007117 status);
7118
7119 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7120 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7121 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007122 if (status == BAD_VALUE &&
7123 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7124 (config.sample_rate <= 2 * reqSamplingRate) &&
7125 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007126 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007127 inStream = NULL;
7128 status = inHwDev->open_input_stream(inHwDev, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007129 }
7130
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007131 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007132 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7133
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007134 // Start record thread
7135 // RecorThread require both input and output device indication to forward to audio
7136 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007137 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007138 thread = new RecordThread(this,
7139 input,
7140 reqSamplingRate,
7141 reqChannels,
7142 id,
7143 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007144 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007145 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007146 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007147 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007148 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007149
Mathias Agopian65ab4712010-07-14 17:59:35 -07007150 // notify client processes of the new input creation
7151 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7152 return id;
7153 }
7154
7155 return 0;
7156}
7157
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007158status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007159{
Glenn Kastend96c5722012-04-25 13:44:49 -07007160 return closeInput_nonvirtual(input);
7161}
7162
7163status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7164{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007165 // keep strong reference on the record thread so that
7166 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007167 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007168 {
7169 Mutex::Autolock _l(mLock);
7170 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007171 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007172 return BAD_VALUE;
7173 }
7174
Steve Block3856b092011-10-20 11:56:00 +01007175 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007176 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007177 mRecordThreads.removeItem(input);
7178 }
7179 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007180 // The thread entity (active unit of execution) is no longer running here,
7181 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007182
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007183 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007184 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007185 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07007186 in->hwDev->close_input_stream(in->hwDev, in->stream);
7187 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007188
7189 return NO_ERROR;
7190}
7191
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007192status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007193{
7194 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007195 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007196
7197 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7198 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007199 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007200 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007201
7202 return NO_ERROR;
7203}
7204
7205
7206int AudioFlinger::newAudioSessionId()
7207{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007208 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007209}
7210
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007211void AudioFlinger::acquireAudioSessionId(int audioSession)
7212{
7213 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007214 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007215 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007216 size_t num = mAudioSessionRefs.size();
7217 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007218 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007219 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7220 ref->mCnt++;
7221 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007222 return;
7223 }
7224 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007225 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7226 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007227}
7228
7229void AudioFlinger::releaseAudioSessionId(int audioSession)
7230{
7231 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007232 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007233 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007234 size_t num = mAudioSessionRefs.size();
7235 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007236 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007237 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7238 ref->mCnt--;
7239 ALOGV(" decremented refcount to %d", ref->mCnt);
7240 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007241 mAudioSessionRefs.removeAt(i);
7242 delete ref;
7243 purgeStaleEffects_l();
7244 }
7245 return;
7246 }
7247 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007248 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007249}
7250
7251void AudioFlinger::purgeStaleEffects_l() {
7252
Steve Block3856b092011-10-20 11:56:00 +01007253 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007254
7255 Vector< sp<EffectChain> > chains;
7256
7257 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7258 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7259 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7260 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007261 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7262 chains.push(ec);
7263 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007264 }
7265 }
7266 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7267 sp<RecordThread> t = mRecordThreads.valueAt(i);
7268 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7269 sp<EffectChain> ec = t->mEffectChains[j];
7270 chains.push(ec);
7271 }
7272 }
7273
7274 for (size_t i = 0; i < chains.size(); i++) {
7275 sp<EffectChain> ec = chains[i];
7276 int sessionid = ec->sessionId();
7277 sp<ThreadBase> t = ec->mThread.promote();
7278 if (t == 0) {
7279 continue;
7280 }
7281 size_t numsessionrefs = mAudioSessionRefs.size();
7282 bool found = false;
7283 for (size_t k = 0; k < numsessionrefs; k++) {
7284 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007285 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007286 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007287 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007288 found = true;
7289 break;
7290 }
7291 }
7292 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007293 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007294 // remove all effects from the chain
7295 while (ec->mEffects.size()) {
7296 sp<EffectModule> effect = ec->mEffects[0];
7297 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007298 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007299 if (effect->purgeHandles()) {
7300 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007301 }
7302 AudioSystem::unregisterEffect(effect->id());
7303 }
7304 }
7305 }
7306 return;
7307}
7308
Mathias Agopian65ab4712010-07-14 17:59:35 -07007309// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007310AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007311{
Glenn Kastena1117922012-01-26 10:53:32 -08007312 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007313}
7314
7315// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007316AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007317{
7318 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007319 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007320}
7321
7322// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007323AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007324{
Glenn Kastena1117922012-01-26 10:53:32 -08007325 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007326}
7327
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007328uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007329{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007330 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007331}
7332
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007333AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007334{
7335 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7336 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007337 AudioStreamOut *output = thread->getOutput();
7338 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007339 return thread;
7340 }
7341 }
7342 return NULL;
7343}
7344
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007345audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007346{
7347 PlaybackThread *thread = primaryPlaybackThread_l();
7348
7349 if (thread == NULL) {
7350 return 0;
7351 }
7352
7353 return thread->device();
7354}
7355
Eric Laurenta011e352012-03-29 15:51:43 -07007356sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7357 int triggerSession,
7358 int listenerSession,
7359 sync_event_callback_t callBack,
7360 void *cookie)
7361{
7362 Mutex::Autolock _l(mLock);
7363
7364 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7365 status_t playStatus = NAME_NOT_FOUND;
7366 status_t recStatus = NAME_NOT_FOUND;
7367 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7368 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7369 if (playStatus == NO_ERROR) {
7370 return event;
7371 }
7372 }
7373 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7374 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7375 if (recStatus == NO_ERROR) {
7376 return event;
7377 }
7378 }
7379 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7380 mPendingSyncEvents.add(event);
7381 } else {
7382 ALOGV("createSyncEvent() invalid event %d", event->type());
7383 event.clear();
7384 }
7385 return event;
7386}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007387
Mathias Agopian65ab4712010-07-14 17:59:35 -07007388// ----------------------------------------------------------------------------
7389// Effect management
7390// ----------------------------------------------------------------------------
7391
7392
Glenn Kastenf587ba52012-01-26 16:25:10 -08007393status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007394{
7395 Mutex::Autolock _l(mLock);
7396 return EffectQueryNumberEffects(numEffects);
7397}
7398
Glenn Kastenf587ba52012-01-26 16:25:10 -08007399status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007400{
7401 Mutex::Autolock _l(mLock);
7402 return EffectQueryEffect(index, descriptor);
7403}
7404
Glenn Kasten5e92a782012-01-30 07:40:52 -08007405status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007406 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007407{
7408 Mutex::Autolock _l(mLock);
7409 return EffectGetDescriptor(pUuid, descriptor);
7410}
7411
7412
Mathias Agopian65ab4712010-07-14 17:59:35 -07007413sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7414 effect_descriptor_t *pDesc,
7415 const sp<IEffectClient>& effectClient,
7416 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007417 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007418 int sessionId,
7419 status_t *status,
7420 int *id,
7421 int *enabled)
7422{
7423 status_t lStatus = NO_ERROR;
7424 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007425 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007426
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007427 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007428 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007429
7430 if (pDesc == NULL) {
7431 lStatus = BAD_VALUE;
7432 goto Exit;
7433 }
7434
Eric Laurent84e9a102010-09-23 16:10:16 -07007435 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007436 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007437 lStatus = PERMISSION_DENIED;
7438 goto Exit;
7439 }
7440
Dima Zavinfce7a472011-04-19 22:30:36 -07007441 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007442 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007443 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007444 lStatus = PERMISSION_DENIED;
7445 goto Exit;
7446 }
7447
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007448 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007449 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007450 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007451 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007452 lStatus = BAD_VALUE;
7453 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007454 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007455 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007456 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007457 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007458 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007459 }
7460 }
7461
Mathias Agopian65ab4712010-07-14 17:59:35 -07007462 {
7463 Mutex::Autolock _l(mLock);
7464
Mathias Agopian65ab4712010-07-14 17:59:35 -07007465
7466 if (!EffectIsNullUuid(&pDesc->uuid)) {
7467 // if uuid is specified, request effect descriptor
7468 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7469 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007470 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007471 goto Exit;
7472 }
7473 } else {
7474 // if uuid is not specified, look for an available implementation
7475 // of the required type in effect factory
7476 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007477 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007478 lStatus = BAD_VALUE;
7479 goto Exit;
7480 }
7481 uint32_t numEffects = 0;
7482 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007483 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007484 bool found = false;
7485
7486 lStatus = EffectQueryNumberEffects(&numEffects);
7487 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007488 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007489 goto Exit;
7490 }
7491 for (uint32_t i = 0; i < numEffects; i++) {
7492 lStatus = EffectQueryEffect(i, &desc);
7493 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007494 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007495 continue;
7496 }
7497 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7498 // If matching type found save effect descriptor. If the session is
7499 // 0 and the effect is not auxiliary, continue enumeration in case
7500 // an auxiliary version of this effect type is available
7501 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08007502 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07007503 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007504 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7505 break;
7506 }
7507 }
7508 }
7509 if (!found) {
7510 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007511 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007512 goto Exit;
7513 }
7514 // For same effect type, chose auxiliary version over insert version if
7515 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007516 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007517 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08007518 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007519 }
7520 }
7521
7522 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007523 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007524 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7525 lStatus = INVALID_OPERATION;
7526 goto Exit;
7527 }
7528
Eric Laurent59255e42011-07-27 19:49:51 -07007529 // check recording permission for visualizer
7530 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7531 !recordingAllowed()) {
7532 lStatus = PERMISSION_DENIED;
7533 goto Exit;
7534 }
7535
Mathias Agopian65ab4712010-07-14 17:59:35 -07007536 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08007537 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007538
7539 // If output is not specified try to find a matching audio session ID in one of the
7540 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007541 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7542 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007543 // Note: io is never 0 when creating an effect on an input
7544 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007545 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007546 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7547 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007548 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007549 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007550 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007551 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007552 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007553 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7554 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7555 io = mRecordThreads.keyAt(i);
7556 break;
7557 }
7558 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007559 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007560 // If no output thread contains the requested session ID, default to
7561 // first output. The effect chain will be moved to the correct output
7562 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007563 if (io == 0 && mPlaybackThreads.size()) {
7564 io = mPlaybackThreads.keyAt(0);
7565 }
Steve Block3856b092011-10-20 11:56:00 +01007566 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007567 }
7568 ThreadBase *thread = checkRecordThread_l(io);
7569 if (thread == NULL) {
7570 thread = checkPlaybackThread_l(io);
7571 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007572 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007573 lStatus = BAD_VALUE;
7574 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007575 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007576 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007577
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007578 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007579
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007580 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007581 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7582 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007583 if (handle != 0 && id != NULL) {
7584 *id = handle->id();
7585 }
7586 }
7587
7588Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007589 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007590 *status = lStatus;
7591 }
7592 return handle;
7593}
7594
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007595status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7596 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007597{
Steve Block3856b092011-10-20 11:56:00 +01007598 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007599 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007600 Mutex::Autolock _l(mLock);
7601 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007602 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007603 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007604 }
Eric Laurentde070132010-07-13 04:45:46 -07007605 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7606 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007607 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007608 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007609 }
Eric Laurentde070132010-07-13 04:45:46 -07007610 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7611 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007612 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007613 return BAD_VALUE;
7614 }
7615
7616 Mutex::Autolock _dl(dstThread->mLock);
7617 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007618 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007619
Mathias Agopian65ab4712010-07-14 17:59:35 -07007620 return NO_ERROR;
7621}
7622
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007623// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007624status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007625 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007626 AudioFlinger::PlaybackThread *dstThread,
7627 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007628{
Steve Block3856b092011-10-20 11:56:00 +01007629 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007630 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007631
Eric Laurent59255e42011-07-27 19:49:51 -07007632 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007633 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007634 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007635 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007636 return INVALID_OPERATION;
7637 }
7638
Eric Laurent39e94f82010-07-28 01:32:47 -07007639 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007640 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007641 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007642 // removed.
7643 srcThread->removeEffectChain_l(chain);
7644
7645 // transfer all effects one by one so that new effect chain is created on new thread with
7646 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007647 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007648 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007649 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007650 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7651 while (effect != 0) {
7652 srcThread->removeEffect_l(effect);
7653 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007654 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7655 if (effect->state() == EffectModule::ACTIVE ||
7656 effect->state() == EffectModule::STOPPING) {
7657 effect->start();
7658 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007659 // if the move request is not received from audio policy manager, the effect must be
7660 // re-registered with the new strategy and output
7661 if (dstChain == 0) {
7662 dstChain = effect->chain().promote();
7663 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007664 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007665 srcThread->addEffect_l(effect);
7666 return NO_INIT;
7667 }
7668 strategy = dstChain->strategy();
7669 }
7670 if (reRegister) {
7671 AudioSystem::unregisterEffect(effect->id());
7672 AudioSystem::registerEffect(&effect->desc(),
7673 dstOutput,
7674 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007675 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007676 effect->id());
7677 }
Eric Laurentde070132010-07-13 04:45:46 -07007678 effect = chain->getEffectFromId_l(0);
7679 }
7680
7681 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007682}
7683
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007684
Mathias Agopian65ab4712010-07-14 17:59:35 -07007685// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007686sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007687 const sp<AudioFlinger::Client>& client,
7688 const sp<IEffectClient>& effectClient,
7689 int32_t priority,
7690 int sessionId,
7691 effect_descriptor_t *desc,
7692 int *enabled,
7693 status_t *status
7694 )
7695{
7696 sp<EffectModule> effect;
7697 sp<EffectHandle> handle;
7698 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007699 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007700 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007701 bool effectCreated = false;
7702 bool effectRegistered = false;
7703
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007704 lStatus = initCheck();
7705 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007706 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007707 goto Exit;
7708 }
7709
7710 // Do not allow effects with session ID 0 on direct output or duplicating threads
7711 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007712 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007713 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007714 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007715 lStatus = BAD_VALUE;
7716 goto Exit;
7717 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007718 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007719 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007720 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007721 desc->name, desc->flags, mType);
7722 lStatus = BAD_VALUE;
7723 goto Exit;
7724 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007725
Steve Block3856b092011-10-20 11:56:00 +01007726 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007727
7728 { // scope for mLock
7729 Mutex::Autolock _l(mLock);
7730
7731 // check for existing effect chain with the requested audio session
7732 chain = getEffectChain_l(sessionId);
7733 if (chain == 0) {
7734 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007735 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007736 chain = new EffectChain(this, sessionId);
7737 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007738 chain->setStrategy(getStrategyForSession_l(sessionId));
7739 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007740 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007741 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007742 }
7743
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007744 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007745
7746 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007747 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007748 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007749 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007750 if (lStatus != NO_ERROR) {
7751 goto Exit;
7752 }
7753 effectRegistered = true;
7754 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007755 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007756 lStatus = effect->status();
7757 if (lStatus != NO_ERROR) {
7758 goto Exit;
7759 }
Eric Laurentcab11242010-07-15 12:50:15 -07007760 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007761 if (lStatus != NO_ERROR) {
7762 goto Exit;
7763 }
7764 effectCreated = true;
7765
7766 effect->setDevice(mDevice);
7767 effect->setMode(mAudioFlinger->getMode());
7768 }
7769 // create effect handle and connect it to effect module
7770 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007771 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007772 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007773 *enabled = (int)effect->isEnabled();
7774 }
7775 }
7776
7777Exit:
7778 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007779 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007780 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007781 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007782 }
7783 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007784 AudioSystem::unregisterEffect(effect->id());
7785 }
7786 if (chainCreated) {
7787 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007788 }
7789 handle.clear();
7790 }
7791
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007792 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007793 *status = lStatus;
7794 }
7795 return handle;
7796}
7797
Eric Laurent717e1282012-06-29 16:36:52 -07007798sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7799{
7800 Mutex::Autolock _l(mLock);
7801 return getEffect_l(sessionId, effectId);
7802}
7803
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007804sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7805{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007806 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007807 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007808}
7809
Eric Laurentde070132010-07-13 04:45:46 -07007810// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7811// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007812status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007813{
7814 // check for existing effect chain with the requested audio session
7815 int sessionId = effect->sessionId();
7816 sp<EffectChain> chain = getEffectChain_l(sessionId);
7817 bool chainCreated = false;
7818
7819 if (chain == 0) {
7820 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007821 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007822 chain = new EffectChain(this, sessionId);
7823 addEffectChain_l(chain);
7824 chain->setStrategy(getStrategyForSession_l(sessionId));
7825 chainCreated = true;
7826 }
Steve Block3856b092011-10-20 11:56:00 +01007827 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007828
7829 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007830 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007831 this, effect->desc().name, chain.get());
7832 return BAD_VALUE;
7833 }
7834
7835 status_t status = chain->addEffect_l(effect);
7836 if (status != NO_ERROR) {
7837 if (chainCreated) {
7838 removeEffectChain_l(chain);
7839 }
7840 return status;
7841 }
7842
7843 effect->setDevice(mDevice);
7844 effect->setMode(mAudioFlinger->getMode());
7845 return NO_ERROR;
7846}
7847
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007848void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007849
Steve Block3856b092011-10-20 11:56:00 +01007850 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007851 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007852 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7853 detachAuxEffect_l(effect->id());
7854 }
7855
7856 sp<EffectChain> chain = effect->chain().promote();
7857 if (chain != 0) {
7858 // remove effect chain if removing last effect
7859 if (chain->removeEffect_l(effect) == 0) {
7860 removeEffectChain_l(chain);
7861 }
7862 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007863 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007864 }
7865}
7866
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007867void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007868 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007869{
7870 effectChains = mEffectChains;
7871 for (size_t i = 0; i < mEffectChains.size(); i++) {
7872 mEffectChains[i]->lock();
7873 }
7874}
7875
7876void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007877 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007878{
7879 for (size_t i = 0; i < effectChains.size(); i++) {
7880 effectChains[i]->unlock();
7881 }
7882}
7883
7884sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7885{
7886 Mutex::Autolock _l(mLock);
7887 return getEffectChain_l(sessionId);
7888}
7889
7890sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7891{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007892 size_t size = mEffectChains.size();
7893 for (size_t i = 0; i < size; i++) {
7894 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007895 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007896 }
7897 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007898 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007899}
7900
Glenn Kastenf78aee72012-01-04 11:00:47 -08007901void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007902{
7903 Mutex::Autolock _l(mLock);
7904 size_t size = mEffectChains.size();
7905 for (size_t i = 0; i < size; i++) {
7906 mEffectChains[i]->setMode_l(mode);
7907 }
7908}
7909
7910void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007911 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007912 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007913
Mathias Agopian65ab4712010-07-14 17:59:35 -07007914 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007915 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007916 // delete the effect module if removing last handle on it
7917 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007918 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007919 removeEffect_l(effect);
7920 AudioSystem::unregisterEffect(effect->id());
7921 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007922 }
7923}
7924
7925status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7926{
7927 int session = chain->sessionId();
7928 int16_t *buffer = mMixBuffer;
7929 bool ownsBuffer = false;
7930
Steve Block3856b092011-10-20 11:56:00 +01007931 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007932 if (session > 0) {
7933 // Only one effect chain can be present in direct output thread and it uses
7934 // the mix buffer as input
7935 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007936 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007937 buffer = new int16_t[numSamples];
7938 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007939 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007940 ownsBuffer = true;
7941 }
7942
7943 // Attach all tracks with same session ID to this chain.
7944 for (size_t i = 0; i < mTracks.size(); ++i) {
7945 sp<Track> track = mTracks[i];
7946 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007947 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007948 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007949 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007950 }
7951 }
7952
7953 // indicate all active tracks in the chain
7954 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7955 sp<Track> track = mActiveTracks[i].promote();
7956 if (track == 0) continue;
7957 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007958 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007959 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007960 }
7961 }
7962 }
7963
7964 chain->setInBuffer(buffer, ownsBuffer);
7965 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007966 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007967 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007968 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7969 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007970 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007971 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7972 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007973 // Effect chain for other sessions are inserted at beginning of effect
7974 // chains list to be processed before output mix effects. Relative order between other
7975 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007976 size_t size = mEffectChains.size();
7977 size_t i = 0;
7978 for (i = 0; i < size; i++) {
7979 if (mEffectChains[i]->sessionId() < session) break;
7980 }
7981 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007982 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007983
7984 return NO_ERROR;
7985}
7986
7987size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7988{
7989 int session = chain->sessionId();
7990
Steve Block3856b092011-10-20 11:56:00 +01007991 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007992
7993 for (size_t i = 0; i < mEffectChains.size(); i++) {
7994 if (chain == mEffectChains[i]) {
7995 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007996 // detach all active tracks from the chain
7997 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7998 sp<Track> track = mActiveTracks[i].promote();
7999 if (track == 0) continue;
8000 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008001 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07008002 chain.get(), session);
8003 chain->decActiveTrackCnt();
8004 }
8005 }
8006
Mathias Agopian65ab4712010-07-14 17:59:35 -07008007 // detach all tracks with same session ID from this chain
8008 for (size_t i = 0; i < mTracks.size(); ++i) {
8009 sp<Track> track = mTracks[i];
8010 if (session == track->sessionId()) {
8011 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008012 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008013 }
8014 }
Eric Laurentde070132010-07-13 04:45:46 -07008015 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008016 }
8017 }
8018 return mEffectChains.size();
8019}
8020
Eric Laurentde070132010-07-13 04:45:46 -07008021status_t AudioFlinger::PlaybackThread::attachAuxEffect(
8022 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008023{
8024 Mutex::Autolock _l(mLock);
8025 return attachAuxEffect_l(track, EffectId);
8026}
8027
Eric Laurentde070132010-07-13 04:45:46 -07008028status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
8029 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008030{
8031 status_t status = NO_ERROR;
8032
8033 if (EffectId == 0) {
8034 track->setAuxBuffer(0, NULL);
8035 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07008036 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
8037 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008038 if (effect != 0) {
8039 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8040 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
8041 } else {
8042 status = INVALID_OPERATION;
8043 }
8044 } else {
8045 status = BAD_VALUE;
8046 }
8047 }
8048 return status;
8049}
8050
8051void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
8052{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008053 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008054 sp<Track> track = mTracks[i];
8055 if (track->auxEffectId() == effectId) {
8056 attachAuxEffect_l(track, 0);
8057 }
8058 }
8059}
8060
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008061status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8062{
8063 // only one chain per input thread
8064 if (mEffectChains.size() != 0) {
8065 return INVALID_OPERATION;
8066 }
Steve Block3856b092011-10-20 11:56:00 +01008067 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008068
8069 chain->setInBuffer(NULL);
8070 chain->setOutBuffer(NULL);
8071
Eric Laurent59255e42011-07-27 19:49:51 -07008072 checkSuspendOnAddEffectChain_l(chain);
8073
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008074 mEffectChains.add(chain);
8075
8076 return NO_ERROR;
8077}
8078
8079size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8080{
Steve Block3856b092011-10-20 11:56:00 +01008081 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00008082 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008083 "removeEffectChain_l() %p invalid chain size %d on thread %p",
8084 chain.get(), mEffectChains.size(), this);
8085 if (mEffectChains.size() == 1) {
8086 mEffectChains.removeAt(0);
8087 }
8088 return 0;
8089}
8090
Mathias Agopian65ab4712010-07-14 17:59:35 -07008091// ----------------------------------------------------------------------------
8092// EffectModule implementation
8093// ----------------------------------------------------------------------------
8094
8095#undef LOG_TAG
8096#define LOG_TAG "AudioFlinger::EffectModule"
8097
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008098AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008099 const wp<AudioFlinger::EffectChain>& chain,
8100 effect_descriptor_t *desc,
8101 int id,
8102 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07008103 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
8104 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07008105 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07008106 // mConfig is set by configure() and not used before then
8107 mEffectInterface(NULL),
8108 mStatus(NO_INIT), mState(IDLE),
8109 // mMaxDisableWaitCnt is set by configure() and not used before then
8110 // mDisableWaitCnt is set by process() and updateState() and not used before then
8111 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008112{
Steve Block3856b092011-10-20 11:56:00 +01008113 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008114 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008115
8116 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008117 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008118
8119 if (mStatus != NO_ERROR) {
8120 return;
8121 }
8122 lStatus = init();
8123 if (lStatus < 0) {
8124 mStatus = lStatus;
8125 goto Error;
8126 }
8127
Steve Block3856b092011-10-20 11:56:00 +01008128 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008129 return;
8130Error:
8131 EffectRelease(mEffectInterface);
8132 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008133 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008134}
8135
8136AudioFlinger::EffectModule::~EffectModule()
8137{
Steve Block3856b092011-10-20 11:56:00 +01008138 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008139 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008140 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8141 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8142 sp<ThreadBase> thread = mThread.promote();
8143 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008144 audio_stream_t *stream = thread->stream();
8145 if (stream != NULL) {
8146 stream->remove_audio_effect(stream, mEffectInterface);
8147 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008148 }
8149 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008150 // release effect engine
8151 EffectRelease(mEffectInterface);
8152 }
8153}
8154
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008155status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008156{
8157 status_t status;
8158
8159 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008160 int priority = handle->priority();
8161 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008162 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008163 size_t i;
8164 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008165 EffectHandle *h = mHandles[i];
8166 if (h == NULL || h->destroyed_l()) continue;
8167 // first non destroyed handle is considered in control
8168 if (controlHandle == NULL)
8169 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008170 if (h->priority() <= priority) break;
8171 }
8172 // if inserted in first place, move effect control from previous owner to this handle
8173 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008174 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008175 if (controlHandle != NULL) {
8176 enabled = controlHandle->enabled();
8177 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008178 }
Eric Laurent59255e42011-07-27 19:49:51 -07008179 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008180 status = NO_ERROR;
8181 } else {
8182 status = ALREADY_EXISTS;
8183 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008184 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008185 mHandles.insertAt(handle, i);
8186 return status;
8187}
8188
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008189size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008190{
8191 Mutex::Autolock _l(mLock);
8192 size_t size = mHandles.size();
8193 size_t i;
8194 for (i = 0; i < size; i++) {
8195 if (mHandles[i] == handle) break;
8196 }
8197 if (i == size) {
8198 return size;
8199 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008200 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008201
Mathias Agopian65ab4712010-07-14 17:59:35 -07008202 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008203 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008204 if (i == 0) {
8205 EffectHandle *h = controlHandle_l();
8206 if (h != NULL) {
8207 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008208 }
8209 }
8210
Eric Laurentec437d82011-07-26 20:54:46 -07008211 // Prevent calls to process() and other functions on effect interface from now on.
8212 // The effect engine will be released by the destructor when the last strong reference on
8213 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008214 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008215 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008216 }
8217
Eric Laurente65c8912012-07-20 15:57:23 -07008218 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008219}
8220
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008221// must be called with EffectModule::mLock held
8222AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008223{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008224 // the first valid handle in the list has control over the module
8225 for (size_t i = 0; i < mHandles.size(); i++) {
8226 EffectHandle *h = mHandles[i];
8227 if (h != NULL && !h->destroyed_l()) {
8228 return h;
8229 }
8230 }
8231
8232 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008233}
8234
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008235size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008236{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008237 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008238 // keep a strong reference on this EffectModule to avoid calling the
8239 // destructor before we exit
8240 sp<EffectModule> keep(this);
8241 {
8242 sp<ThreadBase> thread = mThread.promote();
8243 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008244 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008245 }
8246 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008247 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008248}
8249
8250void AudioFlinger::EffectModule::updateState() {
8251 Mutex::Autolock _l(mLock);
8252
8253 switch (mState) {
8254 case RESTART:
8255 reset_l();
8256 // FALL THROUGH
8257
8258 case STARTING:
8259 // clear auxiliary effect input buffer for next accumulation
8260 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8261 memset(mConfig.inputCfg.buffer.raw,
8262 0,
8263 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8264 }
8265 start_l();
8266 mState = ACTIVE;
8267 break;
8268 case STOPPING:
8269 stop_l();
8270 mDisableWaitCnt = mMaxDisableWaitCnt;
8271 mState = STOPPED;
8272 break;
8273 case STOPPED:
8274 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8275 // turn off sequence.
8276 if (--mDisableWaitCnt == 0) {
8277 reset_l();
8278 mState = IDLE;
8279 }
8280 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008281 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008282 break;
8283 }
8284}
8285
8286void AudioFlinger::EffectModule::process()
8287{
8288 Mutex::Autolock _l(mLock);
8289
Eric Laurentec437d82011-07-26 20:54:46 -07008290 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008291 mConfig.inputCfg.buffer.raw == NULL ||
8292 mConfig.outputCfg.buffer.raw == NULL) {
8293 return;
8294 }
8295
Eric Laurent8f45bd72010-08-31 13:50:07 -07008296 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008297 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8298 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008299 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008300 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008301 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008302 }
8303
8304 // do the actual processing in the effect engine
8305 int ret = (*mEffectInterface)->process(mEffectInterface,
8306 &mConfig.inputCfg.buffer,
8307 &mConfig.outputCfg.buffer);
8308
8309 // force transition to IDLE state when engine is ready
8310 if (mState == STOPPED && ret == -ENODATA) {
8311 mDisableWaitCnt = 1;
8312 }
8313
8314 // clear auxiliary effect input buffer for next accumulation
8315 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008316 memset(mConfig.inputCfg.buffer.raw, 0,
8317 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008318 }
8319 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008320 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8321 // If an insert effect is idle and input buffer is different from output buffer,
8322 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008323 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008324 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008325 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8326 int16_t *in = mConfig.inputCfg.buffer.s16;
8327 int16_t *out = mConfig.outputCfg.buffer.s16;
8328 for (size_t i = 0; i < frameCnt; i++) {
8329 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008330 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008331 }
8332 }
8333}
8334
8335void AudioFlinger::EffectModule::reset_l()
8336{
8337 if (mEffectInterface == NULL) {
8338 return;
8339 }
8340 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8341}
8342
8343status_t AudioFlinger::EffectModule::configure()
8344{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008345 if (mEffectInterface == NULL) {
8346 return NO_INIT;
8347 }
8348
8349 sp<ThreadBase> thread = mThread.promote();
8350 if (thread == 0) {
8351 return DEAD_OBJECT;
8352 }
8353
8354 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07008355 audio_channel_mask_t channelMask = thread->channelMask();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008356
8357 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008358 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008359 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07008360 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008361 }
Glenn Kasten254af182012-07-03 14:59:05 -07008362 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07008363 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8364 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008365 mConfig.inputCfg.samplingRate = thread->sampleRate();
8366 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8367 mConfig.inputCfg.bufferProvider.cookie = NULL;
8368 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8369 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8370 mConfig.outputCfg.bufferProvider.cookie = NULL;
8371 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8372 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8373 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8374 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008375 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008376 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008377 // - in other sessions:
8378 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8379 // other effect: overwrites output buffer: input buffer == output buffer
8380 // Auxiliary effect:
8381 // accumulates in output buffer: input buffer != output buffer
8382 // Therefore: accumulate <=> input buffer != output buffer
8383 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8384 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8385 } else {
8386 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8387 }
8388 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8389 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8390 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8391 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8392
Steve Block3856b092011-10-20 11:56:00 +01008393 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008394 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8395
Mathias Agopian65ab4712010-07-14 17:59:35 -07008396 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008397 uint32_t size = sizeof(int);
8398 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008399 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008400 sizeof(effect_config_t),
8401 &mConfig,
8402 &size,
8403 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008404 if (status == 0) {
8405 status = cmdStatus;
8406 }
8407
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008408 if (status == 0 &&
8409 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8410 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8411 effect_param_t *p = (effect_param_t *)buf32;
8412
8413 p->psize = sizeof(uint32_t);
8414 p->vsize = sizeof(uint32_t);
8415 size = sizeof(int);
8416 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8417
8418 uint32_t latency = 0;
8419 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8420 if (pbt != NULL) {
8421 latency = pbt->latency_l();
8422 }
8423
8424 *((int32_t *)p->data + 1)= latency;
8425 (*mEffectInterface)->command(mEffectInterface,
8426 EFFECT_CMD_SET_PARAM,
8427 sizeof(effect_param_t) + 8,
8428 &buf32,
8429 &size,
8430 &cmdStatus);
8431 }
8432
Mathias Agopian65ab4712010-07-14 17:59:35 -07008433 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8434 (1000 * mConfig.outputCfg.buffer.frameCount);
8435
8436 return status;
8437}
8438
8439status_t AudioFlinger::EffectModule::init()
8440{
8441 Mutex::Autolock _l(mLock);
8442 if (mEffectInterface == NULL) {
8443 return NO_INIT;
8444 }
8445 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008446 uint32_t size = sizeof(status_t);
8447 status_t status = (*mEffectInterface)->command(mEffectInterface,
8448 EFFECT_CMD_INIT,
8449 0,
8450 NULL,
8451 &size,
8452 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008453 if (status == 0) {
8454 status = cmdStatus;
8455 }
8456 return status;
8457}
8458
Eric Laurentec35a142011-10-05 17:42:25 -07008459status_t AudioFlinger::EffectModule::start()
8460{
8461 Mutex::Autolock _l(mLock);
8462 return start_l();
8463}
8464
Mathias Agopian65ab4712010-07-14 17:59:35 -07008465status_t AudioFlinger::EffectModule::start_l()
8466{
8467 if (mEffectInterface == NULL) {
8468 return NO_INIT;
8469 }
8470 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008471 uint32_t size = sizeof(status_t);
8472 status_t status = (*mEffectInterface)->command(mEffectInterface,
8473 EFFECT_CMD_ENABLE,
8474 0,
8475 NULL,
8476 &size,
8477 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008478 if (status == 0) {
8479 status = cmdStatus;
8480 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008481 if (status == 0 &&
8482 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8483 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8484 sp<ThreadBase> thread = mThread.promote();
8485 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008486 audio_stream_t *stream = thread->stream();
8487 if (stream != NULL) {
8488 stream->add_audio_effect(stream, mEffectInterface);
8489 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008490 }
8491 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008492 return status;
8493}
8494
Eric Laurentec437d82011-07-26 20:54:46 -07008495status_t AudioFlinger::EffectModule::stop()
8496{
8497 Mutex::Autolock _l(mLock);
8498 return stop_l();
8499}
8500
Mathias Agopian65ab4712010-07-14 17:59:35 -07008501status_t AudioFlinger::EffectModule::stop_l()
8502{
8503 if (mEffectInterface == NULL) {
8504 return NO_INIT;
8505 }
8506 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008507 uint32_t size = sizeof(status_t);
8508 status_t status = (*mEffectInterface)->command(mEffectInterface,
8509 EFFECT_CMD_DISABLE,
8510 0,
8511 NULL,
8512 &size,
8513 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008514 if (status == 0) {
8515 status = cmdStatus;
8516 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008517 if (status == 0 &&
8518 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8519 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8520 sp<ThreadBase> thread = mThread.promote();
8521 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008522 audio_stream_t *stream = thread->stream();
8523 if (stream != NULL) {
8524 stream->remove_audio_effect(stream, mEffectInterface);
8525 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008526 }
8527 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008528 return status;
8529}
8530
Eric Laurent25f43952010-07-28 05:40:18 -07008531status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8532 uint32_t cmdSize,
8533 void *pCmdData,
8534 uint32_t *replySize,
8535 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008536{
8537 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008538// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008539
Eric Laurentec437d82011-07-26 20:54:46 -07008540 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008541 return NO_INIT;
8542 }
Eric Laurent25f43952010-07-28 05:40:18 -07008543 status_t status = (*mEffectInterface)->command(mEffectInterface,
8544 cmdCode,
8545 cmdSize,
8546 pCmdData,
8547 replySize,
8548 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008549 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008550 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008551 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008552 EffectHandle *h = mHandles[i];
8553 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008554 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8555 }
8556 }
8557 }
8558 return status;
8559}
8560
8561status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8562{
8563 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008564 return setEnabled_l(enabled);
8565}
8566
8567// must be called with EffectModule::mLock held
8568status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8569{
8570
Steve Block3856b092011-10-20 11:56:00 +01008571 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008572
8573 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008574 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8575 if (enabled && status != NO_ERROR) {
8576 return status;
8577 }
8578
Mathias Agopian65ab4712010-07-14 17:59:35 -07008579 switch (mState) {
8580 // going from disabled to enabled
8581 case IDLE:
8582 mState = STARTING;
8583 break;
8584 case STOPPED:
8585 mState = RESTART;
8586 break;
8587 case STOPPING:
8588 mState = ACTIVE;
8589 break;
8590
8591 // going from enabled to disabled
8592 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008593 mState = STOPPED;
8594 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008595 case STARTING:
8596 mState = IDLE;
8597 break;
8598 case ACTIVE:
8599 mState = STOPPING;
8600 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008601 case DESTROYED:
8602 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008603 }
8604 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008605 EffectHandle *h = mHandles[i];
8606 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008607 h->setEnabled(enabled);
8608 }
8609 }
8610 }
8611 return NO_ERROR;
8612}
8613
Glenn Kastenc59c0042012-02-02 14:06:11 -08008614bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008615{
8616 switch (mState) {
8617 case RESTART:
8618 case STARTING:
8619 case ACTIVE:
8620 return true;
8621 case IDLE:
8622 case STOPPING:
8623 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008624 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008625 default:
8626 return false;
8627 }
8628}
8629
Glenn Kastenc59c0042012-02-02 14:06:11 -08008630bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008631{
8632 switch (mState) {
8633 case RESTART:
8634 case ACTIVE:
8635 case STOPPING:
8636 case STOPPED:
8637 return true;
8638 case IDLE:
8639 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008640 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008641 default:
8642 return false;
8643 }
8644}
8645
Mathias Agopian65ab4712010-07-14 17:59:35 -07008646status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8647{
8648 Mutex::Autolock _l(mLock);
8649 status_t status = NO_ERROR;
8650
8651 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8652 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008653 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008654 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8655 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008656 status_t cmdStatus;
8657 uint32_t volume[2];
8658 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008659 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008660 volume[0] = *left;
8661 volume[1] = *right;
8662 if (controller) {
8663 pVolume = volume;
8664 }
Eric Laurent25f43952010-07-28 05:40:18 -07008665 status = (*mEffectInterface)->command(mEffectInterface,
8666 EFFECT_CMD_SET_VOLUME,
8667 size,
8668 volume,
8669 &size,
8670 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008671 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8672 *left = volume[0];
8673 *right = volume[1];
8674 }
8675 }
8676 return status;
8677}
8678
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008679status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008680{
8681 Mutex::Autolock _l(mLock);
8682 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008683 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8684 // audio pre processing modules on RecordThread can receive both output and
8685 // input device indication in the same call
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008686 audio_devices_t dev = device & AUDIO_DEVICE_OUT_ALL;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008687 if (dev) {
8688 status_t cmdStatus;
8689 uint32_t size = sizeof(status_t);
8690
8691 status = (*mEffectInterface)->command(mEffectInterface,
8692 EFFECT_CMD_SET_DEVICE,
8693 sizeof(uint32_t),
8694 &dev,
8695 &size,
8696 &cmdStatus);
8697 if (status == NO_ERROR) {
8698 status = cmdStatus;
8699 }
8700 }
8701 dev = device & AUDIO_DEVICE_IN_ALL;
8702 if (dev) {
8703 status_t cmdStatus;
8704 uint32_t size = sizeof(status_t);
8705
8706 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8707 EFFECT_CMD_SET_INPUT_DEVICE,
8708 sizeof(uint32_t),
8709 &dev,
8710 &size,
8711 &cmdStatus);
8712 if (status2 == NO_ERROR) {
8713 status2 = cmdStatus;
8714 }
8715 if (status == NO_ERROR) {
8716 status = status2;
8717 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008718 }
8719 }
8720 return status;
8721}
8722
Glenn Kastenf78aee72012-01-04 11:00:47 -08008723status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008724{
8725 Mutex::Autolock _l(mLock);
8726 status_t status = NO_ERROR;
8727 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008728 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008729 uint32_t size = sizeof(status_t);
8730 status = (*mEffectInterface)->command(mEffectInterface,
8731 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008732 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008733 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008734 &size,
8735 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008736 if (status == NO_ERROR) {
8737 status = cmdStatus;
8738 }
8739 }
8740 return status;
8741}
8742
Eric Laurent59255e42011-07-27 19:49:51 -07008743void AudioFlinger::EffectModule::setSuspended(bool suspended)
8744{
8745 Mutex::Autolock _l(mLock);
8746 mSuspended = suspended;
8747}
Glenn Kastena3a85482012-01-04 11:01:11 -08008748
8749bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008750{
8751 Mutex::Autolock _l(mLock);
8752 return mSuspended;
8753}
8754
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008755bool AudioFlinger::EffectModule::purgeHandles()
8756{
8757 bool enabled = false;
8758 Mutex::Autolock _l(mLock);
8759 for (size_t i = 0; i < mHandles.size(); i++) {
8760 EffectHandle *handle = mHandles[i];
8761 if (handle != NULL && !handle->destroyed_l()) {
8762 handle->effect().clear();
8763 if (handle->hasControl()) {
8764 enabled = handle->enabled();
8765 }
8766 }
8767 }
8768 return enabled;
8769}
8770
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07008771void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008772{
8773 const size_t SIZE = 256;
8774 char buffer[SIZE];
8775 String8 result;
8776
8777 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8778 result.append(buffer);
8779
8780 bool locked = tryLock(mLock);
8781 // failed to lock - AudioFlinger is probably deadlocked
8782 if (!locked) {
8783 result.append("\t\tCould not lock Fx mutex:\n");
8784 }
8785
8786 result.append("\t\tSession Status State Engine:\n");
8787 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8788 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8789 result.append(buffer);
8790
8791 result.append("\t\tDescriptor:\n");
8792 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8793 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8794 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8795 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8796 result.append(buffer);
8797 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8798 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8799 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8800 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8801 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008802 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008803 mDescriptor.apiVersion,
8804 mDescriptor.flags);
8805 result.append(buffer);
8806 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8807 mDescriptor.name);
8808 result.append(buffer);
8809 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8810 mDescriptor.implementor);
8811 result.append(buffer);
8812
8813 result.append("\t\t- Input configuration:\n");
8814 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8815 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8816 (uint32_t)mConfig.inputCfg.buffer.raw,
8817 mConfig.inputCfg.buffer.frameCount,
8818 mConfig.inputCfg.samplingRate,
8819 mConfig.inputCfg.channels,
8820 mConfig.inputCfg.format);
8821 result.append(buffer);
8822
8823 result.append("\t\t- Output configuration:\n");
8824 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8825 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8826 (uint32_t)mConfig.outputCfg.buffer.raw,
8827 mConfig.outputCfg.buffer.frameCount,
8828 mConfig.outputCfg.samplingRate,
8829 mConfig.outputCfg.channels,
8830 mConfig.outputCfg.format);
8831 result.append(buffer);
8832
8833 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8834 result.append(buffer);
8835 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8836 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008837 EffectHandle *handle = mHandles[i];
8838 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008839 handle->dump(buffer, SIZE);
8840 result.append(buffer);
8841 }
8842 }
8843
8844 result.append("\n");
8845
8846 write(fd, result.string(), result.length());
8847
8848 if (locked) {
8849 mLock.unlock();
8850 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008851}
8852
8853// ----------------------------------------------------------------------------
8854// EffectHandle implementation
8855// ----------------------------------------------------------------------------
8856
8857#undef LOG_TAG
8858#define LOG_TAG "AudioFlinger::EffectHandle"
8859
8860AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8861 const sp<AudioFlinger::Client>& client,
8862 const sp<IEffectClient>& effectClient,
8863 int32_t priority)
8864 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008865 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008866 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008867{
Steve Block3856b092011-10-20 11:56:00 +01008868 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008869
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008870 if (client == 0) {
8871 return;
8872 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008873 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8874 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8875 if (mCblkMemory != 0) {
8876 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8877
Glenn Kastena0d68332012-01-27 16:47:15 -08008878 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008879 new(mCblk) effect_param_cblk_t();
8880 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008881 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008882 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008883 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008884 return;
8885 }
8886}
8887
8888AudioFlinger::EffectHandle::~EffectHandle()
8889{
Steve Block3856b092011-10-20 11:56:00 +01008890 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008891
8892 if (mEffect == 0) {
8893 mDestroyed = true;
8894 return;
8895 }
8896 mEffect->lock();
8897 mDestroyed = true;
8898 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008899 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008900}
8901
8902status_t AudioFlinger::EffectHandle::enable()
8903{
Steve Block3856b092011-10-20 11:56:00 +01008904 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008905 if (!mHasControl) return INVALID_OPERATION;
8906 if (mEffect == 0) return DEAD_OBJECT;
8907
Eric Laurentdb7c0792011-08-10 10:37:50 -07008908 if (mEnabled) {
8909 return NO_ERROR;
8910 }
8911
Eric Laurent59255e42011-07-27 19:49:51 -07008912 mEnabled = true;
8913
8914 sp<ThreadBase> thread = mEffect->thread().promote();
8915 if (thread != 0) {
8916 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8917 }
8918
8919 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8920 if (mEffect->suspended()) {
8921 return NO_ERROR;
8922 }
8923
Eric Laurentdb7c0792011-08-10 10:37:50 -07008924 status_t status = mEffect->setEnabled(true);
8925 if (status != NO_ERROR) {
8926 if (thread != 0) {
8927 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8928 }
8929 mEnabled = false;
8930 }
8931 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008932}
8933
8934status_t AudioFlinger::EffectHandle::disable()
8935{
Steve Block3856b092011-10-20 11:56:00 +01008936 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008937 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008938 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008939
Eric Laurentdb7c0792011-08-10 10:37:50 -07008940 if (!mEnabled) {
8941 return NO_ERROR;
8942 }
Eric Laurent59255e42011-07-27 19:49:51 -07008943 mEnabled = false;
8944
8945 if (mEffect->suspended()) {
8946 return NO_ERROR;
8947 }
8948
8949 status_t status = mEffect->setEnabled(false);
8950
8951 sp<ThreadBase> thread = mEffect->thread().promote();
8952 if (thread != 0) {
8953 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8954 }
8955
8956 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008957}
8958
8959void AudioFlinger::EffectHandle::disconnect()
8960{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008961 disconnect(true);
8962}
8963
Glenn Kasten58123c32012-02-03 10:32:24 -08008964void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008965{
Glenn Kasten58123c32012-02-03 10:32:24 -08008966 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008967 if (mEffect == 0) {
8968 return;
8969 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008970 // restore suspended effects if the disconnected handle was enabled and the last one.
8971 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008972 sp<ThreadBase> thread = mEffect->thread().promote();
8973 if (thread != 0) {
8974 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8975 }
Eric Laurent59255e42011-07-27 19:49:51 -07008976 }
8977
Mathias Agopian65ab4712010-07-14 17:59:35 -07008978 // release sp on module => module destructor can be called now
8979 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008980 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008981 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008982 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008983 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8984 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008985 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008986 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008987 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8988 mClient.clear();
8989 }
8990}
8991
Eric Laurent25f43952010-07-28 05:40:18 -07008992status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8993 uint32_t cmdSize,
8994 void *pCmdData,
8995 uint32_t *replySize,
8996 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008997{
Steve Block3856b092011-10-20 11:56:00 +01008998// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008999// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07009000
9001 // only get parameter command is permitted for applications not controlling the effect
9002 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
9003 return INVALID_OPERATION;
9004 }
9005 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009006 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009007
9008 // handle commands that are not forwarded transparently to effect engine
9009 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
9010 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
9011 // no risk to block the whole media server process or mixer threads is we are stuck here
9012 Mutex::Autolock _l(mCblk->lock);
9013 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
9014 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
9015 mCblk->serverIndex = 0;
9016 mCblk->clientIndex = 0;
9017 return BAD_VALUE;
9018 }
9019 status_t status = NO_ERROR;
9020 while (mCblk->serverIndex < mCblk->clientIndex) {
9021 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07009022 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009023 int *p = (int *)(mBuffer + mCblk->serverIndex);
9024 int size = *p++;
9025 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009026 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009027 break;
9028 }
9029 effect_param_t *param = (effect_param_t *)p;
9030 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009031 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009032 mCblk->serverIndex += size;
9033 continue;
9034 }
Eric Laurent25f43952010-07-28 05:40:18 -07009035 uint32_t psize = sizeof(effect_param_t) +
9036 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
9037 param->vsize;
9038 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
9039 psize,
9040 p,
9041 &rsize,
9042 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07009043 // stop at first error encountered
9044 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009045 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07009046 *(int *)pReplyData = reply;
9047 break;
9048 } else if (reply != NO_ERROR) {
9049 *(int *)pReplyData = reply;
9050 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009051 }
9052 mCblk->serverIndex += size;
9053 }
9054 mCblk->serverIndex = 0;
9055 mCblk->clientIndex = 0;
9056 return status;
9057 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009058 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009059 return enable();
9060 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009061 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009062 return disable();
9063 }
9064
9065 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9066}
9067
Eric Laurent59255e42011-07-27 19:49:51 -07009068void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009069{
Steve Block3856b092011-10-20 11:56:00 +01009070 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009071
9072 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07009073 mEnabled = enabled;
9074
Mathias Agopian65ab4712010-07-14 17:59:35 -07009075 if (signal && mEffectClient != 0) {
9076 mEffectClient->controlStatusChanged(hasControl);
9077 }
9078}
9079
Eric Laurent25f43952010-07-28 05:40:18 -07009080void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
9081 uint32_t cmdSize,
9082 void *pCmdData,
9083 uint32_t replySize,
9084 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009085{
9086 if (mEffectClient != 0) {
9087 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9088 }
9089}
9090
9091
9092
9093void AudioFlinger::EffectHandle::setEnabled(bool enabled)
9094{
9095 if (mEffectClient != 0) {
9096 mEffectClient->enableStatusChanged(enabled);
9097 }
9098}
9099
9100status_t AudioFlinger::EffectHandle::onTransact(
9101 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9102{
9103 return BnEffect::onTransact(code, data, reply, flags);
9104}
9105
9106
9107void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
9108{
Glenn Kastena0d68332012-01-27 16:47:15 -08009109 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009110
9111 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08009112 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07009113 mPriority,
9114 mHasControl,
9115 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009116 mCblk ? mCblk->clientIndex : 0,
9117 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07009118 );
9119
9120 if (locked) {
9121 mCblk->lock.unlock();
9122 }
9123}
9124
9125#undef LOG_TAG
9126#define LOG_TAG "AudioFlinger::EffectChain"
9127
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009128AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009129 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009130 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07009131 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9132 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009133{
Dima Zavinfce7a472011-04-19 22:30:36 -07009134 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009135 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009136 return;
9137 }
9138 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9139 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009140}
9141
9142AudioFlinger::EffectChain::~EffectChain()
9143{
9144 if (mOwnInBuffer) {
9145 delete mInBuffer;
9146 }
9147
9148}
9149
Eric Laurent59255e42011-07-27 19:49:51 -07009150// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009151sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009152{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009153 size_t size = mEffects.size();
9154
9155 for (size_t i = 0; i < size; i++) {
9156 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009157 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009158 }
9159 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009160 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009161}
9162
Eric Laurent59255e42011-07-27 19:49:51 -07009163// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009164sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009165{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009166 size_t size = mEffects.size();
9167
9168 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009169 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9170 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009171 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009172 }
9173 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009174 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009175}
9176
Eric Laurent59255e42011-07-27 19:49:51 -07009177// getEffectFromType_l() must be called with ThreadBase::mLock held
9178sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9179 const effect_uuid_t *type)
9180{
Eric Laurent59255e42011-07-27 19:49:51 -07009181 size_t size = mEffects.size();
9182
9183 for (size_t i = 0; i < size; i++) {
9184 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009185 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009186 }
9187 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009188 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009189}
9190
Eric Laurent91b14c42012-05-30 12:30:29 -07009191void AudioFlinger::EffectChain::clearInputBuffer()
9192{
9193 Mutex::Autolock _l(mLock);
9194 sp<ThreadBase> thread = mThread.promote();
9195 if (thread == 0) {
9196 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9197 return;
9198 }
9199 clearInputBuffer_l(thread);
9200}
9201
9202// Must be called with EffectChain::mLock locked
9203void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9204{
9205 size_t numSamples = thread->frameCount() * thread->channelCount();
9206 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9207
9208}
9209
Mathias Agopian65ab4712010-07-14 17:59:35 -07009210// Must be called with EffectChain::mLock locked
9211void AudioFlinger::EffectChain::process_l()
9212{
Eric Laurentdac69112010-09-28 14:09:57 -07009213 sp<ThreadBase> thread = mThread.promote();
9214 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009215 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009216 return;
9217 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009218 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9219 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009220 // always process effects unless no more tracks are on the session and the effect tail
9221 // has been rendered
9222 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009223 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009224 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009225
Eric Laurent544fe9b2011-11-11 15:42:52 -08009226 if (!tracksOnSession && mTailBufferCount == 0) {
9227 doProcess = false;
9228 }
9229
9230 if (activeTrackCnt() == 0) {
9231 // if no track is active and the effect tail has not been rendered,
9232 // the input buffer must be cleared here as the mixer process will not do it
9233 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009234 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009235 if (mTailBufferCount > 0) {
9236 mTailBufferCount--;
9237 }
9238 }
9239 }
Eric Laurentdac69112010-09-28 14:09:57 -07009240 }
9241
Mathias Agopian65ab4712010-07-14 17:59:35 -07009242 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009243 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009244 for (size_t i = 0; i < size; i++) {
9245 mEffects[i]->process();
9246 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009247 }
9248 for (size_t i = 0; i < size; i++) {
9249 mEffects[i]->updateState();
9250 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009251}
9252
Eric Laurentcab11242010-07-15 12:50:15 -07009253// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009254status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009255{
9256 effect_descriptor_t desc = effect->desc();
9257 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9258
9259 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009260 effect->setChain(this);
9261 sp<ThreadBase> thread = mThread.promote();
9262 if (thread == 0) {
9263 return NO_INIT;
9264 }
9265 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009266
9267 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9268 // Auxiliary effects are inserted at the beginning of mEffects vector as
9269 // they are processed first and accumulated in chain input buffer
9270 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009271
Mathias Agopian65ab4712010-07-14 17:59:35 -07009272 // the input buffer for auxiliary effect contains mono samples in
9273 // 32 bit format. This is to avoid saturation in AudoMixer
9274 // accumulation stage. Saturation is done in EffectModule::process() before
9275 // calling the process in effect engine
9276 size_t numSamples = thread->frameCount();
9277 int32_t *buffer = new int32_t[numSamples];
9278 memset(buffer, 0, numSamples * sizeof(int32_t));
9279 effect->setInBuffer((int16_t *)buffer);
9280 // auxiliary effects output samples to chain input buffer for further processing
9281 // by insert effects
9282 effect->setOutBuffer(mInBuffer);
9283 } else {
9284 // Insert effects are inserted at the end of mEffects vector as they are processed
9285 // after track and auxiliary effects.
9286 // Insert effect order as a function of indicated preference:
9287 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9288 // another effect is present
9289 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9290 // last effect claiming first position
9291 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9292 // first effect claiming last position
9293 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9294 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9295 // already present
9296
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009297 size_t size = mEffects.size();
9298 size_t idx_insert = size;
9299 ssize_t idx_insert_first = -1;
9300 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009301
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009302 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009303 effect_descriptor_t d = mEffects[i]->desc();
9304 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9305 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9306 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9307 // check invalid effect chaining combinations
9308 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9309 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009310 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009311 return INVALID_OPERATION;
9312 }
9313 // remember position of first insert effect and by default
9314 // select this as insert position for new effect
9315 if (idx_insert == size) {
9316 idx_insert = i;
9317 }
9318 // remember position of last insert effect claiming
9319 // first position
9320 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9321 idx_insert_first = i;
9322 }
9323 // remember position of first insert effect claiming
9324 // last position
9325 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9326 idx_insert_last == -1) {
9327 idx_insert_last = i;
9328 }
9329 }
9330 }
9331
9332 // modify idx_insert from first position if needed
9333 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9334 if (idx_insert_last != -1) {
9335 idx_insert = idx_insert_last;
9336 } else {
9337 idx_insert = size;
9338 }
9339 } else {
9340 if (idx_insert_first != -1) {
9341 idx_insert = idx_insert_first + 1;
9342 }
9343 }
9344
9345 // always read samples from chain input buffer
9346 effect->setInBuffer(mInBuffer);
9347
9348 // if last effect in the chain, output samples to chain
9349 // output buffer, otherwise to chain input buffer
9350 if (idx_insert == size) {
9351 if (idx_insert != 0) {
9352 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9353 mEffects[idx_insert-1]->configure();
9354 }
9355 effect->setOutBuffer(mOutBuffer);
9356 } else {
9357 effect->setOutBuffer(mInBuffer);
9358 }
9359 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009360
Steve Block3856b092011-10-20 11:56:00 +01009361 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009362 }
9363 effect->configure();
9364 return NO_ERROR;
9365}
9366
Eric Laurentcab11242010-07-15 12:50:15 -07009367// removeEffect_l() must be called with PlaybackThread::mLock held
9368size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009369{
9370 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009371 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009372 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9373
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009374 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009375 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009376 // calling stop here will remove pre-processing effect from the audio HAL.
9377 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9378 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009379 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9380 mEffects[i]->state() == EffectModule::STOPPING) {
9381 mEffects[i]->stop();
9382 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009383 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9384 delete[] effect->inBuffer();
9385 } else {
9386 if (i == size - 1 && i != 0) {
9387 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9388 mEffects[i - 1]->configure();
9389 }
9390 }
9391 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009392 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009393 break;
9394 }
9395 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009396
9397 return mEffects.size();
9398}
9399
Eric Laurentcab11242010-07-15 12:50:15 -07009400// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009401void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009402{
9403 size_t size = mEffects.size();
9404 for (size_t i = 0; i < size; i++) {
9405 mEffects[i]->setDevice(device);
9406 }
9407}
9408
Eric Laurentcab11242010-07-15 12:50:15 -07009409// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009410void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009411{
9412 size_t size = mEffects.size();
9413 for (size_t i = 0; i < size; i++) {
9414 mEffects[i]->setMode(mode);
9415 }
9416}
9417
Eric Laurentcab11242010-07-15 12:50:15 -07009418// setVolume_l() must be called with PlaybackThread::mLock held
9419bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009420{
9421 uint32_t newLeft = *left;
9422 uint32_t newRight = *right;
9423 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009424 int ctrlIdx = -1;
9425 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009426
Eric Laurentcab11242010-07-15 12:50:15 -07009427 // first update volume controller
9428 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009429 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009430 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9431 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009432 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009433 break;
9434 }
9435 }
9436
9437 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009438 if (hasControl) {
9439 *left = mNewLeftVolume;
9440 *right = mNewRightVolume;
9441 }
9442 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009443 }
9444
9445 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009446 mLeftVolume = newLeft;
9447 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009448
9449 // second get volume update from volume controller
9450 if (ctrlIdx >= 0) {
9451 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009452 mNewLeftVolume = newLeft;
9453 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009454 }
9455 // then indicate volume to all other effects in chain.
9456 // Pass altered volume to effects before volume controller
9457 // and requested volume to effects after controller
9458 uint32_t lVol = newLeft;
9459 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009460
Mathias Agopian65ab4712010-07-14 17:59:35 -07009461 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009462 if ((int)i == ctrlIdx) continue;
9463 // this also works for ctrlIdx == -1 when there is no volume controller
9464 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009465 lVol = *left;
9466 rVol = *right;
9467 }
9468 mEffects[i]->setVolume(&lVol, &rVol, false);
9469 }
9470 *left = newLeft;
9471 *right = newRight;
9472
9473 return hasControl;
9474}
9475
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009476void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009477{
9478 const size_t SIZE = 256;
9479 char buffer[SIZE];
9480 String8 result;
9481
9482 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9483 result.append(buffer);
9484
9485 bool locked = tryLock(mLock);
9486 // failed to lock - AudioFlinger is probably deadlocked
9487 if (!locked) {
9488 result.append("\tCould not lock mutex:\n");
9489 }
9490
Eric Laurentcab11242010-07-15 12:50:15 -07009491 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9492 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009493 mEffects.size(),
9494 (uint32_t)mInBuffer,
9495 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009496 mActiveTrackCnt);
9497 result.append(buffer);
9498 write(fd, result.string(), result.size());
9499
9500 for (size_t i = 0; i < mEffects.size(); ++i) {
9501 sp<EffectModule> effect = mEffects[i];
9502 if (effect != 0) {
9503 effect->dump(fd, args);
9504 }
9505 }
9506
9507 if (locked) {
9508 mLock.unlock();
9509 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009510}
9511
Eric Laurent59255e42011-07-27 19:49:51 -07009512// must be called with ThreadBase::mLock held
9513void AudioFlinger::EffectChain::setEffectSuspended_l(
9514 const effect_uuid_t *type, bool suspend)
9515{
9516 sp<SuspendedEffectDesc> desc;
9517 // use effect type UUID timelow as key as there is no real risk of identical
9518 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009519 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009520 if (suspend) {
9521 if (index >= 0) {
9522 desc = mSuspendedEffects.valueAt(index);
9523 } else {
9524 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -08009525 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07009526 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009527 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009528 }
9529 if (desc->mRefCount++ == 0) {
9530 sp<EffectModule> effect = getEffectIfEnabled(type);
9531 if (effect != 0) {
9532 desc->mEffect = effect;
9533 effect->setSuspended(true);
9534 effect->setEnabled(false);
9535 }
9536 }
9537 } else {
9538 if (index < 0) {
9539 return;
9540 }
9541 desc = mSuspendedEffects.valueAt(index);
9542 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009543 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009544 desc->mRefCount = 1;
9545 }
9546 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009547 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009548 if (desc->mEffect != 0) {
9549 sp<EffectModule> effect = desc->mEffect.promote();
9550 if (effect != 0) {
9551 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009552 effect->lock();
9553 EffectHandle *handle = effect->controlHandle_l();
9554 if (handle != NULL && !handle->destroyed_l()) {
9555 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009556 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009557 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009558 }
9559 desc->mEffect.clear();
9560 }
9561 mSuspendedEffects.removeItemsAt(index);
9562 }
9563 }
9564}
9565
9566// must be called with ThreadBase::mLock held
9567void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9568{
9569 sp<SuspendedEffectDesc> desc;
9570
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009571 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009572 if (suspend) {
9573 if (index >= 0) {
9574 desc = mSuspendedEffects.valueAt(index);
9575 } else {
9576 desc = new SuspendedEffectDesc();
9577 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009578 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009579 }
9580 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009581 Vector< sp<EffectModule> > effects;
9582 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009583 for (size_t i = 0; i < effects.size(); i++) {
9584 setEffectSuspended_l(&effects[i]->desc().type, true);
9585 }
9586 }
9587 } else {
9588 if (index < 0) {
9589 return;
9590 }
9591 desc = mSuspendedEffects.valueAt(index);
9592 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009593 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009594 desc->mRefCount = 1;
9595 }
9596 if (--desc->mRefCount == 0) {
9597 Vector<const effect_uuid_t *> types;
9598 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9599 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9600 continue;
9601 }
9602 types.add(&mSuspendedEffects.valueAt(i)->mType);
9603 }
9604 for (size_t i = 0; i < types.size(); i++) {
9605 setEffectSuspended_l(types[i], false);
9606 }
Steve Block3856b092011-10-20 11:56:00 +01009607 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009608 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9609 }
9610 }
9611}
9612
Eric Laurent6bffdb82011-09-23 08:40:41 -07009613
9614// The volume effect is used for automated tests only
9615#ifndef OPENSL_ES_H_
9616static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9617 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9618const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9619#endif //OPENSL_ES_H_
9620
Eric Laurentdb7c0792011-08-10 10:37:50 -07009621bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9622{
9623 // auxiliary effects and visualizer are never suspended on output mix
9624 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9625 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009626 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9627 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009628 return false;
9629 }
9630 return true;
9631}
9632
Glenn Kastend0539712012-01-30 12:56:03 -08009633void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009634{
Glenn Kastend0539712012-01-30 12:56:03 -08009635 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009636 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009637 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9638 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009639 }
Eric Laurent59255e42011-07-27 19:49:51 -07009640 }
Eric Laurent59255e42011-07-27 19:49:51 -07009641}
9642
9643sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9644 const effect_uuid_t *type)
9645{
Glenn Kasten090f0192012-01-30 13:00:02 -08009646 sp<EffectModule> effect = getEffectFromType_l(type);
9647 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009648}
9649
9650void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9651 bool enabled)
9652{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009653 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009654 if (enabled) {
9655 if (index < 0) {
9656 // if the effect is not suspend check if all effects are suspended
9657 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9658 if (index < 0) {
9659 return;
9660 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009661 if (!isEffectEligibleForSuspend(effect->desc())) {
9662 return;
9663 }
Eric Laurent59255e42011-07-27 19:49:51 -07009664 setEffectSuspended_l(&effect->desc().type, enabled);
9665 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009666 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009667 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009668 return;
9669 }
Eric Laurent59255e42011-07-27 19:49:51 -07009670 }
Steve Block3856b092011-10-20 11:56:00 +01009671 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009672 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009673 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9674 // if effect is requested to suspended but was not yet enabled, supend it now.
9675 if (desc->mEffect == 0) {
9676 desc->mEffect = effect;
9677 effect->setEnabled(false);
9678 effect->setSuspended(true);
9679 }
9680 } else {
9681 if (index < 0) {
9682 return;
9683 }
Steve Block3856b092011-10-20 11:56:00 +01009684 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009685 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009686 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9687 desc->mEffect.clear();
9688 effect->setSuspended(false);
9689 }
9690}
9691
Mathias Agopian65ab4712010-07-14 17:59:35 -07009692#undef LOG_TAG
9693#define LOG_TAG "AudioFlinger"
9694
9695// ----------------------------------------------------------------------------
9696
9697status_t AudioFlinger::onTransact(
9698 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9699{
9700 return BnAudioFlinger::onTransact(code, data, reply, flags);
9701}
9702
Mathias Agopian65ab4712010-07-14 17:59:35 -07009703}; // namespace android