blob: 125ec3a6583b3883c389d75b651ee321009b4676 [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070030#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070031#include <binder/Parcel.h>
32#include <binder/IPCThreadState.h>
33#include <utils/String16.h>
34#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070035#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070036
Dima Zavinfce7a472011-04-19 22:30:36 -070037#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080039#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040
Glenn Kastend3cee2f2012-03-13 17:55:35 -070041#undef ADD_BATTERY_DATA
42
43#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080044#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080045#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070046#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070047
48#include <private/media/AudioTrackShared.h>
49#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070050
Dima Zavin64760242011-05-11 14:15:23 -070051#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070052#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
54#include "AudioMixer.h"
55#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080056#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070059#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070060#include <audio_effects/effect_ns.h>
61#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Glenn Kasten3b21c502011-12-15 09:52:39 -080063#include <audio_utils/primitives.h>
64
Eric Laurentfeb0db62011-07-22 09:04:31 -070065#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080066
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070067// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080068#ifdef DEBUG_CPU_USAGE
69#include <cpustats/CentralTendencyStatistics.h>
70#include <cpustats/ThreadCpuUsage.h>
71#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070072
John Grossman4ff14ba2012-02-08 16:37:41 -080073#include <common_time/cc_helper.h>
74#include <common_time/local_clock.h>
75
Glenn Kasten58912562012-04-03 10:45:00 -070076#include "FastMixer.h"
77
78// NBAIO implementations
79#include "AudioStreamOutSink.h"
80#include "MonoPipe.h"
81#include "MonoPipeReader.h"
Glenn Kastenfbae5da2012-05-21 09:17:20 -070082#include "Pipe.h"
83#include "PipeReader.h"
Glenn Kasten58912562012-04-03 10:45:00 -070084#include "SourceAudioBufferProvider.h"
85
Glenn Kasten1dc28b72012-04-24 10:01:03 -070086#include "SchedulingPolicyService.h"
Glenn Kasten58912562012-04-03 10:45:00 -070087
Mathias Agopian65ab4712010-07-14 17:59:35 -070088// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
John Grossman1c345192012-03-27 14:00:17 -070090// Note: the following macro is used for extremely verbose logging message. In
91// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
92// 0; but one side effect of this is to turn all LOGV's as well. Some messages
93// are so verbose that we want to suppress them even when we have ALOG_ASSERT
94// turned on. Do not uncomment the #def below unless you really know what you
95// are doing and want to see all of the extremely verbose messages.
96//#define VERY_VERY_VERBOSE_LOGGING
97#ifdef VERY_VERY_VERBOSE_LOGGING
98#define ALOGVV ALOGV
99#else
100#define ALOGVV(a...) do { } while(0)
101#endif
Eric Laurentde070132010-07-13 04:45:46 -0700102
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103namespace android {
104
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800105static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
106static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700107
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800109static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110
111// retry counts for buffer fill timeout
112// 50 * ~20msecs = 1 second
113static const int8_t kMaxTrackRetries = 50;
114static const int8_t kMaxTrackStartupRetries = 50;
115// allow less retry attempts on direct output thread.
116// direct outputs can be a scarce resource in audio hardware and should
117// be released as quickly as possible.
118static const int8_t kMaxTrackRetriesDirect = 2;
119
120static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800121static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700122
Glenn Kasten7dede872011-12-13 11:04:14 -0800123// don't warn about blocked writes or record buffer overflows more often than this
124static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700125
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700126// RecordThread loop sleep time upon application overrun or audio HAL read error
127static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128
Glenn Kasten7dede872011-12-13 11:04:14 -0800129// maximum time to wait for setParameters to complete
130static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700131
Eric Laurent7cafbb32011-11-22 18:50:29 -0800132// minimum sleep time for the mixer thread loop when tracks are active but in underrun
133static const uint32_t kMinThreadSleepTimeUs = 5000;
134// maximum divider applied to the active sleep time in the mixer thread loop
135static const uint32_t kMaxThreadSleepTimeShift = 2;
136
Glenn Kasten58912562012-04-03 10:45:00 -0700137// minimum normal mix buffer size, expressed in milliseconds rather than frames
138static const uint32_t kMinNormalMixBufferSizeMs = 20;
Glenn Kasten4adcede2012-05-14 12:26:02 -0700139// maximum normal mix buffer size
140static const uint32_t kMaxNormalMixBufferSizeMs = 24;
Glenn Kasten58912562012-04-03 10:45:00 -0700141
John Grossman4ff14ba2012-02-08 16:37:41 -0800142nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800143
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700144// Whether to use fast mixer
145static const enum {
146 FastMixer_Never, // never initialize or use: for debugging only
147 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
148 // normal mixer multiplier is 1
149 FastMixer_Static, // initialize if needed, then use all the time if initialized,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700150 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700151 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700152 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700153 // FIXME for FastMixer_Dynamic:
154 // Supporting this option will require fixing HALs that can't handle large writes.
155 // For example, one HAL implementation returns an error from a large write,
156 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
157 // We could either fix the HAL implementations, or provide a wrapper that breaks
158 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
159} kUseFastMixer = FastMixer_Static;
160
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700161static uint32_t gScreenState; // incremented by 2 when screen state changes, bit 0 == 1 means "off"
162 // AudioFlinger::setParameters() updates, other threads read w/o lock
163
Glenn Kastenfd4e20c2012-06-04 11:51:12 -0700164// Priorities for requestPriority
165static const int kPriorityAudioApp = 2;
166static const int kPriorityFastMixer = 3;
167
Mathias Agopian65ab4712010-07-14 17:59:35 -0700168// ----------------------------------------------------------------------------
169
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700170#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800171// To collect the amplifier usage
172static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800173 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
174 if (service == NULL) {
175 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800176 return;
177 }
178
179 service->addBatteryData(params);
180}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700181#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800182
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700183static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700184{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700185 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700186 int rc;
187
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700188 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
189 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
190 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
191 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700192 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700193 }
194 rc = audio_hw_device_open(mod, dev);
195 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
196 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
197 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700198 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700199 }
200 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
201 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
202 rc = BAD_VALUE;
203 goto out;
204 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700205 return 0;
206
207out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700208 *dev = NULL;
209 return rc;
210}
211
Mathias Agopian65ab4712010-07-14 17:59:35 -0700212// ----------------------------------------------------------------------------
213
214AudioFlinger::AudioFlinger()
215 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800216 mPrimaryHardwareDev(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700217 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800218 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800219 mMasterMute(false),
220 mNextUniqueId(1),
221 mMode(AUDIO_MODE_INVALID),
222 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700223{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700224}
225
226void AudioFlinger::onFirstRef()
227{
Dima Zavin799a70e2011-04-18 16:57:27 -0700228 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700229
Eric Laurent93575202011-01-18 18:39:02 -0800230 Mutex::Autolock _l(mLock);
231
Dima Zavin799a70e2011-04-18 16:57:27 -0700232 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800233 char val_str[PROPERTY_VALUE_MAX] = { 0 };
234 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
235 uint32_t int_val;
236 if (1 == sscanf(val_str, "%u", &int_val)) {
237 mStandbyTimeInNsecs = milliseconds(int_val);
238 ALOGI("Using %u mSec as standby time.", int_val);
239 } else {
240 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
241 ALOGI("Using default %u mSec as standby time.",
242 (uint32_t)(mStandbyTimeInNsecs / 1000000));
243 }
244 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700245
Eric Laurenta4c5a552012-03-29 10:12:40 -0700246 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247}
248
249AudioFlinger::~AudioFlinger()
250{
251 while (!mRecordThreads.isEmpty()) {
252 // closeInput() will remove first entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700253 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700254 }
255 while (!mPlaybackThreads.isEmpty()) {
256 // closeOutput() will remove first entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700257 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700258 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700259
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800260 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
261 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700262 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
263 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700264 }
265}
266
Eric Laurenta4c5a552012-03-29 10:12:40 -0700267static const char * const audio_interfaces[] = {
268 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
269 AUDIO_HARDWARE_MODULE_ID_A2DP,
270 AUDIO_HARDWARE_MODULE_ID_USB,
271};
272#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
273
John Grossmanee578c02012-07-23 17:05:46 -0700274AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
275 audio_module_handle_t module,
276 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700277{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700278 // if module is 0, the request comes from an old policy manager and we should load
279 // well known modules
280 if (module == 0) {
281 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
282 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
283 loadHwModule_l(audio_interfaces[i]);
284 }
285 } else {
286 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700287 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
288 if (audioHwDevice != NULL) {
289 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700290 }
291 }
292 // then try to find a module supporting the requested device.
Dima Zavin799a70e2011-04-18 16:57:27 -0700293 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
John Grossmanee578c02012-07-23 17:05:46 -0700294 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
295 audio_hw_device_t *dev = audioHwDevice->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700296 if ((dev->get_supported_devices(dev) & devices) == devices)
John Grossmanee578c02012-07-23 17:05:46 -0700297 return audioHwDevice;
Dima Zavin799a70e2011-04-18 16:57:27 -0700298 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700299
Dima Zavin799a70e2011-04-18 16:57:27 -0700300 return NULL;
301}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700302
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700303void AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700304{
305 const size_t SIZE = 256;
306 char buffer[SIZE];
307 String8 result;
308
309 result.append("Clients:\n");
310 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800311 sp<Client> client = mClients.valueAt(i).promote();
312 if (client != 0) {
313 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
314 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700315 }
316 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700317
318 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800319 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700320 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
321 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800322 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700323 result.append(buffer);
324 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700325 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700326}
327
328
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700329void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700330{
331 const size_t SIZE = 256;
332 char buffer[SIZE];
333 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800334 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335
John Grossman4ff14ba2012-02-08 16:37:41 -0800336 snprintf(buffer, SIZE, "Hardware status: %d\n"
337 "Standby Time mSec: %u\n",
338 hardwareStatus,
339 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700340 result.append(buffer);
341 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700342}
343
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700344void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700345{
346 const size_t SIZE = 256;
347 char buffer[SIZE];
348 String8 result;
349 snprintf(buffer, SIZE, "Permission Denial: "
350 "can't dump AudioFlinger from pid=%d, uid=%d\n",
351 IPCThreadState::self()->getCallingPid(),
352 IPCThreadState::self()->getCallingUid());
353 result.append(buffer);
354 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700355}
356
357static bool tryLock(Mutex& mutex)
358{
359 bool locked = false;
360 for (int i = 0; i < kDumpLockRetries; ++i) {
361 if (mutex.tryLock() == NO_ERROR) {
362 locked = true;
363 break;
364 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800365 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700366 }
367 return locked;
368}
369
370status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
371{
Glenn Kasten44deb052012-02-05 18:09:08 -0800372 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700373 dumpPermissionDenial(fd, args);
374 } else {
375 // get state of hardware lock
376 bool hardwareLocked = tryLock(mHardwareLock);
377 if (!hardwareLocked) {
378 String8 result(kHardwareLockedString);
379 write(fd, result.string(), result.size());
380 } else {
381 mHardwareLock.unlock();
382 }
383
384 bool locked = tryLock(mLock);
385
386 // failed to lock - AudioFlinger is probably deadlocked
387 if (!locked) {
388 String8 result(kDeadlockedString);
389 write(fd, result.string(), result.size());
390 }
391
392 dumpClients(fd, args);
393 dumpInternals(fd, args);
394
395 // dump playback threads
396 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
397 mPlaybackThreads.valueAt(i)->dump(fd, args);
398 }
399
400 // dump record threads
401 for (size_t i = 0; i < mRecordThreads.size(); i++) {
402 mRecordThreads.valueAt(i)->dump(fd, args);
403 }
404
Dima Zavin799a70e2011-04-18 16:57:27 -0700405 // dump all hardware devs
406 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700407 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700408 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700409 }
410 if (locked) mLock.unlock();
411 }
412 return NO_ERROR;
413}
414
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800415sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
416{
417 // If pid is already in the mClients wp<> map, then use that entry
418 // (for which promote() is always != 0), otherwise create a new entry and Client.
419 sp<Client> client = mClients.valueFor(pid).promote();
420 if (client == 0) {
421 client = new Client(this, pid);
422 mClients.add(pid, client);
423 }
424
425 return client;
426}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700427
428// IAudioFlinger interface
429
430
431sp<IAudioTrack> AudioFlinger::createTrack(
432 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800433 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700434 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800435 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700436 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800438 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700439 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800440 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800441 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700442 int *sessionId,
443 status_t *status)
444{
445 sp<PlaybackThread::Track> track;
446 sp<TrackHandle> trackHandle;
447 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700448 status_t lStatus;
449 int lSessionId;
450
Glenn Kasten263709e2012-01-06 08:40:01 -0800451 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
452 // but if someone uses binder directly they could bypass that and cause us to crash
453 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000454 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700455 lStatus = BAD_VALUE;
456 goto Exit;
457 }
458
459 {
460 Mutex::Autolock _l(mLock);
461 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700462 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700463 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000464 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700465 lStatus = BAD_VALUE;
466 goto Exit;
467 }
468
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800469 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700470
Steve Block3856b092011-10-20 11:56:00 +0100471 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700472 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700473 // check if an effect chain with the same session ID is present on another
474 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700475 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700476 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
477 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700478 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700479 if (sessions & PlaybackThread::EFFECT_SESSION) {
480 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700481 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700482 }
Eric Laurentde070132010-07-13 04:45:46 -0700483 }
484 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700485 lSessionId = *sessionId;
486 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700487 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700488 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700489 if (sessionId != NULL) {
490 *sessionId = lSessionId;
491 }
492 }
Steve Block3856b092011-10-20 11:56:00 +0100493 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700494
495 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800496 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700497
498 // move effect chain to this output thread if an effect on same session was waiting
499 // for a track to be created
500 if (lStatus == NO_ERROR && effectThread != NULL) {
501 Mutex::Autolock _dl(thread->mLock);
502 Mutex::Autolock _sl(effectThread->mLock);
503 moveEffectChain_l(lSessionId, effectThread, thread, true);
504 }
Eric Laurenta011e352012-03-29 15:51:43 -0700505
506 // Look for sync events awaiting for a session to be used.
507 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
508 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
509 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700510 if (lStatus == NO_ERROR) {
511 track->setSyncEvent(mPendingSyncEvents[i]);
512 } else {
513 mPendingSyncEvents[i]->cancel();
514 }
Eric Laurenta011e352012-03-29 15:51:43 -0700515 mPendingSyncEvents.removeAt(i);
516 i--;
517 }
518 }
519 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700520 }
521 if (lStatus == NO_ERROR) {
522 trackHandle = new TrackHandle(track);
523 } else {
524 // remove local strong reference to Client before deleting the Track so that the Client
525 // destructor is called by the TrackBase destructor with mLock held
526 client.clear();
527 track.clear();
528 }
529
530Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700531 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700532 *status = lStatus;
533 }
534 return trackHandle;
535}
536
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800537uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700538{
539 Mutex::Autolock _l(mLock);
540 PlaybackThread *thread = checkPlaybackThread_l(output);
541 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000542 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700543 return 0;
544 }
545 return thread->sampleRate();
546}
547
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800548int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700549{
550 Mutex::Autolock _l(mLock);
551 PlaybackThread *thread = checkPlaybackThread_l(output);
552 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000553 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700554 return 0;
555 }
556 return thread->channelCount();
557}
558
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800559audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700560{
561 Mutex::Autolock _l(mLock);
562 PlaybackThread *thread = checkPlaybackThread_l(output);
563 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000564 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800565 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700566 }
567 return thread->format();
568}
569
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800570size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700571{
572 Mutex::Autolock _l(mLock);
573 PlaybackThread *thread = checkPlaybackThread_l(output);
574 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000575 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700576 return 0;
577 }
Glenn Kasten58912562012-04-03 10:45:00 -0700578 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
579 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700580 return thread->frameCount();
581}
582
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800583uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700584{
585 Mutex::Autolock _l(mLock);
586 PlaybackThread *thread = checkPlaybackThread_l(output);
587 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000588 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700589 return 0;
590 }
591 return thread->latency();
592}
593
594status_t AudioFlinger::setMasterVolume(float value)
595{
Eric Laurenta1884f92011-08-23 08:25:03 -0700596 status_t ret = initCheck();
597 if (ret != NO_ERROR) {
598 return ret;
599 }
600
Mathias Agopian65ab4712010-07-14 17:59:35 -0700601 // check calling permissions
602 if (!settingsAllowed()) {
603 return PERMISSION_DENIED;
604 }
605
Eric Laurenta4c5a552012-03-29 10:12:40 -0700606 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700607 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700608
John Grossmanee578c02012-07-23 17:05:46 -0700609 // Set master volume in the HALs which support it.
610 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
611 AutoMutex lock(mHardwareLock);
612 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800613
John Grossmanee578c02012-07-23 17:05:46 -0700614 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
615 if (dev->canSetMasterVolume()) {
616 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800617 }
John Grossmanee578c02012-07-23 17:05:46 -0700618 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700619 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700620
John Grossmanee578c02012-07-23 17:05:46 -0700621 // Now set the master volume in each playback thread. Playback threads
622 // assigned to HALs which do not have master volume support will apply
623 // master volume during the mix operation. Threads with HALs which do
624 // support master volume will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800625 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700626 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700627
628 return NO_ERROR;
629}
630
Glenn Kastenf78aee72012-01-04 11:00:47 -0800631status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700632{
Eric Laurenta1884f92011-08-23 08:25:03 -0700633 status_t ret = initCheck();
634 if (ret != NO_ERROR) {
635 return ret;
636 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700637
638 // check calling permissions
639 if (!settingsAllowed()) {
640 return PERMISSION_DENIED;
641 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800642 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000643 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700644 return BAD_VALUE;
645 }
646
647 { // scope for the lock
648 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700649 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700650 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700651 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700652 mHardwareStatus = AUDIO_HW_IDLE;
653 }
654
655 if (NO_ERROR == ret) {
656 Mutex::Autolock _l(mLock);
657 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800658 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700659 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700660 }
661
662 return ret;
663}
664
665status_t AudioFlinger::setMicMute(bool state)
666{
Eric Laurenta1884f92011-08-23 08:25:03 -0700667 status_t ret = initCheck();
668 if (ret != NO_ERROR) {
669 return ret;
670 }
671
Mathias Agopian65ab4712010-07-14 17:59:35 -0700672 // check calling permissions
673 if (!settingsAllowed()) {
674 return PERMISSION_DENIED;
675 }
676
677 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700678 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700679 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700680 ret = dev->set_mic_mute(dev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700681 mHardwareStatus = AUDIO_HW_IDLE;
682 return ret;
683}
684
685bool AudioFlinger::getMicMute() const
686{
Eric Laurenta1884f92011-08-23 08:25:03 -0700687 status_t ret = initCheck();
688 if (ret != NO_ERROR) {
689 return false;
690 }
691
Dima Zavinfce7a472011-04-19 22:30:36 -0700692 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800693 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700694 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700695 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700696 dev->get_mic_mute(dev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700697 mHardwareStatus = AUDIO_HW_IDLE;
698 return state;
699}
700
701status_t AudioFlinger::setMasterMute(bool muted)
702{
John Grossmand8f178d2012-07-20 14:51:35 -0700703 status_t ret = initCheck();
704 if (ret != NO_ERROR) {
705 return ret;
706 }
707
Mathias Agopian65ab4712010-07-14 17:59:35 -0700708 // check calling permissions
709 if (!settingsAllowed()) {
710 return PERMISSION_DENIED;
711 }
712
John Grossmanee578c02012-07-23 17:05:46 -0700713 Mutex::Autolock _l(mLock);
714 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700715
John Grossmanee578c02012-07-23 17:05:46 -0700716 // Set master mute in the HALs which support it.
717 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
718 AutoMutex lock(mHardwareLock);
719 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700720
John Grossmanee578c02012-07-23 17:05:46 -0700721 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
722 if (dev->canSetMasterMute()) {
723 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700724 }
John Grossmanee578c02012-07-23 17:05:46 -0700725 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700726 }
727
John Grossmanee578c02012-07-23 17:05:46 -0700728 // Now set the master mute in each playback thread. Playback threads
729 // assigned to HALs which do not have master mute support will apply master
730 // mute during the mix operation. Threads with HALs which do support master
731 // mute will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800732 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700733 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700734
735 return NO_ERROR;
736}
737
738float AudioFlinger::masterVolume() const
739{
Glenn Kasten98067102011-12-13 11:47:54 -0800740 Mutex::Autolock _l(mLock);
741 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700742}
743
744bool AudioFlinger::masterMute() const
745{
Glenn Kasten98067102011-12-13 11:47:54 -0800746 Mutex::Autolock _l(mLock);
747 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700748}
749
John Grossman4ff14ba2012-02-08 16:37:41 -0800750float AudioFlinger::masterVolume_l() const
751{
John Grossman4ff14ba2012-02-08 16:37:41 -0800752 return mMasterVolume;
753}
754
John Grossmand8f178d2012-07-20 14:51:35 -0700755bool AudioFlinger::masterMute_l() const
756{
John Grossmanee578c02012-07-23 17:05:46 -0700757 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700758}
759
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800760status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
761 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700762{
763 // check calling permissions
764 if (!settingsAllowed()) {
765 return PERMISSION_DENIED;
766 }
767
Glenn Kasten263709e2012-01-06 08:40:01 -0800768 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000769 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700770 return BAD_VALUE;
771 }
772
773 AutoMutex lock(mLock);
774 PlaybackThread *thread = NULL;
775 if (output) {
776 thread = checkPlaybackThread_l(output);
777 if (thread == NULL) {
778 return BAD_VALUE;
779 }
780 }
781
782 mStreamTypes[stream].volume = value;
783
784 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800785 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700786 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700787 }
788 } else {
789 thread->setStreamVolume(stream, value);
790 }
791
792 return NO_ERROR;
793}
794
Glenn Kastenfff6d712012-01-12 16:38:12 -0800795status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796{
797 // check calling permissions
798 if (!settingsAllowed()) {
799 return PERMISSION_DENIED;
800 }
801
Glenn Kasten263709e2012-01-06 08:40:01 -0800802 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700803 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000804 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805 return BAD_VALUE;
806 }
807
Eric Laurent93575202011-01-18 18:39:02 -0800808 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700809 mStreamTypes[stream].mute = muted;
810 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700811 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700812
813 return NO_ERROR;
814}
815
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800816float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817{
Glenn Kasten263709e2012-01-06 08:40:01 -0800818 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700819 return 0.0f;
820 }
821
822 AutoMutex lock(mLock);
823 float volume;
824 if (output) {
825 PlaybackThread *thread = checkPlaybackThread_l(output);
826 if (thread == NULL) {
827 return 0.0f;
828 }
829 volume = thread->streamVolume(stream);
830 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800831 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700832 }
833
834 return volume;
835}
836
Glenn Kastenfff6d712012-01-12 16:38:12 -0800837bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838{
Glenn Kasten263709e2012-01-06 08:40:01 -0800839 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700840 return true;
841 }
842
Glenn Kasten6637baa2012-01-09 09:40:36 -0800843 AutoMutex lock(mLock);
844 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845}
846
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800847status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700848{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800849 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700850 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
851 // check calling permissions
852 if (!settingsAllowed()) {
853 return PERMISSION_DENIED;
854 }
855
Mathias Agopian65ab4712010-07-14 17:59:35 -0700856 // ioHandle == 0 means the parameters are global to the audio hardware interface
857 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700858 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700859 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800860 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700861 AutoMutex lock(mHardwareLock);
862 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
863 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
864 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
865 status_t result = dev->set_parameters(dev, keyValuePairs.string());
866 final_result = result ?: final_result;
867 }
868 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800869 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700870 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
871 AudioParameter param = AudioParameter(keyValuePairs);
872 String8 value;
873 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700874 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
875 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700876 for (size_t i = 0; i < mRecordThreads.size(); i++) {
877 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Glenn Kasten510a3d62012-07-16 14:24:34 -0700878 audio_devices_t device = thread->device() & AUDIO_DEVICE_IN_ALL;
879 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
880 // collect all of the thread's session IDs
881 KeyedVector<int, bool> ids = thread->sessionIds();
882 // suspend effects associated with those session IDs
883 for (size_t j = 0; j < ids.size(); ++j) {
884 int sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700885 thread->setEffectSuspended(FX_IID_AEC,
886 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700887 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700888 thread->setEffectSuspended(FX_IID_NS,
889 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700890 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700891 }
892 }
Eric Laurentbee53372011-08-29 12:42:48 -0700893 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700894 }
895 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700896 String8 screenState;
897 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
898 bool isOff = screenState == "off";
899 if (isOff != (gScreenState & 1)) {
900 gScreenState = ((gScreenState & ~1) + 2) | isOff;
901 }
902 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700903 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700904 }
905
906 // hold a strong ref on thread in case closeOutput() or closeInput() is called
907 // and the thread is exited once the lock is released
908 sp<ThreadBase> thread;
909 {
910 Mutex::Autolock _l(mLock);
911 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -0700912 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700913 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800914 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700915 // indicate output device change to all input threads for pre processing
916 AudioParameter param = AudioParameter(keyValuePairs);
917 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700918 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
919 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700920 for (size_t i = 0; i < mRecordThreads.size(); i++) {
921 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
922 }
923 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700924 }
925 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800926 if (thread != 0) {
927 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700928 }
929 return BAD_VALUE;
930}
931
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800932String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700933{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800934// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700935// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
936
Eric Laurenta4c5a552012-03-29 10:12:40 -0700937 Mutex::Autolock _l(mLock);
938
Mathias Agopian65ab4712010-07-14 17:59:35 -0700939 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700940 String8 out_s8;
941
Dima Zavin799a70e2011-04-18 16:57:27 -0700942 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800943 char *s;
944 {
945 AutoMutex lock(mHardwareLock);
946 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700947 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800948 s = dev->get_parameters(dev, keys.string());
949 mHardwareStatus = AUDIO_HW_IDLE;
950 }
John Grossmanef7740b2012-02-09 11:28:36 -0800951 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700952 free(s);
953 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700954 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700955 }
956
Mathias Agopian65ab4712010-07-14 17:59:35 -0700957 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
958 if (playbackThread != NULL) {
959 return playbackThread->getParameters(keys);
960 }
961 RecordThread *recordThread = checkRecordThread_l(ioHandle);
962 if (recordThread != NULL) {
963 return recordThread->getParameters(keys);
964 }
965 return String8("");
966}
967
Glenn Kastendd8104c2012-07-02 12:42:44 -0700968size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
969 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700970{
Eric Laurenta1884f92011-08-23 08:25:03 -0700971 status_t ret = initCheck();
972 if (ret != NO_ERROR) {
973 return 0;
974 }
975
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800976 AutoMutex lock(mHardwareLock);
977 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700978 struct audio_config config = {
979 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -0700980 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700981 format: format,
982 };
John Grossmanee578c02012-07-23 17:05:46 -0700983 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
984 size_t size = dev->get_input_buffer_size(dev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800985 mHardwareStatus = AUDIO_HW_IDLE;
986 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700987}
988
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800989unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700990{
Mathias Agopian65ab4712010-07-14 17:59:35 -0700991 Mutex::Autolock _l(mLock);
992
993 RecordThread *recordThread = checkRecordThread_l(ioHandle);
994 if (recordThread != NULL) {
995 return recordThread->getInputFramesLost();
996 }
997 return 0;
998}
999
1000status_t AudioFlinger::setVoiceVolume(float value)
1001{
Eric Laurenta1884f92011-08-23 08:25:03 -07001002 status_t ret = initCheck();
1003 if (ret != NO_ERROR) {
1004 return ret;
1005 }
1006
Mathias Agopian65ab4712010-07-14 17:59:35 -07001007 // check calling permissions
1008 if (!settingsAllowed()) {
1009 return PERMISSION_DENIED;
1010 }
1011
1012 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001013 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001014 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001015 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001016 mHardwareStatus = AUDIO_HW_IDLE;
1017
1018 return ret;
1019}
1020
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001021status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1022 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001023{
1024 status_t status;
1025
1026 Mutex::Autolock _l(mLock);
1027
1028 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1029 if (playbackThread != NULL) {
1030 return playbackThread->getRenderPosition(halFrames, dspFrames);
1031 }
1032
1033 return BAD_VALUE;
1034}
1035
1036void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1037{
1038
1039 Mutex::Autolock _l(mLock);
1040
Glenn Kastenbb001922012-02-03 11:10:26 -08001041 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001042 if (mNotificationClients.indexOfKey(pid) < 0) {
1043 sp<NotificationClient> notificationClient = new NotificationClient(this,
1044 client,
1045 pid);
Steve Block3856b092011-10-20 11:56:00 +01001046 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001047
1048 mNotificationClients.add(pid, notificationClient);
1049
1050 sp<IBinder> binder = client->asBinder();
1051 binder->linkToDeath(notificationClient);
1052
1053 // the config change is always sent from playback or record threads to avoid deadlock
1054 // with AudioSystem::gLock
1055 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1056 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1057 }
1058
1059 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1060 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1061 }
1062 }
1063}
1064
1065void AudioFlinger::removeNotificationClient(pid_t pid)
1066{
1067 Mutex::Autolock _l(mLock);
1068
Glenn Kastena3b09252012-01-20 09:19:01 -08001069 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001070
Steve Block3856b092011-10-20 11:56:00 +01001071 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001072 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001073 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001074 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001075 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001076 ALOGV(" pid %d @ %d", ref->mPid, i);
1077 if (ref->mPid == pid) {
1078 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001079 mAudioSessionRefs.removeAt(i);
1080 delete ref;
1081 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001082 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001083 } else {
1084 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001085 }
1086 }
1087 if (removed) {
1088 purgeStaleEffects_l();
1089 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001090}
1091
1092// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001093void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001094{
1095 size_t size = mNotificationClients.size();
1096 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001097 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1098 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001099 }
1100}
1101
1102// removeClient_l() must be called with AudioFlinger::mLock held
1103void AudioFlinger::removeClient_l(pid_t pid)
1104{
Steve Block3856b092011-10-20 11:56:00 +01001105 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001106 mClients.removeItem(pid);
1107}
1108
Eric Laurent717e1282012-06-29 16:36:52 -07001109// getEffectThread_l() must be called with AudioFlinger::mLock held
1110sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1111{
1112 sp<PlaybackThread> thread;
1113
1114 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1115 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1116 ALOG_ASSERT(thread == 0);
1117 thread = mPlaybackThreads.valueAt(i);
1118 }
1119 }
1120
1121 return thread;
1122}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001123
1124// ----------------------------------------------------------------------------
1125
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001126AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001127 audio_devices_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001128 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001129 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001130 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001131 // mChannelMask
1132 mChannelCount(0),
1133 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1134 mParamStatus(NO_ERROR),
Glenn Kasten5ad92f62012-07-19 10:02:15 -07001135 mStandby(false), mDevice(device), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001136 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001137{
1138}
1139
1140AudioFlinger::ThreadBase::~ThreadBase()
1141{
1142 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001143 // do not lock the mutex in destructor
1144 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001145 if (mPowerManager != 0) {
1146 sp<IBinder> binder = mPowerManager->asBinder();
1147 binder->unlinkToDeath(mDeathRecipient);
1148 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001149}
1150
1151void AudioFlinger::ThreadBase::exit()
1152{
Steve Block3856b092011-10-20 11:56:00 +01001153 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001154 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001155 // This lock prevents the following race in thread (uniprocessor for illustration):
1156 // if (!exitPending()) {
1157 // // context switch from here to exit()
1158 // // exit() calls requestExit(), what exitPending() observes
1159 // // exit() calls signal(), which is dropped since no waiters
1160 // // context switch back from exit() to here
1161 // mWaitWorkCV.wait(...);
1162 // // now thread is hung
1163 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001164 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001165 requestExit();
1166 mWaitWorkCV.signal();
1167 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001168 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1169 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001170 requestExitAndWait();
1171}
1172
Mathias Agopian65ab4712010-07-14 17:59:35 -07001173status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1174{
1175 status_t status;
1176
Steve Block3856b092011-10-20 11:56:00 +01001177 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001178 Mutex::Autolock _l(mLock);
1179
1180 mNewParameters.add(keyValuePairs);
1181 mWaitWorkCV.signal();
1182 // wait condition with timeout in case the thread loop has exited
1183 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001184 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001185 status = mParamStatus;
1186 mWaitWorkCV.signal();
1187 } else {
1188 status = TIMED_OUT;
1189 }
1190 return status;
1191}
1192
1193void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1194{
1195 Mutex::Autolock _l(mLock);
1196 sendConfigEvent_l(event, param);
1197}
1198
1199// sendConfigEvent_l() must be called with ThreadBase::mLock held
1200void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1201{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001202 ConfigEvent configEvent;
1203 configEvent.mEvent = event;
1204 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001205 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001206 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001207 mWaitWorkCV.signal();
1208}
1209
1210void AudioFlinger::ThreadBase::processConfigEvents()
1211{
1212 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001213 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001214 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001215 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001216 mConfigEvents.removeAt(0);
1217 // release mLock before locking AudioFlinger mLock: lock order is always
1218 // AudioFlinger then ThreadBase to avoid cross deadlock
1219 mLock.unlock();
1220 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001221 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001222 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001223 mLock.lock();
1224 }
1225 mLock.unlock();
1226}
1227
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001228void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001229{
1230 const size_t SIZE = 256;
1231 char buffer[SIZE];
1232 String8 result;
1233
1234 bool locked = tryLock(mLock);
1235 if (!locked) {
1236 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1237 write(fd, buffer, strlen(buffer));
1238 }
1239
Eric Laurent612bbb52012-03-14 15:03:26 -07001240 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1241 result.append(buffer);
1242 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1243 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001244 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1245 result.append(buffer);
1246 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1247 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001248 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1249 result.append(buffer);
1250 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001251 result.append(buffer);
1252 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1253 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001254 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1255 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001256 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1257 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001258 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001259 result.append(buffer);
1260
1261 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1262 result.append(buffer);
1263 result.append(" Index Command");
1264 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1265 snprintf(buffer, SIZE, "\n %02d ", i);
1266 result.append(buffer);
1267 result.append(mNewParameters[i]);
1268 }
1269
1270 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1271 result.append(buffer);
1272 snprintf(buffer, SIZE, " Index event param\n");
1273 result.append(buffer);
1274 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001275 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001276 result.append(buffer);
1277 }
1278 result.append("\n");
1279
1280 write(fd, result.string(), result.size());
1281
1282 if (locked) {
1283 mLock.unlock();
1284 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001285}
1286
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001287void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001288{
1289 const size_t SIZE = 256;
1290 char buffer[SIZE];
1291 String8 result;
1292
1293 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1294 write(fd, buffer, strlen(buffer));
1295
1296 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1297 sp<EffectChain> chain = mEffectChains[i];
1298 if (chain != 0) {
1299 chain->dump(fd, args);
1300 }
1301 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001302}
1303
Eric Laurentfeb0db62011-07-22 09:04:31 -07001304void AudioFlinger::ThreadBase::acquireWakeLock()
1305{
1306 Mutex::Autolock _l(mLock);
1307 acquireWakeLock_l();
1308}
1309
1310void AudioFlinger::ThreadBase::acquireWakeLock_l()
1311{
1312 if (mPowerManager == 0) {
1313 // use checkService() to avoid blocking if power service is not up yet
1314 sp<IBinder> binder =
1315 defaultServiceManager()->checkService(String16("power"));
1316 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001317 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001318 } else {
1319 mPowerManager = interface_cast<IPowerManager>(binder);
1320 binder->linkToDeath(mDeathRecipient);
1321 }
1322 }
1323 if (mPowerManager != 0) {
1324 sp<IBinder> binder = new BBinder();
1325 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1326 binder,
1327 String16(mName));
1328 if (status == NO_ERROR) {
1329 mWakeLockToken = binder;
1330 }
Steve Block3856b092011-10-20 11:56:00 +01001331 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001332 }
1333}
1334
1335void AudioFlinger::ThreadBase::releaseWakeLock()
1336{
1337 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001338 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001339}
1340
1341void AudioFlinger::ThreadBase::releaseWakeLock_l()
1342{
1343 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001344 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001345 if (mPowerManager != 0) {
1346 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1347 }
1348 mWakeLockToken.clear();
1349 }
1350}
1351
1352void AudioFlinger::ThreadBase::clearPowerManager()
1353{
1354 Mutex::Autolock _l(mLock);
1355 releaseWakeLock_l();
1356 mPowerManager.clear();
1357}
1358
1359void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1360{
1361 sp<ThreadBase> thread = mThread.promote();
1362 if (thread != 0) {
1363 thread->clearPowerManager();
1364 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001365 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001366}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001367
Eric Laurent59255e42011-07-27 19:49:51 -07001368void AudioFlinger::ThreadBase::setEffectSuspended(
1369 const effect_uuid_t *type, bool suspend, int sessionId)
1370{
1371 Mutex::Autolock _l(mLock);
1372 setEffectSuspended_l(type, suspend, sessionId);
1373}
1374
1375void AudioFlinger::ThreadBase::setEffectSuspended_l(
1376 const effect_uuid_t *type, bool suspend, int sessionId)
1377{
Glenn Kasten090f0192012-01-30 13:00:02 -08001378 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001379 if (chain != 0) {
1380 if (type != NULL) {
1381 chain->setEffectSuspended_l(type, suspend);
1382 } else {
1383 chain->setEffectSuspendedAll_l(suspend);
1384 }
1385 }
1386
1387 updateSuspendedSessions_l(type, suspend, sessionId);
1388}
1389
1390void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1391{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001392 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001393 if (index < 0) {
1394 return;
1395 }
1396
Glenn Kasten0a7af182012-07-09 16:09:19 -07001397 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1398 mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001399
1400 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001401 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001402 for (int j = 0; j < desc->mRefCount; j++) {
1403 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1404 chain->setEffectSuspendedAll_l(true);
1405 } else {
Steve Block3856b092011-10-20 11:56:00 +01001406 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001407 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001408 chain->setEffectSuspended_l(&desc->mType, true);
1409 }
1410 }
1411 }
1412}
1413
Eric Laurent59255e42011-07-27 19:49:51 -07001414void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1415 bool suspend,
1416 int sessionId)
1417{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001418 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001419
1420 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1421
1422 if (suspend) {
1423 if (index >= 0) {
Glenn Kasten0a7af182012-07-09 16:09:19 -07001424 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001425 } else {
1426 mSuspendedSessions.add(sessionId, sessionEffects);
1427 }
1428 } else {
1429 if (index < 0) {
1430 return;
1431 }
Glenn Kasten0a7af182012-07-09 16:09:19 -07001432 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001433 }
1434
1435
1436 int key = EffectChain::kKeyForSuspendAll;
1437 if (type != NULL) {
1438 key = type->timeLow;
1439 }
1440 index = sessionEffects.indexOfKey(key);
1441
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001442 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001443 if (suspend) {
1444 if (index >= 0) {
1445 desc = sessionEffects.valueAt(index);
1446 } else {
1447 desc = new SuspendedSessionDesc();
1448 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001449 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001450 }
1451 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001452 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001453 }
1454 desc->mRefCount++;
1455 } else {
1456 if (index < 0) {
1457 return;
1458 }
1459 desc = sessionEffects.valueAt(index);
1460 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001461 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001462 sessionEffects.removeItemsAt(index);
1463 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001464 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001465 sessionId);
1466 mSuspendedSessions.removeItem(sessionId);
1467 }
1468 }
1469 }
1470 if (!sessionEffects.isEmpty()) {
1471 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1472 }
1473}
1474
1475void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1476 bool enabled,
1477 int sessionId)
1478{
1479 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001480 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1481}
Eric Laurent59255e42011-07-27 19:49:51 -07001482
Eric Laurenta85a74a2011-10-19 11:44:54 -07001483void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1484 bool enabled,
1485 int sessionId)
1486{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001487 if (mType != RECORD) {
1488 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1489 // another session. This gives the priority to well behaved effect control panels
1490 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001491 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1492 // global effects
1493 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001494 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1495 }
1496 }
Eric Laurent59255e42011-07-27 19:49:51 -07001497
1498 sp<EffectChain> chain = getEffectChain_l(sessionId);
1499 if (chain != 0) {
1500 chain->checkSuspendOnEffectEnabled(effect, enabled);
1501 }
1502}
1503
Mathias Agopian65ab4712010-07-14 17:59:35 -07001504// ----------------------------------------------------------------------------
1505
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001506AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1507 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001508 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001509 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001510 type_t type)
1511 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001512 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001513 // mStreamTypes[] initialized in constructor body
1514 mOutput(output),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001515 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001516 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001517 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001518 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001519 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001520 // index 0 is reserved for normal mixer's submix
1521 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001522{
Glenn Kasten480b4682012-02-28 12:30:08 -08001523 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001524
John Grossmanee578c02012-07-23 17:05:46 -07001525 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1526 // it would be safer to explicitly pass initial masterVolume/masterMute as
1527 // parameter.
1528 //
1529 // If the HAL we are using has support for master volume or master mute,
1530 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1531 // and the mute set to false).
1532 mMasterVolume = audioFlinger->masterVolume_l();
1533 mMasterMute = audioFlinger->masterMute_l();
1534 if (mOutput && mOutput->audioHwDev) {
1535 if (mOutput->audioHwDev->canSetMasterVolume()) {
1536 mMasterVolume = 1.0;
1537 }
1538
1539 if (mOutput->audioHwDev->canSetMasterMute()) {
1540 mMasterMute = false;
1541 }
1542 }
1543
Mathias Agopian65ab4712010-07-14 17:59:35 -07001544 readOutputParameters();
1545
Glenn Kasten263709e2012-01-06 08:40:01 -08001546 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001547 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1548 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1549 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001550 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1551 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001552 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001553 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1554 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001555}
1556
1557AudioFlinger::PlaybackThread::~PlaybackThread()
1558{
1559 delete [] mMixBuffer;
1560}
1561
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001562void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001563{
1564 dumpInternals(fd, args);
1565 dumpTracks(fd, args);
1566 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001567}
1568
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001569void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001570{
1571 const size_t SIZE = 256;
1572 char buffer[SIZE];
1573 String8 result;
1574
Glenn Kasten58912562012-04-03 10:45:00 -07001575 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1576 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1577 const stream_type_t *st = &mStreamTypes[i];
1578 if (i > 0) {
1579 result.appendFormat(", ");
1580 }
1581 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1582 if (st->mute) {
1583 result.append("M");
1584 }
1585 }
1586 result.append("\n");
1587 write(fd, result.string(), result.length());
1588 result.clear();
1589
Mathias Agopian65ab4712010-07-14 17:59:35 -07001590 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1591 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001592 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001593 for (size_t i = 0; i < mTracks.size(); ++i) {
1594 sp<Track> track = mTracks[i];
1595 if (track != 0) {
1596 track->dump(buffer, SIZE);
1597 result.append(buffer);
1598 }
1599 }
1600
1601 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1602 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001603 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001604 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001605 sp<Track> track = mActiveTracks[i].promote();
1606 if (track != 0) {
1607 track->dump(buffer, SIZE);
1608 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609 }
1610 }
1611 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001612
1613 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1614 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1615 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1616 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001617}
1618
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001619void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001620{
1621 const size_t SIZE = 256;
1622 char buffer[SIZE];
1623 String8 result;
1624
1625 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1626 result.append(buffer);
1627 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1628 result.append(buffer);
1629 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1630 result.append(buffer);
1631 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1632 result.append(buffer);
1633 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1634 result.append(buffer);
1635 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1636 result.append(buffer);
1637 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1638 result.append(buffer);
1639 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001640 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001641
1642 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001643}
1644
1645// Thread virtuals
1646status_t AudioFlinger::PlaybackThread::readyToRun()
1647{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001648 status_t status = initCheck();
1649 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001650 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001651 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001652 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001653 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001654 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001655}
1656
1657void AudioFlinger::PlaybackThread::onFirstRef()
1658{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001659 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001660}
1661
1662// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001663sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001665 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001666 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001667 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001668 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001669 int frameCount,
1670 const sp<IMemory>& sharedBuffer,
1671 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001672 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001673 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001674 status_t *status)
1675{
1676 sp<Track> track;
1677 status_t lStatus;
1678
Glenn Kasten73d22752012-03-19 13:38:30 -07001679 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1680
1681 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001682 if (flags & IAudioFlinger::TRACK_FAST) {
1683 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001684 // not timed
1685 (!isTimed) &&
1686 // either of these use cases:
1687 (
1688 // use case 1: shared buffer with any frame count
1689 (
1690 (sharedBuffer != 0)
1691 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001692 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001693 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001694 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001695 ((frameCount == 0) ||
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001696 (frameCount >= (int) (mFrameCount * 2))) // * 2 is due to SRC jitter, see below
Glenn Kasten73d22752012-03-19 13:38:30 -07001697 )
1698 ) &&
1699 // PCM data
1700 audio_is_linear_pcm(format) &&
1701 // mono or stereo
1702 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1703 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001704#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001705 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001706 (sampleRate == mSampleRate) &&
1707#endif
1708 // normal mixer has an associated fast mixer
1709 hasFastMixer() &&
1710 // there are sufficient fast track slots available
1711 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001712 // FIXME test that MixerThread for this fast track has a capable output HAL
1713 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001714 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001715 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1716 if (frameCount == 0) {
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001717 frameCount = mFrameCount * 2; // FIXME * 2 is due to SRC jitter, should be computed
Glenn Kastene0fa4672012-04-24 14:35:14 -07001718 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001719 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001720 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001721 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001722 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07001723 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001724 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1725 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1726 audio_is_linear_pcm(format),
1727 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001728 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001729 // For compatibility with AudioTrack calculation, buffer depth is forced
1730 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1731 // This is probably too conservative, but legacy application code may depend on it.
1732 // If you change this calculation, also review the start threshold which is related.
1733 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1734 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1735 if (minBufCount < 2) {
1736 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001737 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001738 int minFrameCount = mNormalFrameCount * minBufCount;
1739 if (frameCount < minFrameCount) {
1740 frameCount = minFrameCount;
1741 }
1742 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001743 }
1744
Mathias Agopian65ab4712010-07-14 17:59:35 -07001745 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001746 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1747 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001748 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001749 "for output %p with format %d",
1750 sampleRate, format, channelMask, mOutput, mFormat);
1751 lStatus = BAD_VALUE;
1752 goto Exit;
1753 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001754 }
1755 } else {
1756 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1757 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001758 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759 lStatus = BAD_VALUE;
1760 goto Exit;
1761 }
1762 }
1763
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001764 lStatus = initCheck();
1765 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001766 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001767 goto Exit;
1768 }
1769
1770 { // scope for mLock
1771 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001772
1773 // all tracks in same audio session must share the same routing strategy otherwise
1774 // conflicts will happen when tracks are moved from one output to another by audio policy
1775 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001776 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001777 for (size_t i = 0; i < mTracks.size(); ++i) {
1778 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001779 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001780 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001781 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001782 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001783 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001784 lStatus = BAD_VALUE;
1785 goto Exit;
1786 }
1787 }
1788 }
1789
John Grossman4ff14ba2012-02-08 16:37:41 -08001790 if (!isTimed) {
1791 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001792 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001793 } else {
1794 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1795 channelMask, frameCount, sharedBuffer, sessionId);
1796 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001797 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001798 lStatus = NO_MEMORY;
1799 goto Exit;
1800 }
1801 mTracks.add(track);
1802
1803 sp<EffectChain> chain = getEffectChain_l(sessionId);
1804 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001805 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001806 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001807 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001808 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001809 }
1810 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001811
Glenn Kasten3acbd052012-02-28 10:39:56 -08001812 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1813 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1814 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1815 // so ask activity manager to do this on our behalf
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07001816 int err = requestPriority(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001817 if (err != 0) {
1818 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07001819 kPriorityAudioApp, callingPid, tid, err);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001820 }
1821 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001822
Mathias Agopian65ab4712010-07-14 17:59:35 -07001823 lStatus = NO_ERROR;
1824
1825Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001826 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001827 *status = lStatus;
1828 }
1829 return track;
1830}
1831
Eric Laurente737cda2012-05-22 18:55:44 -07001832uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1833{
1834 if (mFastMixer != NULL) {
1835 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1836 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1837 }
1838 return latency;
1839}
1840
1841uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1842{
1843 return latency;
1844}
1845
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846uint32_t AudioFlinger::PlaybackThread::latency() const
1847{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001848 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001849 return latency_l();
1850}
1851uint32_t AudioFlinger::PlaybackThread::latency_l() const
1852{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001853 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001854 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001855 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856 return 0;
1857 }
1858}
1859
Glenn Kasten6637baa2012-01-09 09:40:36 -08001860void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001862 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001863 // Don't apply master volume in SW if our HAL can do it for us.
1864 if (mOutput && mOutput->audioHwDev &&
1865 mOutput->audioHwDev->canSetMasterVolume()) {
1866 mMasterVolume = 1.0;
1867 } else {
1868 mMasterVolume = value;
1869 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001870}
1871
Glenn Kasten6637baa2012-01-09 09:40:36 -08001872void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001873{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001874 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001875 // Don't apply master mute in SW if our HAL can do it for us.
1876 if (mOutput && mOutput->audioHwDev &&
1877 mOutput->audioHwDev->canSetMasterMute()) {
1878 mMasterMute = false;
1879 } else {
1880 mMasterMute = muted;
1881 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001882}
1883
Glenn Kasten6637baa2012-01-09 09:40:36 -08001884void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001885{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001886 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001887 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001888}
1889
Glenn Kasten6637baa2012-01-09 09:40:36 -08001890void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001891{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001892 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001893 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001894}
1895
Glenn Kastenfff6d712012-01-12 16:38:12 -08001896float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001897{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001898 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001899 return mStreamTypes[stream].volume;
1900}
1901
Mathias Agopian65ab4712010-07-14 17:59:35 -07001902// addTrack_l() must be called with ThreadBase::mLock held
1903status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1904{
1905 status_t status = ALREADY_EXISTS;
1906
1907 // set retry count for buffer fill
1908 track->mRetryCount = kMaxTrackStartupRetries;
1909 if (mActiveTracks.indexOf(track) < 0) {
1910 // the track is newly added, make sure it fills up all its
1911 // buffers before playing. This is to ensure the client will
1912 // effectively get the latency it requested.
1913 track->mFillingUpStatus = Track::FS_FILLING;
1914 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001915 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916 mActiveTracks.add(track);
1917 if (track->mainBuffer() != mMixBuffer) {
1918 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1919 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001920 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001921 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001922 }
1923 }
1924
1925 status = NO_ERROR;
1926 }
1927
Steve Block3856b092011-10-20 11:56:00 +01001928 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001929 mWaitWorkCV.broadcast();
1930
1931 return status;
1932}
1933
1934// destroyTrack_l() must be called with ThreadBase::mLock held
1935void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1936{
1937 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001938 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001940 removeTrack_l(track);
1941 }
1942}
1943
1944void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1945{
Eric Laurent29864602012-05-08 18:57:51 -07001946 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001947 mTracks.remove(track);
1948 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001949 // redundant as track is about to be destroyed, for dumpsys only
1950 track->mName = -1;
1951 if (track->isFastTrack()) {
1952 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001953 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001954 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1955 mFastTrackAvailMask |= 1 << index;
1956 // redundant as track is about to be destroyed, for dumpsys only
1957 track->mFastIndex = -1;
1958 }
Eric Laurentb469b942011-05-09 12:09:06 -07001959 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1960 if (chain != 0) {
1961 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962 }
1963}
1964
1965String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1966{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001967 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001968 char *s;
1969
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001970 Mutex::Autolock _l(mLock);
1971 if (initCheck() != NO_ERROR) {
1972 return out_s8;
1973 }
1974
Dima Zavin799a70e2011-04-18 16:57:27 -07001975 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001976 out_s8 = String8(s);
1977 free(s);
1978 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001979}
1980
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001981// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001982void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1983 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001984 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001985
Steve Block3856b092011-10-20 11:56:00 +01001986 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001987
1988 switch (event) {
1989 case AudioSystem::OUTPUT_OPENED:
1990 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001991 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992 desc.samplingRate = mSampleRate;
1993 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07001994 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001995 desc.latency = latency();
1996 param2 = &desc;
1997 break;
1998
1999 case AudioSystem::STREAM_CONFIG_CHANGED:
2000 param2 = &param;
2001 case AudioSystem::OUTPUT_CLOSED:
2002 default:
2003 break;
2004 }
2005 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2006}
2007
2008void AudioFlinger::PlaybackThread::readOutputParameters()
2009{
Dima Zavin799a70e2011-04-18 16:57:27 -07002010 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002011 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2012 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07002013 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002014 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002015 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002016 if (mFrameCount & 15) {
2017 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2018 mFrameCount);
2019 }
2020
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002021 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002022 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002023 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002024 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002025 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2026 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2027 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2028 maxNormalFrameCount = maxNormalFrameCount & ~15;
2029 if (maxNormalFrameCount < minNormalFrameCount) {
2030 maxNormalFrameCount = minNormalFrameCount;
2031 }
2032 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2033 if (multiplier <= 1.0) {
2034 multiplier = 1.0;
2035 } else if (multiplier <= 2.0) {
2036 if (2 * mFrameCount <= maxNormalFrameCount) {
2037 multiplier = 2.0;
2038 } else {
2039 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2040 }
2041 } else {
2042 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2043 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2044 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2045 // FIXME this rounding up should not be done if no HAL SRC
2046 uint32_t truncMult = (uint32_t) multiplier;
2047 if ((truncMult & 1)) {
2048 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2049 ++truncMult;
2050 }
2051 }
2052 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002053 }
Glenn Kasten58912562012-04-03 10:45:00 -07002054 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002055 mNormalFrameCount = multiplier * mFrameCount;
2056 // round up to nearest 16 frames to satisfy AudioMixer
2057 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002058 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002059
Glenn Kastene9dd0172012-01-27 18:08:45 -08002060 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002061 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2062 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002063
Eric Laurentde070132010-07-13 04:45:46 -07002064 // force reconfiguration of effect chains and engines to take new buffer size and audio
2065 // parameters into account
2066 // Note that mLock is not held when readOutputParameters() is called from the constructor
2067 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2068 // matter.
2069 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2070 Vector< sp<EffectChain> > effectChains = mEffectChains;
2071 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002072 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002073 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002074}
2075
Eric Laurente737cda2012-05-22 18:55:44 -07002076
Mathias Agopian65ab4712010-07-14 17:59:35 -07002077status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2078{
Glenn Kastena0d68332012-01-27 16:47:15 -08002079 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002080 return BAD_VALUE;
2081 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002082 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002083 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002084 return INVALID_OPERATION;
2085 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002086 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002087
Dima Zavin799a70e2011-04-18 16:57:27 -07002088 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002089}
2090
Eric Laurent39e94f82010-07-28 01:32:47 -07002091uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002092{
2093 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002094 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002095 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002096 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002097 }
2098
2099 for (size_t i = 0; i < mTracks.size(); ++i) {
2100 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002101 if (sessionId == track->sessionId() &&
2102 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002103 result |= TRACK_SESSION;
2104 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105 }
2106 }
2107
Eric Laurent39e94f82010-07-28 01:32:47 -07002108 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002109}
2110
Eric Laurentde070132010-07-13 04:45:46 -07002111uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2112{
Dima Zavinfce7a472011-04-19 22:30:36 -07002113 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002114 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002115 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2116 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002117 }
2118 for (size_t i = 0; i < mTracks.size(); i++) {
2119 sp<Track> track = mTracks[i];
2120 if (sessionId == track->sessionId() &&
2121 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002122 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002123 }
2124 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002125 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002126}
2127
Mathias Agopian65ab4712010-07-14 17:59:35 -07002128
Glenn Kastenaed850d2012-01-26 09:46:34 -08002129AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002130{
2131 Mutex::Autolock _l(mLock);
2132 return mOutput;
2133}
2134
2135AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2136{
2137 Mutex::Autolock _l(mLock);
2138 AudioStreamOut *output = mOutput;
2139 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002140 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2141 // must push a NULL and wait for ack
2142 mOutputSink.clear();
2143 mPipeSink.clear();
2144 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002145 return output;
2146}
2147
2148// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002149audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002150{
2151 if (mOutput == NULL) {
2152 return NULL;
2153 }
2154 return &mOutput->stream->common;
2155}
2156
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002157uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002158{
Eric Laurentab9071b2012-06-04 13:45:29 -07002159 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002160}
2161
Eric Laurenta011e352012-03-29 15:51:43 -07002162status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2163{
2164 if (!isValidSyncEvent(event)) {
2165 return BAD_VALUE;
2166 }
2167
2168 Mutex::Autolock _l(mLock);
2169
2170 for (size_t i = 0; i < mTracks.size(); ++i) {
2171 sp<Track> track = mTracks[i];
2172 if (event->triggerSession() == track->sessionId()) {
2173 track->setSyncEvent(event);
2174 return NO_ERROR;
2175 }
2176 }
2177
2178 return NAME_NOT_FOUND;
2179}
2180
2181bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event)
2182{
2183 switch (event->type()) {
2184 case AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE:
2185 return true;
2186 default:
2187 break;
2188 }
2189 return false;
2190}
2191
Eric Laurent44a957f2012-05-15 15:26:05 -07002192void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2193{
2194 size_t count = tracksToRemove.size();
2195 if (CC_UNLIKELY(count)) {
2196 for (size_t i = 0 ; i < count ; i++) {
2197 const sp<Track>& track = tracksToRemove.itemAt(i);
2198 if ((track->sharedBuffer() != 0) &&
2199 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2200 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2201 }
2202 }
2203 }
2204
2205}
2206
Mathias Agopian65ab4712010-07-14 17:59:35 -07002207// ----------------------------------------------------------------------------
2208
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002209AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002210 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002211 : PlaybackThread(audioFlinger, output, id, device, type),
2212 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002213 // mFastMixer below
2214 mFastMixerFutex(0)
2215 // mOutputSink below
2216 // mPipeSink below
2217 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002218{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002219 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002220 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002221 "mFrameCount=%d, mNormalFrameCount=%d",
2222 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2223 mNormalFrameCount);
2224 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2225
Mathias Agopian65ab4712010-07-14 17:59:35 -07002226 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002227 if (mChannelCount != FCC_2) {
2228 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229 }
Glenn Kasten58912562012-04-03 10:45:00 -07002230
2231 // create an NBAIO sink for the HAL output stream, and negotiate
2232 mOutputSink = new AudioStreamOutSink(output->stream);
2233 size_t numCounterOffers = 0;
2234 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2235 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2236 ALOG_ASSERT(index == 0);
2237
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002238 // initialize fast mixer depending on configuration
2239 bool initFastMixer;
2240 switch (kUseFastMixer) {
2241 case FastMixer_Never:
2242 initFastMixer = false;
2243 break;
2244 case FastMixer_Always:
2245 initFastMixer = true;
2246 break;
2247 case FastMixer_Static:
2248 case FastMixer_Dynamic:
2249 initFastMixer = mFrameCount < mNormalFrameCount;
2250 break;
2251 }
2252 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002253
2254 // create a MonoPipe to connect our submix to FastMixer
2255 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002256 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2257 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2258 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2259 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002260 const NBAIO_Format offers[1] = {format};
2261 size_t numCounterOffers = 0;
2262 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2263 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002264 monoPipe->setAvgFrames((mScreenState & 1) ?
2265 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002266 mPipeSink = monoPipe;
2267
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002268#ifdef TEE_SINK_FRAMES
2269 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2270 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2271 numCounterOffers = 0;
2272 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2273 ALOG_ASSERT(index == 0);
2274 mTeeSink = teeSink;
2275 PipeReader *teeSource = new PipeReader(*teeSink);
2276 numCounterOffers = 0;
2277 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2278 ALOG_ASSERT(index == 0);
2279 mTeeSource = teeSource;
2280#endif
2281
Glenn Kasten58912562012-04-03 10:45:00 -07002282 // create fast mixer and configure it initially with just one fast track for our submix
2283 mFastMixer = new FastMixer();
2284 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002285#ifdef STATE_QUEUE_DUMP
2286 sq->setObserverDump(&mStateQueueObserverDump);
2287 sq->setMutatorDump(&mStateQueueMutatorDump);
2288#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002289 FastMixerState *state = sq->begin();
2290 FastTrack *fastTrack = &state->mFastTracks[0];
2291 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2292 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2293 fastTrack->mVolumeProvider = NULL;
2294 fastTrack->mGeneration++;
2295 state->mFastTracksGen++;
2296 state->mTrackMask = 1;
2297 // fast mixer will use the HAL output sink
2298 state->mOutputSink = mOutputSink.get();
2299 state->mOutputSinkGen++;
2300 state->mFrameCount = mFrameCount;
2301 state->mCommand = FastMixerState::COLD_IDLE;
2302 // already done in constructor initialization list
2303 //mFastMixerFutex = 0;
2304 state->mColdFutexAddr = &mFastMixerFutex;
2305 state->mColdGen++;
2306 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002307 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002308 sq->end();
2309 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2310
2311 // start the fast mixer
2312 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002313 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002314 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002315 if (err != 0) {
2316 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002317 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002318 }
Glenn Kasten58912562012-04-03 10:45:00 -07002319
Glenn Kastenc15d6652012-05-30 14:52:57 -07002320#ifdef AUDIO_WATCHDOG
2321 // create and start the watchdog
2322 mAudioWatchdog = new AudioWatchdog();
2323 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2324 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2325 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002326 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002327 if (err != 0) {
2328 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002329 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002330 }
2331#endif
2332
Glenn Kasten58912562012-04-03 10:45:00 -07002333 } else {
2334 mFastMixer = NULL;
2335 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002336
2337 switch (kUseFastMixer) {
2338 case FastMixer_Never:
2339 case FastMixer_Dynamic:
2340 mNormalSink = mOutputSink;
2341 break;
2342 case FastMixer_Always:
2343 mNormalSink = mPipeSink;
2344 break;
2345 case FastMixer_Static:
2346 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2347 break;
2348 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002349}
2350
2351AudioFlinger::MixerThread::~MixerThread()
2352{
Glenn Kasten58912562012-04-03 10:45:00 -07002353 if (mFastMixer != NULL) {
2354 FastMixerStateQueue *sq = mFastMixer->sq();
2355 FastMixerState *state = sq->begin();
2356 if (state->mCommand == FastMixerState::COLD_IDLE) {
2357 int32_t old = android_atomic_inc(&mFastMixerFutex);
2358 if (old == -1) {
2359 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2360 }
2361 }
2362 state->mCommand = FastMixerState::EXIT;
2363 sq->end();
2364 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2365 mFastMixer->join();
2366 // Though the fast mixer thread has exited, it's state queue is still valid.
2367 // We'll use that extract the final state which contains one remaining fast track
2368 // corresponding to our sub-mix.
2369 state = sq->begin();
2370 ALOG_ASSERT(state->mTrackMask == 1);
2371 FastTrack *fastTrack = &state->mFastTracks[0];
2372 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2373 delete fastTrack->mBufferProvider;
2374 sq->end(false /*didModify*/);
2375 delete mFastMixer;
Glenn Kastenc15d6652012-05-30 14:52:57 -07002376 if (mAudioWatchdog != 0) {
2377 mAudioWatchdog->requestExit();
2378 mAudioWatchdog->requestExitAndWait();
2379 mAudioWatchdog.clear();
2380 }
Glenn Kasten58912562012-04-03 10:45:00 -07002381 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002382 delete mAudioMixer;
2383}
2384
Glenn Kasten83efdd02012-02-24 07:21:32 -08002385class CpuStats {
2386public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002387 CpuStats();
2388 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002389#ifdef DEBUG_CPU_USAGE
2390private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002391 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2392 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2393
2394 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2395
2396 int mCpuNum; // thread's current CPU number
2397 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002398#endif
2399};
2400
Glenn Kasten190a46f2012-03-06 11:27:10 -08002401CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002402#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002403 : mCpuNum(-1), mCpukHz(-1)
2404#endif
2405{
2406}
2407
2408void CpuStats::sample(const String8 &title) {
2409#ifdef DEBUG_CPU_USAGE
2410 // get current thread's delta CPU time in wall clock ns
2411 double wcNs;
2412 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2413
2414 // record sample for wall clock statistics
2415 if (valid) {
2416 mWcStats.sample(wcNs);
2417 }
2418
2419 // get the current CPU number
2420 int cpuNum = sched_getcpu();
2421
2422 // get the current CPU frequency in kHz
2423 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2424
2425 // check if either CPU number or frequency changed
2426 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2427 mCpuNum = cpuNum;
2428 mCpukHz = cpukHz;
2429 // ignore sample for purposes of cycles
2430 valid = false;
2431 }
2432
2433 // if no change in CPU number or frequency, then record sample for cycle statistics
2434 if (valid && mCpukHz > 0) {
2435 double cycles = wcNs * cpukHz * 0.000001;
2436 mHzStats.sample(cycles);
2437 }
2438
2439 unsigned n = mWcStats.n();
2440 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002441 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002442 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002443 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2444 double perLoop = elapsed / (double) n;
2445 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002446 double perLoop1k = perLoop * 0.001;
2447 double mean = mWcStats.mean();
2448 double stddev = mWcStats.stddev();
2449 double minimum = mWcStats.minimum();
2450 double maximum = mWcStats.maximum();
2451 double meanCycles = mHzStats.mean();
2452 double stddevCycles = mHzStats.stddev();
2453 double minCycles = mHzStats.minimum();
2454 double maxCycles = mHzStats.maximum();
2455 mCpuUsage.resetElapsed();
2456 mWcStats.reset();
2457 mHzStats.reset();
2458 ALOGD("CPU usage for %s over past %.1f secs\n"
2459 " (%u mixer loops at %.1f mean ms per loop):\n"
2460 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2461 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2462 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2463 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002464 elapsed * .000000001, n, perLoop * .000001,
2465 mean * .001,
2466 stddev * .001,
2467 minimum * .001,
2468 maximum * .001,
2469 mean / perLoop100,
2470 stddev / perLoop100,
2471 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002472 maximum / perLoop100,
2473 meanCycles / perLoop1k,
2474 stddevCycles / perLoop1k,
2475 minCycles / perLoop1k,
2476 maxCycles / perLoop1k);
2477
Glenn Kasten83efdd02012-02-24 07:21:32 -08002478 }
2479 }
2480#endif
2481};
2482
Glenn Kasten37d825e2012-02-24 07:21:48 -08002483void AudioFlinger::PlaybackThread::checkSilentMode_l()
2484{
2485 if (!mMasterMute) {
2486 char value[PROPERTY_VALUE_MAX];
2487 if (property_get("ro.audio.silent", value, "0") > 0) {
2488 char *endptr;
2489 unsigned long ul = strtoul(value, &endptr, 0);
2490 if (*endptr == '\0' && ul != 0) {
2491 ALOGD("Silence is golden");
2492 // The setprop command will not allow a property to be changed after
2493 // the first time it is set, so we don't have to worry about un-muting.
2494 setMasterMute_l(true);
2495 }
2496 }
2497 }
2498}
2499
Glenn Kasten000f0e32012-03-01 17:10:56 -08002500bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002501{
2502 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002503
Glenn Kasten000f0e32012-03-01 17:10:56 -08002504 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002505
2506 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002507 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002508
Glenn Kasten000f0e32012-03-01 17:10:56 -08002509 // DUPLICATING
2510 // FIXME could this be made local to while loop?
2511 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002512
Glenn Kasten66fcab92012-02-24 14:59:21 -08002513 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002514 sleepTime = idleSleepTime;
2515
Glenn Kasten9f34a362012-03-20 16:46:41 -07002516 if (mType == MIXER) {
2517 sleepTimeShift = 0;
2518 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002519
Glenn Kasten83efdd02012-02-24 07:21:32 -08002520 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002521 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002522
Eric Laurentfeb0db62011-07-22 09:04:31 -07002523 acquireWakeLock();
2524
Mathias Agopian65ab4712010-07-14 17:59:35 -07002525 while (!exitPending())
2526 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002527 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002528
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002529 Vector< sp<EffectChain> > effectChains;
2530
Mathias Agopian65ab4712010-07-14 17:59:35 -07002531 processConfigEvents();
2532
Mathias Agopian65ab4712010-07-14 17:59:35 -07002533 { // scope for mLock
2534
2535 Mutex::Autolock _l(mLock);
2536
2537 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002538 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002539 }
2540
Glenn Kastenfa26a852012-03-06 11:28:04 -08002541 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002542
Mathias Agopian65ab4712010-07-14 17:59:35 -07002543 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002544 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002545 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002546 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002547
2548 threadLoop_standby();
2549
Mathias Agopian65ab4712010-07-14 17:59:35 -07002550 mStandby = true;
2551 mBytesWritten = 0;
2552 }
2553
Glenn Kasten3e074702012-02-28 18:40:35 -08002554 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002555 // we're about to wait, flush the binder command buffer
2556 IPCThreadState::self()->flushCommands();
2557
Glenn Kastenfa26a852012-03-06 11:28:04 -08002558 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002559
Mathias Agopian65ab4712010-07-14 17:59:35 -07002560 if (exitPending()) break;
2561
Eric Laurentfeb0db62011-07-22 09:04:31 -07002562 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002563 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002564 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002565 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002566 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002567 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002568
Eric Laurentda747442012-04-25 18:53:13 -07002569 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002570 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002571
Glenn Kasten37d825e2012-02-24 07:21:48 -08002572 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002573
Glenn Kasten000f0e32012-03-01 17:10:56 -08002574 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002575 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002576 if (mType == MIXER) {
2577 sleepTimeShift = 0;
2578 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002579
Mathias Agopian65ab4712010-07-14 17:59:35 -07002580 continue;
2581 }
2582 }
2583
Glenn Kasten81028042012-04-30 18:15:12 -07002584 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002585 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002586
2587 // prevent any changes in effect chain list and in each effect chain
2588 // during mixing and effect process as the audio buffers could be deleted
2589 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002590 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002591 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002592
Glenn Kastenfec279f2012-03-08 07:47:15 -08002593 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002594 threadLoop_mix();
2595 } else {
2596 threadLoop_sleepTime();
2597 }
2598
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002599 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002600 sleepTime = suspendSleepTimeUs();
2601 }
2602
2603 // only process effects if we're going to write
2604 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002605 for (size_t i = 0; i < effectChains.size(); i ++) {
2606 effectChains[i]->process_l();
2607 }
2608 }
2609
2610 // enable changes in effect chain
2611 unlockEffectChains(effectChains);
2612
2613 // sleepTime == 0 means we must write to audio hardware
2614 if (sleepTime == 0) {
2615
2616 threadLoop_write();
2617
2618if (mType == MIXER) {
2619 // write blocked detection
2620 nsecs_t now = systemTime();
2621 nsecs_t delta = now - mLastWriteTime;
2622 if (!mStandby && delta > maxPeriod) {
2623 mNumDelayedWrites++;
2624 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002625#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002626 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002627#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002628 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2629 ns2ms(delta), mNumDelayedWrites, this);
2630 lastWarning = now;
2631 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002632 }
2633}
2634
2635 mStandby = false;
2636 } else {
2637 usleep(sleepTime);
2638 }
2639
Glenn Kasten58912562012-04-03 10:45:00 -07002640 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002641 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002642 // same lock. This will also mutate and push a new fast mixer state.
2643 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002644 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002645
Glenn Kastenfa26a852012-03-06 11:28:04 -08002646 // FIXME I don't understand the need for this here;
2647 // it was in the original code but maybe the
2648 // assignment in saveOutputTracks() makes this unnecessary?
2649 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002650
2651 // Effect chains will be actually deleted here if they were removed from
2652 // mEffectChains list during mixing or effects processing
2653 effectChains.clear();
2654
2655 // FIXME Note that the above .clear() is no longer necessary since effectChains
2656 // is now local to this block, but will keep it for now (at least until merge done).
2657 }
2658
Glenn Kasten9f34a362012-03-20 16:46:41 -07002659 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2660 if (mType == MIXER || mType == DIRECT) {
2661 // put output stream into standby mode
2662 if (!mStandby) {
2663 mOutput->stream->common.standby(&mOutput->stream->common);
2664 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002665 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002666
2667 releaseWakeLock();
2668
2669 ALOGV("Thread %p type %d exiting", this, mType);
2670 return false;
2671}
2672
Glenn Kasten58912562012-04-03 10:45:00 -07002673void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2674{
Glenn Kasten58912562012-04-03 10:45:00 -07002675 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2676}
2677
2678void AudioFlinger::MixerThread::threadLoop_write()
2679{
2680 // FIXME we should only do one push per cycle; confirm this is true
2681 // Start the fast mixer if it's not already running
2682 if (mFastMixer != NULL) {
2683 FastMixerStateQueue *sq = mFastMixer->sq();
2684 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002685 if (state->mCommand != FastMixerState::MIX_WRITE &&
2686 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002687 if (state->mCommand == FastMixerState::COLD_IDLE) {
2688 int32_t old = android_atomic_inc(&mFastMixerFutex);
2689 if (old == -1) {
2690 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2691 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002692 if (mAudioWatchdog != 0) {
2693 mAudioWatchdog->resume();
2694 }
Glenn Kasten58912562012-04-03 10:45:00 -07002695 }
2696 state->mCommand = FastMixerState::MIX_WRITE;
2697 sq->end();
2698 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002699 if (kUseFastMixer == FastMixer_Dynamic) {
2700 mNormalSink = mPipeSink;
2701 }
Glenn Kasten58912562012-04-03 10:45:00 -07002702 } else {
2703 sq->end(false /*didModify*/);
2704 }
2705 }
2706 PlaybackThread::threadLoop_write();
2707}
2708
Glenn Kasten000f0e32012-03-01 17:10:56 -08002709// shared by MIXER and DIRECT, overridden by DUPLICATING
2710void AudioFlinger::PlaybackThread::threadLoop_write()
2711{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002712 // FIXME rewrite to reduce number of system calls
2713 mLastWriteTime = systemTime();
2714 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002715 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002716
Eric Laurent67c0a582012-05-01 19:31:12 -07002717 // If an NBAIO sink is present, use it to write the normal mixer's submix
2718 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002719#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002720 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002721#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002722 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002723#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002724 // update the setpoint when gScreenState changes
2725 uint32_t screenState = gScreenState;
2726 if (screenState != mScreenState) {
2727 mScreenState = screenState;
2728 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2729 if (pipe != NULL) {
2730 pipe->setAvgFrames((mScreenState & 1) ?
2731 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2732 }
2733 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002734 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002735#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002736 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002737#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002738 if (framesWritten > 0) {
2739 bytesWritten = framesWritten << mBitShift;
2740 } else {
2741 bytesWritten = framesWritten;
2742 }
2743 // otherwise use the HAL / AudioStreamOut directly
2744 } else {
2745 // Direct output thread.
2746 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002747 }
2748
Eric Laurent67c0a582012-05-01 19:31:12 -07002749 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002750 mNumWrites++;
2751 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002752}
2753
Glenn Kasten58912562012-04-03 10:45:00 -07002754void AudioFlinger::MixerThread::threadLoop_standby()
2755{
2756 // Idle the fast mixer if it's currently running
2757 if (mFastMixer != NULL) {
2758 FastMixerStateQueue *sq = mFastMixer->sq();
2759 FastMixerState *state = sq->begin();
2760 if (!(state->mCommand & FastMixerState::IDLE)) {
2761 state->mCommand = FastMixerState::COLD_IDLE;
2762 state->mColdFutexAddr = &mFastMixerFutex;
2763 state->mColdGen++;
2764 mFastMixerFutex = 0;
2765 sq->end();
2766 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2767 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002768 if (kUseFastMixer == FastMixer_Dynamic) {
2769 mNormalSink = mOutputSink;
2770 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002771 if (mAudioWatchdog != 0) {
2772 mAudioWatchdog->pause();
2773 }
Glenn Kasten58912562012-04-03 10:45:00 -07002774 } else {
2775 sq->end(false /*didModify*/);
2776 }
2777 }
2778 PlaybackThread::threadLoop_standby();
2779}
2780
Glenn Kasten000f0e32012-03-01 17:10:56 -08002781// shared by MIXER and DIRECT, overridden by DUPLICATING
2782void AudioFlinger::PlaybackThread::threadLoop_standby()
2783{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002784 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002785 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002786}
2787
2788void AudioFlinger::MixerThread::threadLoop_mix()
2789{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002790 // obtain the presentation timestamp of the next output buffer
2791 int64_t pts;
2792 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002793
Glenn Kasten952eeb22012-03-06 11:30:57 -08002794 if (NULL != mOutput->stream->get_next_write_timestamp) {
2795 status = mOutput->stream->get_next_write_timestamp(
2796 mOutput->stream, &pts);
2797 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002798
Glenn Kasten952eeb22012-03-06 11:30:57 -08002799 if (status != NO_ERROR) {
2800 pts = AudioBufferProvider::kInvalidPTS;
2801 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002802
Glenn Kasten952eeb22012-03-06 11:30:57 -08002803 // mix buffers...
2804 mAudioMixer->process(pts);
2805 // increase sleep time progressively when application underrun condition clears.
2806 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2807 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2808 // such that we would underrun the audio HAL.
2809 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2810 sleepTimeShift--;
2811 }
2812 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002813 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002814 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002815}
2816
2817void AudioFlinger::MixerThread::threadLoop_sleepTime()
2818{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002819 // If no tracks are ready, sleep once for the duration of an output
2820 // buffer size, then write 0s to the output
2821 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002822 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002823 sleepTime = activeSleepTime >> sleepTimeShift;
2824 if (sleepTime < kMinThreadSleepTimeUs) {
2825 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002826 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002827 // reduce sleep time in case of consecutive application underruns to avoid
2828 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2829 // duration we would end up writing less data than needed by the audio HAL if
2830 // the condition persists.
2831 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2832 sleepTimeShift++;
2833 }
2834 } else {
2835 sleepTime = idleSleepTime;
2836 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002837 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002838 memset (mMixBuffer, 0, mixBufferSize);
2839 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002840 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002841 }
2842 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002843}
2844
2845// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002846AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002847 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002848{
2849
Glenn Kasten29c23c32012-01-26 13:37:52 -08002850 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002851 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002852 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002853 size_t mixedTracks = 0;
2854 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002855 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002856 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002857 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002858
2859 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002860 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002861
Eric Laurent571d49c2010-08-11 05:20:11 -07002862 if (masterMute) {
2863 masterVolume = 0;
2864 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002865 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002866 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002867 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002868 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002869 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002870 masterVolume = (float)((v + (1 << 23)) >> 24);
2871 chain.clear();
2872 }
2873
Glenn Kasten288ed212012-04-25 17:52:27 -07002874 // prepare a new state to push
2875 FastMixerStateQueue *sq = NULL;
2876 FastMixerState *state = NULL;
2877 bool didModify = false;
2878 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2879 if (mFastMixer != NULL) {
2880 sq = mFastMixer->sq();
2881 state = sq->begin();
2882 }
2883
Mathias Agopian65ab4712010-07-14 17:59:35 -07002884 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002885 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002886 if (t == 0) continue;
2887
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002888 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002889 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002890
Glenn Kasten288ed212012-04-25 17:52:27 -07002891 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002892 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002893
2894 // It's theoretically possible (though unlikely) for a fast track to be created
2895 // and then removed within the same normal mix cycle. This is not a problem, as
2896 // the track never becomes active so it's fast mixer slot is never touched.
2897 // The converse, of removing an (active) track and then creating a new track
2898 // at the identical fast mixer slot within the same normal mix cycle,
2899 // is impossible because the slot isn't marked available until the end of each cycle.
2900 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002901 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2902 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002903 FastTrack *fastTrack = &state->mFastTracks[j];
2904
2905 // Determine whether the track is currently in underrun condition,
2906 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002907 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2908 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002909 uint32_t recentFull = (underruns.mBitFields.mFull -
2910 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2911 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2912 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2913 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2914 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2915 uint32_t recentUnderruns = recentPartial + recentEmpty;
2916 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002917 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002918 // or stopped which can occur when flush() is called while active
2919 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002920 track->mUnderrunCount += recentUnderruns;
2921 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002922
Glenn Kastend08f48c2012-05-01 18:14:02 -07002923 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002924 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002925 bool isActive = true;
2926 switch (track->mState) {
2927 case TrackBase::STOPPING_1:
2928 // track stays active in STOPPING_1 state until first underrun
2929 if (recentUnderruns > 0) {
2930 track->mState = TrackBase::STOPPING_2;
2931 }
2932 break;
2933 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002934 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002935 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002936 break;
2937 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002938 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002939 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002940 break;
2941 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002942 if (recentFull > 0 || recentPartial > 0) {
2943 // track has provided at least some frames recently: reset retry count
2944 track->mRetryCount = kMaxTrackRetries;
2945 }
2946 if (recentUnderruns == 0) {
2947 // no recent underruns: stay active
2948 break;
2949 }
2950 // there has recently been an underrun of some kind
2951 if (track->sharedBuffer() == 0) {
2952 // were any of the recent underruns "empty" (no frames available)?
2953 if (recentEmpty == 0) {
2954 // no, then ignore the partial underruns as they are allowed indefinitely
2955 break;
2956 }
2957 // there has recently been an "empty" underrun: decrement the retry counter
2958 if (--(track->mRetryCount) > 0) {
2959 break;
2960 }
2961 // indicate to client process that the track was disabled because of underrun;
2962 // it will then automatically call start() when data is available
2963 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2964 // remove from active list, but state remains ACTIVE [confusing but true]
2965 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002966 break;
2967 }
2968 // fall through
2969 case TrackBase::STOPPING_2:
2970 case TrackBase::PAUSED:
2971 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002972 case TrackBase::STOPPED:
2973 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002974 // Check for presentation complete if track is inactive
2975 // We have consumed all the buffers of this track.
2976 // This would be incomplete if we auto-paused on underrun
2977 {
2978 size_t audioHALFrames =
2979 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2980 size_t framesWritten =
2981 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2982 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2983 // track stays in active list until presentation is complete
2984 break;
2985 }
2986 }
2987 if (track->isStopping_2()) {
2988 track->mState = TrackBase::STOPPED;
2989 }
2990 if (track->isStopped()) {
2991 // Can't reset directly, as fast mixer is still polling this track
2992 // track->reset();
2993 // So instead mark this track as needing to be reset after push with ack
2994 resetMask |= 1 << i;
2995 }
2996 isActive = false;
2997 break;
2998 case TrackBase::IDLE:
2999 default:
3000 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003001 }
3002
3003 if (isActive) {
3004 // was it previously inactive?
3005 if (!(state->mTrackMask & (1 << j))) {
3006 ExtendedAudioBufferProvider *eabp = track;
3007 VolumeProvider *vp = track;
3008 fastTrack->mBufferProvider = eabp;
3009 fastTrack->mVolumeProvider = vp;
3010 fastTrack->mSampleRate = track->mSampleRate;
3011 fastTrack->mChannelMask = track->mChannelMask;
3012 fastTrack->mGeneration++;
3013 state->mTrackMask |= 1 << j;
3014 didModify = true;
3015 // no acknowledgement required for newly active tracks
3016 }
3017 // cache the combined master volume and stream type volume for fast mixer; this
3018 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3019 track->mCachedVolume = track->isMuted() ?
3020 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3021 ++fastTracks;
3022 } else {
3023 // was it previously active?
3024 if (state->mTrackMask & (1 << j)) {
3025 fastTrack->mBufferProvider = NULL;
3026 fastTrack->mGeneration++;
3027 state->mTrackMask &= ~(1 << j);
3028 didModify = true;
3029 // If any fast tracks were removed, we must wait for acknowledgement
3030 // because we're about to decrement the last sp<> on those tracks.
3031 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003032 } else {
3033 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003034 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003035 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003036 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003037 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003038 }
3039 continue;
3040 }
3041
3042 { // local variable scope to avoid goto warning
3043
Mathias Agopian65ab4712010-07-14 17:59:35 -07003044 audio_track_cblk_t* cblk = track->cblk();
3045
3046 // The first time a track is added we wait
3047 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003048 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003049 // make sure that we have enough frames to mix one full buffer.
3050 // enforce this condition only once to enable draining the buffer in case the client
3051 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003052 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003053 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003054 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003055 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003056 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003057 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003058 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003059 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003060 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003061 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003062 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003063 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003064 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3065 // the minimum track buffer size is normally twice the number of frames necessary
3066 // to fill one buffer and the resampler should not leave more than one buffer worth
3067 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003068 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003069 }
3070 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003071 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003072 !track->isPaused() && !track->isTerminated())
3073 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003074 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003075
3076 mixedTracks++;
3077
3078 // track->mainBuffer() != mMixBuffer means there is an effect chain
3079 // connected to the track
3080 chain.clear();
3081 if (track->mainBuffer() != mMixBuffer) {
3082 chain = getEffectChain_l(track->sessionId());
3083 // Delegate volume control to effect in track effect chain if needed
3084 if (chain != 0) {
3085 tracksWithEffect++;
3086 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003087 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003088 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003089 }
3090 }
3091
3092
3093 int param = AudioMixer::VOLUME;
3094 if (track->mFillingUpStatus == Track::FS_FILLED) {
3095 // no ramp for the first volume setting
3096 track->mFillingUpStatus = Track::FS_ACTIVE;
3097 if (track->mState == TrackBase::RESUMING) {
3098 track->mState = TrackBase::ACTIVE;
3099 param = AudioMixer::RAMP_VOLUME;
3100 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003101 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003102 } else if (cblk->server != 0) {
3103 // If the track is stopped before the first frame was mixed,
3104 // do not apply ramp
3105 param = AudioMixer::RAMP_VOLUME;
3106 }
3107
3108 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003109 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003110 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003111 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003112 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003113 if (track->isPausing()) {
3114 track->setPaused();
3115 }
3116 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003117
Mathias Agopian65ab4712010-07-14 17:59:35 -07003118 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003119 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003120 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003121 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003122 vl = vlr & 0xFFFF;
3123 vr = vlr >> 16;
3124 // track volumes come from shared memory, so can't be trusted and must be clamped
3125 if (vl > MAX_GAIN_INT) {
3126 ALOGV("Track left volume out of range: %04X", vl);
3127 vl = MAX_GAIN_INT;
3128 }
3129 if (vr > MAX_GAIN_INT) {
3130 ALOGV("Track right volume out of range: %04X", vr);
3131 vr = MAX_GAIN_INT;
3132 }
3133 // now apply the master volume and stream type volume
3134 vl = (uint32_t)(v * vl) << 12;
3135 vr = (uint32_t)(v * vr) << 12;
3136 // assuming master volume and stream type volume each go up to 1.0,
3137 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003138
Glenn Kasten05632a52012-01-03 14:22:33 -08003139 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3140 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003141 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003142 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003143 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003144 }
3145 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003146 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003147 // Delegate volume control to effect in track effect chain if needed
3148 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3149 // Do not ramp volume if volume is controlled by effect
3150 param = AudioMixer::VOLUME;
3151 track->mHasVolumeController = true;
3152 } else {
3153 // force no volume ramp when volume controller was just disabled or removed
3154 // from effect chain to avoid volume spike
3155 if (track->mHasVolumeController) {
3156 param = AudioMixer::VOLUME;
3157 }
3158 track->mHasVolumeController = false;
3159 }
3160
3161 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003162 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003163 vl = (vl + (1 << 11)) >> 12;
3164 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3165 vr = (vr + (1 << 11)) >> 12;
3166 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003167
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003168 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 -07003169
Mathias Agopian65ab4712010-07-14 17:59:35 -07003170 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003171 mAudioMixer->setBufferProvider(name, track);
3172 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003173
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003174 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3175 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3176 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003177 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003178 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003179 AudioMixer::TRACK,
3180 AudioMixer::FORMAT, (void *)track->format());
3181 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003182 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003183 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003184 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003185 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003186 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003187 AudioMixer::RESAMPLE,
3188 AudioMixer::SAMPLE_RATE,
3189 (void *)(cblk->sampleRate));
3190 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003191 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003192 AudioMixer::TRACK,
3193 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3194 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003195 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003196 AudioMixer::TRACK,
3197 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3198
3199 // reset retry count
3200 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003201
Eric Laurent27741442012-01-17 19:20:12 -08003202 // If one track is ready, set the mixer ready if:
3203 // - the mixer was not ready during previous round OR
3204 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003205 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003206 mixerStatus != MIXER_TRACKS_ENABLED) {
3207 mixerStatus = MIXER_TRACKS_READY;
3208 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003209 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003210 // clear effect chain input buffer if an active track underruns to avoid sending
3211 // previous audio buffer again to effects
3212 chain = getEffectChain_l(track->sessionId());
3213 if (chain != 0) {
3214 chain->clearInputBuffer();
3215 }
3216
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003217 //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 -07003218 if ((track->sharedBuffer() != 0) ||
Eric Laurent83faee02012-04-27 18:24:29 -07003219 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220 // We have consumed all the buffers of this track.
3221 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003222 // TODO: use actual buffer filling status instead of latency when available from
3223 // audio HAL
3224 size_t audioHALFrames =
3225 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3226 size_t framesWritten =
3227 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3228 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003229 if (track->isStopped()) {
3230 track->reset();
3231 }
Eric Laurenta011e352012-03-29 15:51:43 -07003232 tracksToRemove->add(track);
3233 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003234 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003235 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003236 // No buffers for this track. Give it a few chances to
3237 // fill a buffer, then remove it from active list.
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003238 if (--(track->mRetryCount) <= 0 || track->isTerminated()) {
3239 ALOGV_IF(track->mRetryCount <= 0, "BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003240 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003241 // indicate to client process that the track was disabled because of underrun;
3242 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003243 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003244 // If one track is not ready, mark the mixer also not ready if:
3245 // - the mixer was ready during previous round OR
3246 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003247 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003248 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003249 mixerStatus = MIXER_TRACKS_ENABLED;
3250 }
3251 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003252 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003253 }
Glenn Kasten58912562012-04-03 10:45:00 -07003254
3255 } // local variable scope to avoid goto warning
3256track_is_ready: ;
3257
Mathias Agopian65ab4712010-07-14 17:59:35 -07003258 }
3259
Glenn Kasten288ed212012-04-25 17:52:27 -07003260 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003261 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003262 if (didModify) {
3263 state->mFastTracksGen++;
3264 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3265 if (kUseFastMixer == FastMixer_Dynamic &&
3266 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3267 state->mCommand = FastMixerState::COLD_IDLE;
3268 state->mColdFutexAddr = &mFastMixerFutex;
3269 state->mColdGen++;
3270 mFastMixerFutex = 0;
3271 if (kUseFastMixer == FastMixer_Dynamic) {
3272 mNormalSink = mOutputSink;
3273 }
3274 // If we go into cold idle, need to wait for acknowledgement
3275 // so that fast mixer stops doing I/O.
3276 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003277 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003278 }
3279 sq->end();
3280 }
3281 if (sq != NULL) {
3282 sq->end(didModify);
3283 sq->push(block);
3284 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07003285 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3286 mAudioWatchdog->pause();
3287 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003288
3289 // Now perform the deferred reset on fast tracks that have stopped
3290 while (resetMask != 0) {
3291 size_t i = __builtin_ctz(resetMask);
3292 ALOG_ASSERT(i < count);
3293 resetMask &= ~(1 << i);
3294 sp<Track> t = mActiveTracks[i].promote();
3295 if (t == 0) continue;
3296 Track* track = t.get();
3297 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3298 track->reset();
3299 }
Glenn Kasten58912562012-04-03 10:45:00 -07003300
Mathias Agopian65ab4712010-07-14 17:59:35 -07003301 // remove all the tracks that need to be...
3302 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003303 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003304 for (size_t i=0 ; i<count ; i++) {
3305 const sp<Track>& track = tracksToRemove->itemAt(i);
3306 mActiveTracks.remove(track);
3307 if (track->mainBuffer() != mMixBuffer) {
3308 chain = getEffectChain_l(track->sessionId());
3309 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003310 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003311 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003312 }
3313 }
3314 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003315 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003316 }
3317 }
3318 }
3319
3320 // mix buffer must be cleared if all tracks are connected to an
3321 // effect chain as in this case the mixer will not write to
3322 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003323 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3324 // FIXME as a performance optimization, should remember previous zero status
3325 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003326 }
3327
Glenn Kasten58912562012-04-03 10:45:00 -07003328 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003329 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003330 if (fastTracks > 0) {
3331 mixerStatus = MIXER_TRACKS_READY;
3332 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003333 return mixerStatus;
3334}
3335
Glenn Kasten66fcab92012-02-24 14:59:21 -08003336/*
3337The derived values that are cached:
3338 - mixBufferSize from frame count * frame size
3339 - activeSleepTime from activeSleepTimeUs()
3340 - idleSleepTime from idleSleepTimeUs()
3341 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3342 - maxPeriod from frame count and sample rate (MIXER only)
3343
3344The parameters that affect these derived values are:
3345 - frame count
3346 - frame size
3347 - sample rate
3348 - device type: A2DP or not
3349 - device latency
3350 - format: PCM or not
3351 - active sleep time
3352 - idle sleep time
3353*/
3354
3355void AudioFlinger::PlaybackThread::cacheParameters_l()
3356{
Glenn Kasten58912562012-04-03 10:45:00 -07003357 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003358 activeSleepTime = activeSleepTimeUs();
3359 idleSleepTime = idleSleepTimeUs();
3360}
3361
Eric Laurent22167852012-06-20 12:26:32 -07003362void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003363{
Steve Block3856b092011-10-20 11:56:00 +01003364 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003365 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003366 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003367
Mathias Agopian65ab4712010-07-14 17:59:35 -07003368 size_t size = mTracks.size();
3369 for (size_t i = 0; i < size; i++) {
3370 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003371 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003372 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003373 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003374 }
3375 }
3376}
3377
Mathias Agopian65ab4712010-07-14 17:59:35 -07003378// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003379int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003380{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003381 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003382}
3383
3384// deleteTrackName_l() must be called with ThreadBase::mLock held
3385void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3386{
Steve Block3856b092011-10-20 11:56:00 +01003387 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003388 mAudioMixer->deleteTrackName(name);
3389}
3390
3391// checkForNewParameters_l() must be called with ThreadBase::mLock held
3392bool AudioFlinger::MixerThread::checkForNewParameters_l()
3393{
Glenn Kasten58912562012-04-03 10:45:00 -07003394 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3395 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003396 bool reconfig = false;
3397
3398 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003399
3400 if (mFastMixer != NULL) {
3401 FastMixerStateQueue *sq = mFastMixer->sq();
3402 FastMixerState *state = sq->begin();
3403 if (!(state->mCommand & FastMixerState::IDLE)) {
3404 previousCommand = state->mCommand;
3405 state->mCommand = FastMixerState::HOT_IDLE;
3406 sq->end();
3407 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3408 } else {
3409 sq->end(false /*didModify*/);
3410 }
3411 }
3412
Mathias Agopian65ab4712010-07-14 17:59:35 -07003413 status_t status = NO_ERROR;
3414 String8 keyValuePair = mNewParameters[0];
3415 AudioParameter param = AudioParameter(keyValuePair);
3416 int value;
3417
3418 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3419 reconfig = true;
3420 }
3421 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003422 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003423 status = BAD_VALUE;
3424 } else {
3425 reconfig = true;
3426 }
3427 }
3428 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003429 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003430 status = BAD_VALUE;
3431 } else {
3432 reconfig = true;
3433 }
3434 }
3435 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3436 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003437 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003438 // if frame count is changed after track creation
3439 if (!mTracks.isEmpty()) {
3440 status = INVALID_OPERATION;
3441 } else {
3442 reconfig = true;
3443 }
3444 }
3445 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003446#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003447 // when changing the audio output device, call addBatteryData to notify
3448 // the change
Glenn Kasten5ad92f62012-07-19 10:02:15 -07003449 if (mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003450 uint32_t params = 0;
3451 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003452 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003453 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3454 }
3455
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003456 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003457 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003458 // check if any other device (except speaker) is on
3459 if (value & deviceWithoutSpeaker ) {
3460 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3461 }
3462
3463 if (params != 0) {
3464 addBatteryData(params);
3465 }
3466 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003467#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003468
Mathias Agopian65ab4712010-07-14 17:59:35 -07003469 // forward device change to effects that have requested to be
3470 // aware of attached audio device.
Glenn Kasten5ad92f62012-07-19 10:02:15 -07003471 mDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003472 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003473 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003474 }
3475 }
3476
3477 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003478 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003479 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003480 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003481 mOutput->stream->common.standby(&mOutput->stream->common);
3482 mStandby = true;
3483 mBytesWritten = 0;
3484 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003485 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003486 }
3487 if (status == NO_ERROR && reconfig) {
3488 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003489 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3490 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003491 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003492 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493 for (size_t i = 0; i < mTracks.size() ; i++) {
Glenn Kasten254af182012-07-03 14:59:05 -07003494 int name = getTrackName_l(mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003495 if (name < 0) break;
3496 mTracks[i]->mName = name;
3497 // limit track sample rate to 2 x new output sample rate
3498 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3499 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3500 }
3501 }
3502 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3503 }
3504 }
3505
3506 mNewParameters.removeAt(0);
3507
3508 mParamStatus = status;
3509 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003510 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3511 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003512 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003513 }
Glenn Kasten58912562012-04-03 10:45:00 -07003514
3515 if (!(previousCommand & FastMixerState::IDLE)) {
3516 ALOG_ASSERT(mFastMixer != NULL);
3517 FastMixerStateQueue *sq = mFastMixer->sq();
3518 FastMixerState *state = sq->begin();
3519 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3520 state->mCommand = previousCommand;
3521 sq->end();
3522 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3523 }
3524
Mathias Agopian65ab4712010-07-14 17:59:35 -07003525 return reconfig;
3526}
3527
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07003528void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003529{
3530 const size_t SIZE = 256;
3531 char buffer[SIZE];
3532 String8 result;
3533
3534 PlaybackThread::dumpInternals(fd, args);
3535
3536 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3537 result.append(buffer);
3538 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003539
3540 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3541 FastMixerDumpState copy = mFastMixerDumpState;
3542 copy.dump(fd);
3543
Glenn Kasten39993082012-05-31 13:40:27 -07003544#ifdef STATE_QUEUE_DUMP
3545 // Similar for state queue
3546 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3547 observerCopy.dump(fd);
3548 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3549 mutatorCopy.dump(fd);
3550#endif
3551
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003552 // Write the tee output to a .wav file
3553 NBAIO_Source *teeSource = mTeeSource.get();
3554 if (teeSource != NULL) {
3555 char teePath[64];
3556 struct timeval tv;
3557 gettimeofday(&tv, NULL);
3558 struct tm tm;
3559 localtime_r(&tv.tv_sec, &tm);
3560 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3561 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3562 if (teeFd >= 0) {
3563 char wavHeader[44];
3564 memcpy(wavHeader,
3565 "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",
3566 sizeof(wavHeader));
3567 NBAIO_Format format = teeSource->format();
3568 unsigned channelCount = Format_channelCount(format);
3569 ALOG_ASSERT(channelCount <= FCC_2);
3570 unsigned sampleRate = Format_sampleRate(format);
3571 wavHeader[22] = channelCount; // number of channels
3572 wavHeader[24] = sampleRate; // sample rate
3573 wavHeader[25] = sampleRate >> 8;
3574 wavHeader[32] = channelCount * 2; // block alignment
3575 write(teeFd, wavHeader, sizeof(wavHeader));
3576 size_t total = 0;
3577 bool firstRead = true;
3578 for (;;) {
3579#define TEE_SINK_READ 1024
3580 short buffer[TEE_SINK_READ * FCC_2];
3581 size_t count = TEE_SINK_READ;
3582 ssize_t actual = teeSource->read(buffer, count);
3583 bool wasFirstRead = firstRead;
3584 firstRead = false;
3585 if (actual <= 0) {
3586 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3587 continue;
3588 }
3589 break;
3590 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003591 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003592 write(teeFd, buffer, actual * channelCount * sizeof(short));
3593 total += actual;
3594 }
3595 lseek(teeFd, (off_t) 4, SEEK_SET);
3596 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3597 write(teeFd, &temp, sizeof(temp));
3598 lseek(teeFd, (off_t) 40, SEEK_SET);
3599 temp = total * channelCount * sizeof(short);
3600 write(teeFd, &temp, sizeof(temp));
3601 close(teeFd);
3602 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3603 } else {
3604 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3605 }
3606 }
3607
Glenn Kastenc15d6652012-05-30 14:52:57 -07003608 if (mAudioWatchdog != 0) {
3609 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3610 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3611 wdCopy.dump(fd);
3612 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003613}
3614
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003615uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003616{
Glenn Kasten58912562012-04-03 10:45:00 -07003617 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618}
3619
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003620uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003621{
Glenn Kasten58912562012-04-03 10:45:00 -07003622 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003623}
3624
Glenn Kasten66fcab92012-02-24 14:59:21 -08003625void AudioFlinger::MixerThread::cacheParameters_l()
3626{
3627 PlaybackThread::cacheParameters_l();
3628
3629 // FIXME: Relaxed timing because of a certain device that can't meet latency
3630 // Should be reduced to 2x after the vendor fixes the driver issue
3631 // increase threshold again due to low power audio mode. The way this warning
3632 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003633 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003634}
3635
Mathias Agopian65ab4712010-07-14 17:59:35 -07003636// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003637AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003638 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003639 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003640 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003641{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003642}
3643
3644AudioFlinger::DirectOutputThread::~DirectOutputThread()
3645{
3646}
3647
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003648AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3649 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003650)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003651{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003652 sp<Track> trackToRemove;
3653
Glenn Kastenfec279f2012-03-08 07:47:15 -08003654 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003655
Glenn Kasten952eeb22012-03-06 11:30:57 -08003656 // find out which tracks need to be processed
3657 if (mActiveTracks.size() != 0) {
3658 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003659 // The track died recently
3660 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003661
Glenn Kasten952eeb22012-03-06 11:30:57 -08003662 Track* const track = t.get();
3663 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003664
Glenn Kasten952eeb22012-03-06 11:30:57 -08003665 // The first time a track is added we wait
3666 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003667 uint32_t minFrames;
3668 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3669 minFrames = mNormalFrameCount;
3670 } else {
3671 minFrames = 1;
3672 }
3673 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003674 !track->isPaused() && !track->isTerminated())
3675 {
3676 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003677
Glenn Kasten952eeb22012-03-06 11:30:57 -08003678 if (track->mFillingUpStatus == Track::FS_FILLED) {
3679 track->mFillingUpStatus = Track::FS_ACTIVE;
3680 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003681 if (track->mState == TrackBase::RESUMING) {
3682 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003683 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003684 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003685
Glenn Kasten952eeb22012-03-06 11:30:57 -08003686 // compute volume for this track
3687 float left, right;
3688 if (track->isMuted() || mMasterMute || track->isPausing() ||
3689 mStreamTypes[track->streamType()].mute) {
3690 left = right = 0;
3691 if (track->isPausing()) {
3692 track->setPaused();
3693 }
3694 } else {
3695 float typeVolume = mStreamTypes[track->streamType()].volume;
3696 float v = mMasterVolume * typeVolume;
3697 uint32_t vlr = cblk->getVolumeLR();
3698 float v_clamped = v * (vlr & 0xFFFF);
3699 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3700 left = v_clamped/MAX_GAIN;
3701 v_clamped = v * (vlr >> 16);
3702 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3703 right = v_clamped/MAX_GAIN;
3704 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003705
Glenn Kasten952eeb22012-03-06 11:30:57 -08003706 if (left != mLeftVolFloat || right != mRightVolFloat) {
3707 mLeftVolFloat = left;
3708 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003709
Glenn Kasten952eeb22012-03-06 11:30:57 -08003710 // Convert volumes from float to 8.24
3711 uint32_t vl = (uint32_t)(left * (1 << 24));
3712 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003713
Glenn Kasten952eeb22012-03-06 11:30:57 -08003714 // Delegate volume control to effect in track effect chain if needed
3715 // only one effect chain can be present on DirectOutputThread, so if
3716 // there is one, the track is connected to it
3717 if (!mEffectChains.isEmpty()) {
3718 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003719 mEffectChains[0]->setVolume_l(&vl, &vr);
3720 left = (float)vl / (1 << 24);
3721 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003722 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003723 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003724 }
3725
3726 // reset retry count
3727 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003728 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003729 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003730 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003731 // clear effect chain input buffer if an active track underruns to avoid sending
3732 // previous audio buffer again to effects
3733 if (!mEffectChains.isEmpty()) {
3734 mEffectChains[0]->clearInputBuffer();
3735 }
3736
Glenn Kasten952eeb22012-03-06 11:30:57 -08003737 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003738 if ((track->sharedBuffer() != 0) ||
Eric Laurent67c0a582012-05-01 19:31:12 -07003739 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003740 // We have consumed all the buffers of this track.
3741 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003742 // TODO: implement behavior for compressed audio
3743 size_t audioHALFrames =
3744 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3745 size_t framesWritten =
3746 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3747 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003748 if (track->isStopped()) {
3749 track->reset();
3750 }
Eric Laurenta011e352012-03-29 15:51:43 -07003751 trackToRemove = track;
3752 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003753 } else {
3754 // No buffers for this track. Give it a few chances to
3755 // fill a buffer, then remove it from active list.
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003756 if (--(track->mRetryCount) <= 0 || track->isTerminated()) {
3757 ALOGV_IF(track->mRetryCount <= 0, "BUFFER TIMEOUT: remove(%d) from active list", track->name());
Glenn Kasten952eeb22012-03-06 11:30:57 -08003758 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003759 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003760 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003761 }
3762 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003763 }
3764 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003765
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003766 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003767 // remove all the tracks that need to be...
3768 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003769 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003770 mActiveTracks.remove(trackToRemove);
3771 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003772 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003773 trackToRemove->sessionId());
3774 mEffectChains[0]->decActiveTrackCnt();
3775 }
3776 if (trackToRemove->isTerminated()) {
3777 removeTrack_l(trackToRemove);
3778 }
3779 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003780
Glenn Kastenfec279f2012-03-08 07:47:15 -08003781 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003782}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003783
Glenn Kasten000f0e32012-03-01 17:10:56 -08003784void AudioFlinger::DirectOutputThread::threadLoop_mix()
3785{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003786 AudioBufferProvider::Buffer buffer;
3787 size_t frameCount = mFrameCount;
3788 int8_t *curBuf = (int8_t *)mMixBuffer;
3789 // output audio to hardware
3790 while (frameCount) {
3791 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003792 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003793 if (CC_UNLIKELY(buffer.raw == NULL)) {
3794 memset(curBuf, 0, frameCount * mFrameSize);
3795 break;
3796 }
3797 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3798 frameCount -= buffer.frameCount;
3799 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003800 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003801 }
3802 sleepTime = 0;
3803 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003804 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003805
Glenn Kasten000f0e32012-03-01 17:10:56 -08003806}
3807
3808void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3809{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003810 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003811 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003812 sleepTime = activeSleepTime;
3813 } else {
3814 sleepTime = idleSleepTime;
3815 }
3816 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003817 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003818 sleepTime = 0;
3819 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003820}
3821
3822// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003823int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003824{
3825 return 0;
3826}
3827
3828// deleteTrackName_l() must be called with ThreadBase::mLock held
3829void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3830{
3831}
3832
3833// checkForNewParameters_l() must be called with ThreadBase::mLock held
3834bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3835{
3836 bool reconfig = false;
3837
3838 while (!mNewParameters.isEmpty()) {
3839 status_t status = NO_ERROR;
3840 String8 keyValuePair = mNewParameters[0];
3841 AudioParameter param = AudioParameter(keyValuePair);
3842 int value;
3843
3844 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3845 // do not accept frame count changes if tracks are open as the track buffer
3846 // size depends on frame count and correct behavior would not be garantied
3847 // if frame count is changed after track creation
3848 if (!mTracks.isEmpty()) {
3849 status = INVALID_OPERATION;
3850 } else {
3851 reconfig = true;
3852 }
3853 }
3854 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003855 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003856 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003857 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003858 mOutput->stream->common.standby(&mOutput->stream->common);
3859 mStandby = true;
3860 mBytesWritten = 0;
3861 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003862 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003863 }
3864 if (status == NO_ERROR && reconfig) {
3865 readOutputParameters();
3866 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3867 }
3868 }
3869
3870 mNewParameters.removeAt(0);
3871
3872 mParamStatus = status;
3873 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003874 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3875 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003876 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003877 }
3878 return reconfig;
3879}
3880
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003881uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003882{
3883 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003884 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003885 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003886 } else {
3887 time = 10000;
3888 }
3889 return time;
3890}
3891
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003892uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003893{
3894 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003895 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003896 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003897 } else {
3898 time = 10000;
3899 }
3900 return time;
3901}
3902
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003903uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003904{
3905 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003906 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003907 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3908 } else {
3909 time = 10000;
3910 }
3911 return time;
3912}
3913
Glenn Kasten66fcab92012-02-24 14:59:21 -08003914void AudioFlinger::DirectOutputThread::cacheParameters_l()
3915{
3916 PlaybackThread::cacheParameters_l();
3917
3918 // use shorter standby delay as on normal output to release
3919 // hardware resources as soon as possible
3920 standbyDelay = microseconds(activeSleepTime*2);
3921}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003922
Mathias Agopian65ab4712010-07-14 17:59:35 -07003923// ----------------------------------------------------------------------------
3924
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003925AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003926 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003927 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3928 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003929{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003930 addOutputTrack(mainThread);
3931}
3932
3933AudioFlinger::DuplicatingThread::~DuplicatingThread()
3934{
3935 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3936 mOutputTracks[i]->destroy();
3937 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003938}
3939
Glenn Kasten000f0e32012-03-01 17:10:56 -08003940void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003941{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003942 // mix buffers...
3943 if (outputsReady(outputTracks)) {
3944 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3945 } else {
3946 memset(mMixBuffer, 0, mixBufferSize);
3947 }
3948 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003949 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003950 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003951}
3952
3953void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3954{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003955 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003956 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003957 sleepTime = activeSleepTime;
3958 } else {
3959 sleepTime = idleSleepTime;
3960 }
3961 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003962 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3963 writeFrames = mNormalFrameCount;
3964 memset(mMixBuffer, 0, mixBufferSize);
3965 } else {
3966 // flush remaining overflow buffers in output tracks
3967 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003968 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003969 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003970 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003971}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003972
Glenn Kasten000f0e32012-03-01 17:10:56 -08003973void AudioFlinger::DuplicatingThread::threadLoop_write()
3974{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003975 for (size_t i = 0; i < outputTracks.size(); i++) {
3976 outputTracks[i]->write(mMixBuffer, writeFrames);
3977 }
3978 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003979}
Glenn Kasten688a6402012-02-29 07:57:06 -08003980
Glenn Kasten000f0e32012-03-01 17:10:56 -08003981void AudioFlinger::DuplicatingThread::threadLoop_standby()
3982{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003983 // DuplicatingThread implements standby by stopping all tracks
3984 for (size_t i = 0; i < outputTracks.size(); i++) {
3985 outputTracks[i]->stop();
3986 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003987}
3988
Glenn Kastenfa26a852012-03-06 11:28:04 -08003989void AudioFlinger::DuplicatingThread::saveOutputTracks()
3990{
3991 outputTracks = mOutputTracks;
3992}
3993
3994void AudioFlinger::DuplicatingThread::clearOutputTracks()
3995{
3996 outputTracks.clear();
3997}
3998
Mathias Agopian65ab4712010-07-14 17:59:35 -07003999void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4000{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004001 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004002 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004003 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004004 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004005 this,
4006 mSampleRate,
4007 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004008 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004009 frameCount);
4010 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004011 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004012 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004013 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004014 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004015 }
4016}
4017
4018void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4019{
4020 Mutex::Autolock _l(mLock);
4021 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004022 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004023 mOutputTracks[i]->destroy();
4024 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004025 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004026 return;
4027 }
4028 }
Steve Block3856b092011-10-20 11:56:00 +01004029 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004030}
4031
Glenn Kasten438b0362012-03-06 11:24:48 -08004032// caller must hold mLock
4033void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004034{
4035 mWaitTimeMs = UINT_MAX;
4036 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4037 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004038 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004039 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4040 if (waitTimeMs < mWaitTimeMs) {
4041 mWaitTimeMs = waitTimeMs;
4042 }
4043 }
4044 }
4045}
4046
4047
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004048bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004049{
4050 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004051 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004052 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004053 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004054 return false;
4055 }
4056 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004057 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004058 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004059 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004060 return false;
4061 }
4062 }
4063 return true;
4064}
4065
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004066uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004067{
4068 return (mWaitTimeMs * 1000) / 2;
4069}
4070
Glenn Kasten66fcab92012-02-24 14:59:21 -08004071void AudioFlinger::DuplicatingThread::cacheParameters_l()
4072{
4073 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4074 updateWaitTime_l();
4075
4076 MixerThread::cacheParameters_l();
4077}
4078
Mathias Agopian65ab4712010-07-14 17:59:35 -07004079// ----------------------------------------------------------------------------
4080
4081// TrackBase constructor must be called with AudioFlinger::mLock held
4082AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004083 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004084 const sp<Client>& client,
4085 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004086 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004087 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004088 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004089 const sp<IMemory>& sharedBuffer,
4090 int sessionId)
4091 : RefBase(),
4092 mThread(thread),
4093 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004094 mCblk(NULL),
4095 // mBuffer
4096 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004097 mFrameCount(0),
4098 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004099 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004100 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004101 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004102 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004103 // mChannelCount
4104 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004105{
Steve Block3856b092011-10-20 11:56:00 +01004106 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004107
Steve Blockb8a80522011-12-20 16:23:08 +00004108 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004109 size_t size = sizeof(audio_track_cblk_t);
4110 uint8_t channelCount = popcount(channelMask);
4111 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4112 if (sharedBuffer == 0) {
4113 size += bufferSize;
4114 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004115
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004116 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004117 mCblkMemory = client->heap()->allocate(size);
4118 if (mCblkMemory != 0) {
4119 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004120 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004121 new(mCblk) audio_track_cblk_t();
4122 // clear all buffers
4123 mCblk->frameCount = frameCount;
4124 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004125// uncomment the following lines to quickly test 32-bit wraparound
4126// mCblk->user = 0xffff0000;
4127// mCblk->server = 0xffff0000;
4128// mCblk->userBase = 0xffff0000;
4129// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004130 mChannelCount = channelCount;
4131 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004132 if (sharedBuffer == 0) {
4133 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4134 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4135 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004136 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004137 mCblk->flags = CBLK_UNDERRUN_ON;
4138 } else {
4139 mBuffer = sharedBuffer->pointer();
4140 }
4141 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4142 }
4143 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004144 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004145 client->heap()->dump("AudioTrack");
4146 return;
4147 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004148 } else {
4149 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004150 // construct the shared structure in-place.
4151 new(mCblk) audio_track_cblk_t();
4152 // clear all buffers
4153 mCblk->frameCount = frameCount;
4154 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004155// uncomment the following lines to quickly test 32-bit wraparound
4156// mCblk->user = 0xffff0000;
4157// mCblk->server = 0xffff0000;
4158// mCblk->userBase = 0xffff0000;
4159// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004160 mChannelCount = channelCount;
4161 mChannelMask = channelMask;
4162 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4163 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4164 // Force underrun condition to avoid false underrun callback until first data is
4165 // written to buffer (other flags are cleared)
4166 mCblk->flags = CBLK_UNDERRUN_ON;
4167 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004168 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004169}
4170
4171AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4172{
Glenn Kastena0d68332012-01-27 16:47:15 -08004173 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004174 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004175 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004176 } else {
4177 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004178 }
4179 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004180 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004181 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004182 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004183 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004184 // If the client's reference count drops to zero, the associated destructor
4185 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4186 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004187 mClient.clear();
4188 }
4189}
4190
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004191// AudioBufferProvider interface
4192// getNextBuffer() = 0;
4193// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004194void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4195{
Glenn Kastene0feee32011-12-13 11:53:26 -08004196 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004197 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004198 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004199 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200 buffer->frameCount = 0;
4201}
4202
4203bool AudioFlinger::ThreadBase::TrackBase::step() {
4204 bool result;
4205 audio_track_cblk_t* cblk = this->cblk();
4206
4207 result = cblk->stepServer(mFrameCount);
4208 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004209 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004210 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004211 }
4212 return result;
4213}
4214
4215void AudioFlinger::ThreadBase::TrackBase::reset() {
4216 audio_track_cblk_t* cblk = this->cblk();
4217
4218 cblk->user = 0;
4219 cblk->server = 0;
4220 cblk->userBase = 0;
4221 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004222 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004223 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004224}
4225
Mathias Agopian65ab4712010-07-14 17:59:35 -07004226int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4227 return (int)mCblk->sampleRate;
4228}
4229
Mathias Agopian65ab4712010-07-14 17:59:35 -07004230void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4231 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004232 size_t frameSize = cblk->frameSize;
4233 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4234 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004235
4236 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004237 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4238 "TrackBase::getBuffer buffer out of range:\n"
4239 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4240 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004241 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004242 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004243
4244 return bufferStart;
4245}
4246
Eric Laurenta011e352012-03-29 15:51:43 -07004247status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4248{
4249 mSyncEvents.add(event);
4250 return NO_ERROR;
4251}
4252
Mathias Agopian65ab4712010-07-14 17:59:35 -07004253// ----------------------------------------------------------------------------
4254
4255// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4256AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004257 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004258 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004259 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004260 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004261 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004262 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004263 int frameCount,
4264 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004265 int sessionId,
4266 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004267 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004268 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004269 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004270 // mRetryCount initialized later when needed
4271 mSharedBuffer(sharedBuffer),
4272 mStreamType(streamType),
4273 mName(-1), // see note below
4274 mMainBuffer(thread->mixBuffer()),
4275 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004276 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004277 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004278 mFlags(flags),
4279 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004280 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004281 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004282{
4283 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004284 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4285 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004286 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004287 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Glenn Kasten254af182012-07-03 14:59:05 -07004288 mName = thread->getTrackName_l(channelMask);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004289 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004290 if (mName < 0) {
4291 ALOGE("no more track names available");
4292 return;
4293 }
4294 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004295 if (flags & IAudioFlinger::TRACK_FAST) {
4296 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4297 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4298 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004299 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004300 // FIXME This is too eager. We allocate a fast track index before the
4301 // fast track becomes active. Since fast tracks are a scarce resource,
4302 // this means we are potentially denying other more important fast tracks from
4303 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004304 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004305 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004306 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004307 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004308 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004309 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004310 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004311 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004312}
4313
4314AudioFlinger::PlaybackThread::Track::~Track()
4315{
Steve Block3856b092011-10-20 11:56:00 +01004316 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004317}
4318
4319void AudioFlinger::PlaybackThread::Track::destroy()
4320{
4321 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4322 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004323 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004324 // we must acquire a strong reference on this Track before locking mLock
4325 // here so that the destructor is called only when exiting this function.
4326 // On the other hand, as long as Track::destroy() is only called by
4327 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4328 // this Track with its member mTrack.
4329 sp<Track> keep(this);
4330 { // scope for mLock
4331 sp<ThreadBase> thread = mThread.promote();
4332 if (thread != 0) {
4333 if (!isOutputTrack()) {
4334 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004335 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004336
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004337#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004338 // to track the speaker usage
4339 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004340#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004341 }
4342 AudioSystem::releaseOutput(thread->id());
4343 }
4344 Mutex::Autolock _l(thread->mLock);
4345 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4346 playbackThread->destroyTrack_l(this);
4347 }
4348 }
4349}
4350
Glenn Kasten288ed212012-04-25 17:52:27 -07004351/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4352{
Glenn Kastene213c862012-04-25 13:46:15 -07004353 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 -07004354 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004355}
4356
Mathias Agopian65ab4712010-07-14 17:59:35 -07004357void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4358{
Glenn Kasten83d86532012-01-17 14:39:34 -08004359 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004360 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004361 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004362 } else {
4363 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4364 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004365 track_state state = mState;
4366 char stateChar;
4367 switch (state) {
4368 case IDLE:
4369 stateChar = 'I';
4370 break;
4371 case TERMINATED:
4372 stateChar = 'T';
4373 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004374 case STOPPING_1:
4375 stateChar = 's';
4376 break;
4377 case STOPPING_2:
4378 stateChar = '5';
4379 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004380 case STOPPED:
4381 stateChar = 'S';
4382 break;
4383 case RESUMING:
4384 stateChar = 'R';
4385 break;
4386 case ACTIVE:
4387 stateChar = 'A';
4388 break;
4389 case PAUSING:
4390 stateChar = 'p';
4391 break;
4392 case PAUSED:
4393 stateChar = 'P';
4394 break;
Eric Laurent29864602012-05-08 18:57:51 -07004395 case FLUSHED:
4396 stateChar = 'F';
4397 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004398 default:
4399 stateChar = '?';
4400 break;
4401 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004402 char nowInUnderrun;
4403 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4404 case UNDERRUN_FULL:
4405 nowInUnderrun = ' ';
4406 break;
4407 case UNDERRUN_PARTIAL:
4408 nowInUnderrun = '<';
4409 break;
4410 case UNDERRUN_EMPTY:
4411 nowInUnderrun = '*';
4412 break;
4413 default:
4414 nowInUnderrun = '?';
4415 break;
4416 }
Glenn Kastene213c862012-04-25 13:46:15 -07004417 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4418 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004419 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004420 mStreamType,
4421 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004422 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004423 mSessionId,
4424 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004425 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004426 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004427 mMute,
4428 mFillingUpStatus,
4429 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004430 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4431 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004432 mCblk->server,
4433 mCblk->user,
4434 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004435 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004436 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004437 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004438 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004439}
4440
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004441// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004442status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004443 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004444{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004445 audio_track_cblk_t* cblk = this->cblk();
4446 uint32_t framesReady;
4447 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004448
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004449 // Check if last stepServer failed, try to step now
4450 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004451 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4452 // Since the fast mixer is higher priority than client callback thread,
4453 // it does not result in priority inversion for client.
4454 // But a non-blocking solution would be preferable to avoid
4455 // fast mixer being unable to tryLock(), and
4456 // to avoid the extra context switches if the client wakes up,
4457 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004458 if (!step()) goto getNextBuffer_exit;
4459 ALOGV("stepServer recovered");
4460 mStepServerFailed = false;
4461 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004462
Glenn Kasten288ed212012-04-25 17:52:27 -07004463 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004464 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004465
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004466 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004467 uint32_t s = cblk->server;
4468 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4469
4470 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4471 if (framesReq > framesReady) {
4472 framesReq = framesReady;
4473 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004474 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004475 framesReq = bufferEnd - s;
4476 }
4477
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004478 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004479 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004480 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004481 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004482
4483getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004484 buffer->raw = NULL;
4485 buffer->frameCount = 0;
4486 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4487 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004488}
4489
Glenn Kasten288ed212012-04-25 17:52:27 -07004490// Note that framesReady() takes a mutex on the control block using tryLock().
4491// This could result in priority inversion if framesReady() is called by the normal mixer,
4492// as the normal mixer thread runs at lower
4493// priority than the client's callback thread: there is a short window within framesReady()
4494// during which the normal mixer could be preempted, and the client callback would block.
4495// Another problem can occur if framesReady() is called by the fast mixer:
4496// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4497// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4498size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004499 return mCblk->framesReady();
4500}
4501
Glenn Kasten288ed212012-04-25 17:52:27 -07004502// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004503bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004504 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004505
John Grossman4ff14ba2012-02-08 16:37:41 -08004506 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004507 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4508 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004509 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004510 return true;
4511 }
4512 return false;
4513}
4514
Glenn Kasten3acbd052012-02-28 10:39:56 -08004515status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004516 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004517{
4518 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004519 ALOGV("start(%d), calling pid %d session %d",
4520 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004521
Mathias Agopian65ab4712010-07-14 17:59:35 -07004522 sp<ThreadBase> thread = mThread.promote();
4523 if (thread != 0) {
4524 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004525 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004526 // here the track could be either new, or restarted
4527 // in both cases "unstop" the track
4528 if (mState == PAUSED) {
4529 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004530 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004531 } else {
4532 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004533 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004534 }
4535
4536 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4537 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004538 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004539 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004540
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004541#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004542 // to track the speaker usage
4543 if (status == NO_ERROR) {
4544 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4545 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004546#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004547 }
4548 if (status == NO_ERROR) {
4549 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4550 playbackThread->addTrack_l(this);
4551 } else {
4552 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004553 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004554 }
4555 } else {
4556 status = BAD_VALUE;
4557 }
4558 return status;
4559}
4560
4561void AudioFlinger::PlaybackThread::Track::stop()
4562{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004563 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004564 sp<ThreadBase> thread = mThread.promote();
4565 if (thread != 0) {
4566 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004567 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004568 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004569 // If the track is not active (PAUSED and buffers full), flush buffers
4570 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4571 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4572 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004573 mState = STOPPED;
4574 } else if (!isFastTrack()) {
4575 mState = STOPPED;
4576 } else {
4577 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4578 // and then to STOPPED and reset() when presentation is complete
4579 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004580 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004581 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004582 }
4583 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4584 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004585 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004586 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004587
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004588#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004589 // to track the speaker usage
4590 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004591#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004592 }
4593 }
4594}
4595
4596void AudioFlinger::PlaybackThread::Track::pause()
4597{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004598 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004599 sp<ThreadBase> thread = mThread.promote();
4600 if (thread != 0) {
4601 Mutex::Autolock _l(thread->mLock);
4602 if (mState == ACTIVE || mState == RESUMING) {
4603 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004604 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004605 if (!isOutputTrack()) {
4606 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004607 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004608 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004609
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004610#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004611 // to track the speaker usage
4612 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004613#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004614 }
4615 }
4616 }
4617}
4618
4619void AudioFlinger::PlaybackThread::Track::flush()
4620{
Steve Block3856b092011-10-20 11:56:00 +01004621 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004622 sp<ThreadBase> thread = mThread.promote();
4623 if (thread != 0) {
4624 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004625 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4626 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004627 return;
4628 }
4629 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004630 // FLUSHED state
4631 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004632 // do not reset the track if it is still in the process of being stopped or paused.
4633 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004634 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004635 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004636 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4637 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4638 reset();
4639 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004640 }
4641}
4642
4643void AudioFlinger::PlaybackThread::Track::reset()
4644{
4645 // Do not reset twice to avoid discarding data written just after a flush and before
4646 // the audioflinger thread detects the track is stopped.
4647 if (!mResetDone) {
4648 TrackBase::reset();
4649 // Force underrun condition to avoid false underrun callback until first data is
4650 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004651 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4652 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004653 mFillingUpStatus = FS_FILLING;
4654 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004655 if (mState == FLUSHED) {
4656 mState = IDLE;
4657 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004658 }
4659}
4660
4661void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4662{
4663 mMute = muted;
4664}
4665
Mathias Agopian65ab4712010-07-14 17:59:35 -07004666status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4667{
4668 status_t status = DEAD_OBJECT;
4669 sp<ThreadBase> thread = mThread.promote();
4670 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004671 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004672 sp<AudioFlinger> af = mClient->audioFlinger();
4673
4674 Mutex::Autolock _l(af->mLock);
4675
4676 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004677
Eric Laurent109347d2012-07-02 12:31:03 -07004678 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004679 Mutex::Autolock _dl(playbackThread->mLock);
4680 Mutex::Autolock _sl(srcThread->mLock);
4681 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4682 if (chain == 0) {
4683 return INVALID_OPERATION;
4684 }
4685
4686 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4687 if (effect == 0) {
4688 return INVALID_OPERATION;
4689 }
4690 srcThread->removeEffect_l(effect);
4691 playbackThread->addEffect_l(effect);
4692 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4693 if (effect->state() == EffectModule::ACTIVE ||
4694 effect->state() == EffectModule::STOPPING) {
4695 effect->start();
4696 }
4697
4698 sp<EffectChain> dstChain = effect->chain().promote();
4699 if (dstChain == 0) {
4700 srcThread->addEffect_l(effect);
4701 return INVALID_OPERATION;
4702 }
4703 AudioSystem::unregisterEffect(effect->id());
4704 AudioSystem::registerEffect(&effect->desc(),
4705 srcThread->id(),
4706 dstChain->strategy(),
4707 AUDIO_SESSION_OUTPUT_MIX,
4708 effect->id());
4709 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004710 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004711 }
4712 return status;
4713}
4714
4715void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4716{
4717 mAuxEffectId = EffectId;
4718 mAuxBuffer = buffer;
4719}
4720
Eric Laurenta011e352012-03-29 15:51:43 -07004721bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4722 size_t audioHalFrames)
4723{
4724 // a track is considered presented when the total number of frames written to audio HAL
4725 // corresponds to the number of frames written when presentationComplete() is called for the
4726 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4727 if (mPresentationCompleteFrames == 0) {
4728 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4729 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4730 mPresentationCompleteFrames, audioHalFrames);
4731 }
4732 if (framesWritten >= mPresentationCompleteFrames) {
4733 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4734 mSessionId, framesWritten);
4735 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004736 return true;
4737 }
4738 return false;
4739}
4740
4741void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4742{
4743 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4744 if (mSyncEvents[i]->type() == type) {
4745 mSyncEvents[i]->trigger();
4746 mSyncEvents.removeAt(i);
4747 i--;
4748 }
4749 }
4750}
4751
Glenn Kasten58912562012-04-03 10:45:00 -07004752// implement VolumeBufferProvider interface
4753
4754uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4755{
4756 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4757 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4758 uint32_t vlr = mCblk->getVolumeLR();
4759 uint32_t vl = vlr & 0xFFFF;
4760 uint32_t vr = vlr >> 16;
4761 // track volumes come from shared memory, so can't be trusted and must be clamped
4762 if (vl > MAX_GAIN_INT) {
4763 vl = MAX_GAIN_INT;
4764 }
4765 if (vr > MAX_GAIN_INT) {
4766 vr = MAX_GAIN_INT;
4767 }
4768 // now apply the cached master volume and stream type volume;
4769 // this is trusted but lacks any synchronization or barrier so may be stale
4770 float v = mCachedVolume;
4771 vl *= v;
4772 vr *= v;
4773 // re-combine into U4.16
4774 vlr = (vr << 16) | (vl & 0xFFFF);
4775 // FIXME look at mute, pause, and stop flags
4776 return vlr;
4777}
Eric Laurenta011e352012-03-29 15:51:43 -07004778
Eric Laurent29864602012-05-08 18:57:51 -07004779status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4780{
4781 if (mState == TERMINATED || mState == PAUSED ||
4782 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4783 (mState == STOPPED)))) {
4784 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4785 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4786 event->cancel();
4787 return INVALID_OPERATION;
4788 }
4789 TrackBase::setSyncEvent(event);
4790 return NO_ERROR;
4791}
4792
John Grossman4ff14ba2012-02-08 16:37:41 -08004793// timed audio tracks
4794
4795sp<AudioFlinger::PlaybackThread::TimedTrack>
4796AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004797 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004798 const sp<Client>& client,
4799 audio_stream_type_t streamType,
4800 uint32_t sampleRate,
4801 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004802 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004803 int frameCount,
4804 const sp<IMemory>& sharedBuffer,
4805 int sessionId) {
4806 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004807 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004808
Glenn Kastena0356762012-03-19 10:38:51 -07004809 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004810 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4811 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004812}
4813
4814AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004815 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004816 const sp<Client>& client,
4817 audio_stream_type_t streamType,
4818 uint32_t sampleRate,
4819 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004820 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004821 int frameCount,
4822 const sp<IMemory>& sharedBuffer,
4823 int sessionId)
4824 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004825 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004826 mQueueHeadInFlight(false),
4827 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004828 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004829 mTimedSilenceBuffer(NULL),
4830 mTimedSilenceBufferSize(0),
4831 mTimedAudioOutputOnTime(false),
4832 mMediaTimeTransformValid(false)
4833{
4834 LocalClock lc;
4835 mLocalTimeFreq = lc.getLocalFreq();
4836
4837 mLocalTimeToSampleTransform.a_zero = 0;
4838 mLocalTimeToSampleTransform.b_zero = 0;
4839 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4840 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4841 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4842 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004843
4844 mMediaTimeToSampleTransform.a_zero = 0;
4845 mMediaTimeToSampleTransform.b_zero = 0;
4846 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4847 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4848 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4849 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004850}
4851
4852AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4853 mClient->releaseTimedTrack();
4854 delete [] mTimedSilenceBuffer;
4855}
4856
4857status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4858 size_t size, sp<IMemory>* buffer) {
4859
4860 Mutex::Autolock _l(mTimedBufferQueueLock);
4861
4862 trimTimedBufferQueue_l();
4863
4864 // lazily initialize the shared memory heap for timed buffers
4865 if (mTimedMemoryDealer == NULL) {
4866 const int kTimedBufferHeapSize = 512 << 10;
4867
4868 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4869 "AudioFlingerTimed");
4870 if (mTimedMemoryDealer == NULL)
4871 return NO_MEMORY;
4872 }
4873
4874 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4875 if (newBuffer == NULL) {
4876 newBuffer = mTimedMemoryDealer->allocate(size);
4877 if (newBuffer == NULL)
4878 return NO_MEMORY;
4879 }
4880
4881 *buffer = newBuffer;
4882 return NO_ERROR;
4883}
4884
4885// caller must hold mTimedBufferQueueLock
4886void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4887 int64_t mediaTimeNow;
4888 {
4889 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4890 if (!mMediaTimeTransformValid)
4891 return;
4892
4893 int64_t targetTimeNow;
4894 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4895 ? mCCHelper.getCommonTime(&targetTimeNow)
4896 : mCCHelper.getLocalTime(&targetTimeNow);
4897
4898 if (OK != res)
4899 return;
4900
4901 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4902 &mediaTimeNow)) {
4903 return;
4904 }
4905 }
4906
John Grossman1c345192012-03-27 14:00:17 -07004907 size_t trimEnd;
4908 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004909 int64_t bufEnd;
4910
John Grossmanc95cfbb2012-04-12 11:53:11 -07004911 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4912 // We have a next buffer. Just use its PTS as the PTS of the frame
4913 // following the last frame in this buffer. If the stream is sparse
4914 // (ie, there are deliberate gaps left in the stream which should be
4915 // filled with silence by the TimedAudioTrack), then this can result
4916 // in one extra buffer being left un-trimmed when it could have
4917 // been. In general, this is not typical, and we would rather
4918 // optimized away the TS calculation below for the more common case
4919 // where PTSes are contiguous.
4920 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4921 } else {
4922 // We have no next buffer. Compute the PTS of the frame following
4923 // the last frame in this buffer by computing the duration of of
4924 // this frame in media time units and adding it to the PTS of the
4925 // buffer.
4926 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4927 / mCblk->frameSize;
4928
4929 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4930 &bufEnd)) {
4931 ALOGE("Failed to convert frame count of %lld to media time"
4932 " duration" " (scale factor %d/%u) in %s",
4933 frameCount,
4934 mMediaTimeToSampleTransform.a_to_b_numer,
4935 mMediaTimeToSampleTransform.a_to_b_denom,
4936 __PRETTY_FUNCTION__);
4937 break;
4938 }
4939 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004940 }
John Grossman9fbdee12012-03-26 17:51:46 -07004941
4942 if (bufEnd > mediaTimeNow)
4943 break;
4944
4945 // Is the buffer we want to use in the middle of a mix operation right
4946 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4947 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004948 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004949 mTrimQueueHeadOnRelease = true;
4950 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004951 }
4952
John Grossman9fbdee12012-03-26 17:51:46 -07004953 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004954 if (trimStart < trimEnd) {
4955 // Update the bookkeeping for framesReady()
4956 for (size_t i = trimStart; i < trimEnd; ++i) {
4957 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4958 }
4959
4960 // Now actually remove the buffers from the queue.
4961 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004962 }
4963}
4964
John Grossman1c345192012-03-27 14:00:17 -07004965void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4966 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004967 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4968 "%s called (reason \"%s\"), but timed buffer queue has no"
4969 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004970
4971 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4972 mTimedBufferQueue.removeAt(0);
4973}
4974
4975void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4976 const TimedBuffer& buf,
4977 const char* logTag) {
4978 uint32_t bufBytes = buf.buffer()->size();
4979 uint32_t consumedAlready = buf.position();
4980
Eric Laurentb388e532012-04-14 13:32:48 -07004981 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004982 "Bad bookkeeping while updating frames pending. Timed buffer is"
4983 " only %u bytes long, but claims to have consumed %u"
4984 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004985 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004986
4987 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004988 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4989 "Bad bookkeeping while updating frames pending. Should have at"
4990 " least %u queued frames, but we think we have only %u. (update"
4991 " reason: \"%s\")",
4992 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004993
4994 mFramesPendingInQueue -= bufFrames;
4995}
4996
John Grossman4ff14ba2012-02-08 16:37:41 -08004997status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
4998 const sp<IMemory>& buffer, int64_t pts) {
4999
5000 {
5001 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5002 if (!mMediaTimeTransformValid)
5003 return INVALID_OPERATION;
5004 }
5005
5006 Mutex::Autolock _l(mTimedBufferQueueLock);
5007
John Grossman1c345192012-03-27 14:00:17 -07005008 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5009 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005010 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5011
5012 return NO_ERROR;
5013}
5014
5015status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5016 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5017
John Grossman1c345192012-03-27 14:00:17 -07005018 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5019 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5020 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005021
5022 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5023 target == TimedAudioTrack::COMMON_TIME)) {
5024 return BAD_VALUE;
5025 }
5026
5027 Mutex::Autolock lock(mMediaTimeTransformLock);
5028 mMediaTimeTransform = xform;
5029 mMediaTimeTransformTarget = target;
5030 mMediaTimeTransformValid = true;
5031
5032 return NO_ERROR;
5033}
5034
5035#define min(a, b) ((a) < (b) ? (a) : (b))
5036
5037// implementation of getNextBuffer for tracks whose buffers have timestamps
5038status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5039 AudioBufferProvider::Buffer* buffer, int64_t pts)
5040{
5041 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005042 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005043 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005044 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005045 return INVALID_OPERATION;
5046 }
5047
John Grossman4ff14ba2012-02-08 16:37:41 -08005048 Mutex::Autolock _l(mTimedBufferQueueLock);
5049
John Grossman9fbdee12012-03-26 17:51:46 -07005050 ALOG_ASSERT(!mQueueHeadInFlight,
5051 "getNextBuffer called without releaseBuffer!");
5052
John Grossman4ff14ba2012-02-08 16:37:41 -08005053 while (true) {
5054
5055 // if we have no timed buffers, then fail
5056 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005057 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005058 buffer->frameCount = 0;
5059 return NOT_ENOUGH_DATA;
5060 }
5061
5062 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5063
5064 // calculate the PTS of the head of the timed buffer queue expressed in
5065 // local time
5066 int64_t headLocalPTS;
5067 {
5068 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5069
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005070 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005071
5072 if (mMediaTimeTransform.a_to_b_denom == 0) {
5073 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005074 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005075 return NO_ERROR;
5076 }
5077
5078 int64_t transformedPTS;
5079 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5080 &transformedPTS)) {
5081 // the transform failed. this shouldn't happen, but if it does
5082 // then just drop this buffer
5083 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005084 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005085 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005086 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005087 return NO_ERROR;
5088 }
5089
5090 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5091 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5092 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005093 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005094 buffer->frameCount = 0;
5095 return INVALID_OPERATION;
5096 }
5097 } else {
5098 headLocalPTS = transformedPTS;
5099 }
5100 }
5101
5102 // adjust the head buffer's PTS to reflect the portion of the head buffer
5103 // that has already been consumed
5104 int64_t effectivePTS = headLocalPTS +
5105 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5106
5107 // Calculate the delta in samples between the head of the input buffer
5108 // queue and the start of the next output buffer that will be written.
5109 // If the transformation fails because of over or underflow, it means
5110 // that the sample's position in the output stream is so far out of
5111 // whack that it should just be dropped.
5112 int64_t sampleDelta;
5113 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5114 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005115 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5116 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005117 continue;
5118 }
5119 if (!mLocalTimeToSampleTransform.doForwardTransform(
5120 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005121 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005122 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005123 continue;
5124 }
5125
John Grossman1c345192012-03-27 14:00:17 -07005126 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5127 " sampleDelta=[%d.%08x]",
5128 head.pts(), head.position(), pts,
5129 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5130 + (sampleDelta >> 32)),
5131 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005132
5133 // if the delta between the ideal placement for the next input sample and
5134 // the current output position is within this threshold, then we will
5135 // concatenate the next input samples to the previous output
5136 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005137 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005138
5139 // if this is the first buffer of audio that we're emitting from this track
5140 // then it should be almost exactly on time.
5141 const int64_t kSampleStartupThreshold = 1LL << 32;
5142
5143 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005144 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005145 // the next input is close enough to being on time, so concatenate it
5146 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005147 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005148
John Grossman1c345192012-03-27 14:00:17 -07005149 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5150 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005151 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005152 }
5153
5154 // Looks like our output is not on time. Reset our on timed status.
5155 // Next time we mix samples from our input queue, then should be within
5156 // the StartupThreshold.
5157 mTimedAudioOutputOnTime = false;
5158 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005159 // the gap between the current output position and the proper start of
5160 // the next input sample is too big, so fill it with silence
5161 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5162
John Grossman9fbdee12012-03-26 17:51:46 -07005163 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005164 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5165 return NO_ERROR;
5166 } else {
5167 // the next input sample is late
5168 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5169 size_t onTimeSamplePosition =
5170 head.position() + lateFrames * mCblk->frameSize;
5171
5172 if (onTimeSamplePosition > head.buffer()->size()) {
5173 // all the remaining samples in the head are too late, so
5174 // drop it and move on
5175 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005176 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005177 continue;
5178 } else {
5179 // skip over the late samples
5180 head.setPosition(onTimeSamplePosition);
5181
5182 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005183 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005184
5185 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5186 return NO_ERROR;
5187 }
5188 }
5189 }
5190}
5191
5192// Yield samples from the timed buffer queue head up to the given output
5193// buffer's capacity.
5194//
5195// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005196void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005197 AudioBufferProvider::Buffer* buffer) {
5198
5199 const TimedBuffer& head = mTimedBufferQueue[0];
5200
5201 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5202 head.position());
5203
5204 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5205 mCblk->frameSize);
5206 size_t framesRequested = buffer->frameCount;
5207 buffer->frameCount = min(framesLeftInHead, framesRequested);
5208
John Grossman9fbdee12012-03-26 17:51:46 -07005209 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005210 mTimedAudioOutputOnTime = true;
5211}
5212
5213// Yield samples of silence up to the given output buffer's capacity
5214//
5215// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005216void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005217 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5218
5219 // lazily allocate a buffer filled with silence
5220 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5221 delete [] mTimedSilenceBuffer;
5222 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5223 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5224 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5225 }
5226
5227 buffer->raw = mTimedSilenceBuffer;
5228 size_t framesRequested = buffer->frameCount;
5229 buffer->frameCount = min(numFrames, framesRequested);
5230
5231 mTimedAudioOutputOnTime = false;
5232}
5233
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005234// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005235void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5236 AudioBufferProvider::Buffer* buffer) {
5237
5238 Mutex::Autolock _l(mTimedBufferQueueLock);
5239
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005240 // If the buffer which was just released is part of the buffer at the head
5241 // of the queue, be sure to update the amt of the buffer which has been
5242 // consumed. If the buffer being returned is not part of the head of the
5243 // queue, its either because the buffer is part of the silence buffer, or
5244 // because the head of the timed queue was trimmed after the mixer called
5245 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005246 if (buffer->raw == mTimedSilenceBuffer) {
5247 ALOG_ASSERT(!mQueueHeadInFlight,
5248 "Queue head in flight during release of silence buffer!");
5249 goto done;
5250 }
5251
5252 ALOG_ASSERT(mQueueHeadInFlight,
5253 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5254 " head in flight.");
5255
5256 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005257 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005258
5259 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005260 void* end = reinterpret_cast<void*>(
5261 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5262 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005263
John Grossman9fbdee12012-03-26 17:51:46 -07005264 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5265 "released buffer not within the head of the timed buffer"
5266 " queue; qHead = [%p, %p], released buffer = %p",
5267 start, end, buffer->raw);
5268
5269 head.setPosition(head.position() +
5270 (buffer->frameCount * mCblk->frameSize));
5271 mQueueHeadInFlight = false;
5272
John Grossman1c345192012-03-27 14:00:17 -07005273 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5274 "Bad bookkeeping during releaseBuffer! Should have at"
5275 " least %u queued frames, but we think we have only %u",
5276 buffer->frameCount, mFramesPendingInQueue);
5277
5278 mFramesPendingInQueue -= buffer->frameCount;
5279
John Grossman9fbdee12012-03-26 17:51:46 -07005280 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5281 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005282 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005283 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005284 }
John Grossman9fbdee12012-03-26 17:51:46 -07005285 } else {
5286 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5287 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005288 }
5289
John Grossman9fbdee12012-03-26 17:51:46 -07005290done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005291 buffer->raw = 0;
5292 buffer->frameCount = 0;
5293}
5294
Glenn Kasten288ed212012-04-25 17:52:27 -07005295size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005296 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005297 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005298}
5299
5300AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5301 : mPTS(0), mPosition(0) {}
5302
5303AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5304 const sp<IMemory>& buffer, int64_t pts)
5305 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5306
Mathias Agopian65ab4712010-07-14 17:59:35 -07005307// ----------------------------------------------------------------------------
5308
5309// RecordTrack constructor must be called with AudioFlinger::mLock held
5310AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005311 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005312 const sp<Client>& client,
5313 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005314 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005315 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005316 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005317 int sessionId)
5318 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005319 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005320 mOverflow(false)
5321{
5322 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005323 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5324 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5325 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5326 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5327 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5328 } else {
5329 mCblk->frameSize = sizeof(int8_t);
5330 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005331 }
5332}
5333
5334AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5335{
Glenn Kasten510a3d62012-07-16 14:24:34 -07005336 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005337}
5338
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005339// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005340status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005341{
5342 audio_track_cblk_t* cblk = this->cblk();
5343 uint32_t framesAvail;
5344 uint32_t framesReq = buffer->frameCount;
5345
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005346 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005347 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005348 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005349 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005350 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005351 }
5352
5353 framesAvail = cblk->framesAvailable_l();
5354
Glenn Kastenf6b16782011-12-15 09:51:17 -08005355 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005356 uint32_t s = cblk->server;
5357 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5358
5359 if (framesReq > framesAvail) {
5360 framesReq = framesAvail;
5361 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005362 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005363 framesReq = bufferEnd - s;
5364 }
5365
5366 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005367 buffer->frameCount = framesReq;
5368 return NO_ERROR;
5369 }
5370
5371getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005372 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005373 buffer->frameCount = 0;
5374 return NOT_ENOUGH_DATA;
5375}
5376
Glenn Kasten3acbd052012-02-28 10:39:56 -08005377status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005378 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005379{
5380 sp<ThreadBase> thread = mThread.promote();
5381 if (thread != 0) {
5382 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005383 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005384 } else {
5385 return BAD_VALUE;
5386 }
5387}
5388
5389void AudioFlinger::RecordThread::RecordTrack::stop()
5390{
5391 sp<ThreadBase> thread = mThread.promote();
5392 if (thread != 0) {
5393 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005394 recordThread->mLock.lock();
5395 bool doStop = recordThread->stop_l(this);
5396 if (doStop) {
5397 TrackBase::reset();
5398 // Force overrun condition to avoid false overrun callback until first data is
5399 // read from buffer
5400 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5401 }
5402 recordThread->mLock.unlock();
5403 if (doStop) {
5404 AudioSystem::stopInput(recordThread->id());
5405 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005406 }
5407}
5408
Glenn Kasten510a3d62012-07-16 14:24:34 -07005409/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
5410{
5411 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
5412}
5413
Mathias Agopian65ab4712010-07-14 17:59:35 -07005414void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5415{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005416 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005417 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005418 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005419 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005420 mSessionId,
5421 mFrameCount,
5422 mState,
5423 mCblk->sampleRate,
5424 mCblk->server,
5425 mCblk->user);
5426}
5427
5428
5429// ----------------------------------------------------------------------------
5430
5431AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005432 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005433 DuplicatingThread *sourceThread,
5434 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005435 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005436 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005437 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005438 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5439 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005440 mActive(false), mSourceThread(sourceThread)
5441{
5442
Mathias Agopian65ab4712010-07-14 17:59:35 -07005443 if (mCblk != NULL) {
5444 mCblk->flags |= CBLK_DIRECTION_OUT;
5445 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446 mOutBuffer.frameCount = 0;
5447 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005448 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005449 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5450 mCblk, mBuffer, mCblk->buffers,
5451 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005452 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005453 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005454 }
5455}
5456
5457AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5458{
5459 clearBufferQueue();
5460}
5461
Glenn Kasten3acbd052012-02-28 10:39:56 -08005462status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005463 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005464{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005465 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005466 if (status != NO_ERROR) {
5467 return status;
5468 }
5469
5470 mActive = true;
5471 mRetryCount = 127;
5472 return status;
5473}
5474
5475void AudioFlinger::PlaybackThread::OutputTrack::stop()
5476{
5477 Track::stop();
5478 clearBufferQueue();
5479 mOutBuffer.frameCount = 0;
5480 mActive = false;
5481}
5482
5483bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5484{
5485 Buffer *pInBuffer;
5486 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005487 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005488 bool outputBufferFull = false;
5489 inBuffer.frameCount = frames;
5490 inBuffer.i16 = data;
5491
5492 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5493
5494 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005495 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005496 sp<ThreadBase> thread = mThread.promote();
5497 if (thread != 0) {
5498 MixerThread *mixerThread = (MixerThread *)thread.get();
5499 if (mCblk->frameCount > frames){
5500 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5501 uint32_t startFrames = (mCblk->frameCount - frames);
5502 pInBuffer = new Buffer;
5503 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5504 pInBuffer->frameCount = startFrames;
5505 pInBuffer->i16 = pInBuffer->mBuffer;
5506 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5507 mBufferQueue.add(pInBuffer);
5508 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005509 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005510 }
5511 }
5512 }
5513 }
5514
5515 while (waitTimeLeftMs) {
5516 // First write pending buffers, then new data
5517 if (mBufferQueue.size()) {
5518 pInBuffer = mBufferQueue.itemAt(0);
5519 } else {
5520 pInBuffer = &inBuffer;
5521 }
5522
5523 if (pInBuffer->frameCount == 0) {
5524 break;
5525 }
5526
5527 if (mOutBuffer.frameCount == 0) {
5528 mOutBuffer.frameCount = pInBuffer->frameCount;
5529 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005530 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005531 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005532 outputBufferFull = true;
5533 break;
5534 }
5535 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5536 if (waitTimeLeftMs >= waitTimeMs) {
5537 waitTimeLeftMs -= waitTimeMs;
5538 } else {
5539 waitTimeLeftMs = 0;
5540 }
5541 }
5542
5543 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5544 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5545 mCblk->stepUser(outFrames);
5546 pInBuffer->frameCount -= outFrames;
5547 pInBuffer->i16 += outFrames * channelCount;
5548 mOutBuffer.frameCount -= outFrames;
5549 mOutBuffer.i16 += outFrames * channelCount;
5550
5551 if (pInBuffer->frameCount == 0) {
5552 if (mBufferQueue.size()) {
5553 mBufferQueue.removeAt(0);
5554 delete [] pInBuffer->mBuffer;
5555 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005556 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005557 } else {
5558 break;
5559 }
5560 }
5561 }
5562
5563 // If we could not write all frames, allocate a buffer and queue it for next time.
5564 if (inBuffer.frameCount) {
5565 sp<ThreadBase> thread = mThread.promote();
5566 if (thread != 0 && !thread->standby()) {
5567 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5568 pInBuffer = new Buffer;
5569 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5570 pInBuffer->frameCount = inBuffer.frameCount;
5571 pInBuffer->i16 = pInBuffer->mBuffer;
5572 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5573 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005574 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005575 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005576 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005577 }
5578 }
5579 }
5580
5581 // Calling write() with a 0 length buffer, means that no more data will be written:
5582 // If no more buffers are pending, fill output track buffer to make sure it is started
5583 // by output mixer.
5584 if (frames == 0 && mBufferQueue.size() == 0) {
5585 if (mCblk->user < mCblk->frameCount) {
5586 frames = mCblk->frameCount - mCblk->user;
5587 pInBuffer = new Buffer;
5588 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5589 pInBuffer->frameCount = frames;
5590 pInBuffer->i16 = pInBuffer->mBuffer;
5591 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5592 mBufferQueue.add(pInBuffer);
5593 } else if (mActive) {
5594 stop();
5595 }
5596 }
5597
5598 return outputBufferFull;
5599}
5600
5601status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5602{
5603 int active;
5604 status_t result;
5605 audio_track_cblk_t* cblk = mCblk;
5606 uint32_t framesReq = buffer->frameCount;
5607
Steve Block3856b092011-10-20 11:56:00 +01005608// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005609 buffer->frameCount = 0;
5610
5611 uint32_t framesAvail = cblk->framesAvailable();
5612
5613
5614 if (framesAvail == 0) {
5615 Mutex::Autolock _l(cblk->lock);
5616 goto start_loop_here;
5617 while (framesAvail == 0) {
5618 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005619 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005620 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005621 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005622 }
5623 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5624 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005625 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005626 }
5627 // read the server count again
5628 start_loop_here:
5629 framesAvail = cblk->framesAvailable_l();
5630 }
5631 }
5632
5633// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005634// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005635// }
5636
5637 if (framesReq > framesAvail) {
5638 framesReq = framesAvail;
5639 }
5640
5641 uint32_t u = cblk->user;
5642 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5643
Marco Nelissena1472d92012-03-30 14:36:54 -07005644 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005645 framesReq = bufferEnd - u;
5646 }
5647
5648 buffer->frameCount = framesReq;
5649 buffer->raw = (void *)cblk->buffer(u);
5650 return NO_ERROR;
5651}
5652
5653
5654void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5655{
5656 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005657
5658 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005659 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005660 delete [] pBuffer->mBuffer;
5661 delete pBuffer;
5662 }
5663 mBufferQueue.clear();
5664}
5665
5666// ----------------------------------------------------------------------------
5667
5668AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5669 : RefBase(),
5670 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005671 // FIXME should be a "k" constant not hard-coded, in .h or ro. property, see 4 lines below
Mathias Agopian65ab4712010-07-14 17:59:35 -07005672 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005673 mPid(pid),
5674 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005675{
5676 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5677}
5678
5679// Client destructor must be called with AudioFlinger::mLock held
5680AudioFlinger::Client::~Client()
5681{
5682 mAudioFlinger->removeClient_l(mPid);
5683}
5684
Glenn Kasten435dbe62012-01-30 10:15:48 -08005685sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005686{
5687 return mMemoryDealer;
5688}
5689
John Grossman4ff14ba2012-02-08 16:37:41 -08005690// Reserve one of the limited slots for a timed audio track associated
5691// with this client
5692bool AudioFlinger::Client::reserveTimedTrack()
5693{
5694 const int kMaxTimedTracksPerClient = 4;
5695
5696 Mutex::Autolock _l(mTimedTrackLock);
5697
5698 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5699 ALOGW("can not create timed track - pid %d has exceeded the limit",
5700 mPid);
5701 return false;
5702 }
5703
5704 mTimedTrackCount++;
5705 return true;
5706}
5707
5708// Release a slot for a timed audio track
5709void AudioFlinger::Client::releaseTimedTrack()
5710{
5711 Mutex::Autolock _l(mTimedTrackLock);
5712 mTimedTrackCount--;
5713}
5714
Mathias Agopian65ab4712010-07-14 17:59:35 -07005715// ----------------------------------------------------------------------------
5716
5717AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5718 const sp<IAudioFlingerClient>& client,
5719 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005720 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005721{
5722}
5723
5724AudioFlinger::NotificationClient::~NotificationClient()
5725{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005726}
5727
5728void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5729{
5730 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005731 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005732}
5733
5734// ----------------------------------------------------------------------------
5735
5736AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5737 : BnAudioTrack(),
5738 mTrack(track)
5739{
5740}
5741
5742AudioFlinger::TrackHandle::~TrackHandle() {
5743 // just stop the track on deletion, associated resources
5744 // will be freed from the main thread once all pending buffers have
5745 // been played. Unless it's not in the active track list, in which
5746 // case we free everything now...
5747 mTrack->destroy();
5748}
5749
Glenn Kasten90716c52012-01-26 13:40:12 -08005750sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5751 return mTrack->getCblk();
5752}
5753
Glenn Kasten3acbd052012-02-28 10:39:56 -08005754status_t AudioFlinger::TrackHandle::start() {
5755 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005756}
5757
5758void AudioFlinger::TrackHandle::stop() {
5759 mTrack->stop();
5760}
5761
5762void AudioFlinger::TrackHandle::flush() {
5763 mTrack->flush();
5764}
5765
5766void AudioFlinger::TrackHandle::mute(bool e) {
5767 mTrack->mute(e);
5768}
5769
5770void AudioFlinger::TrackHandle::pause() {
5771 mTrack->pause();
5772}
5773
Mathias Agopian65ab4712010-07-14 17:59:35 -07005774status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5775{
5776 return mTrack->attachAuxEffect(EffectId);
5777}
5778
John Grossman4ff14ba2012-02-08 16:37:41 -08005779status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5780 sp<IMemory>* buffer) {
5781 if (!mTrack->isTimedTrack())
5782 return INVALID_OPERATION;
5783
5784 PlaybackThread::TimedTrack* tt =
5785 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5786 return tt->allocateTimedBuffer(size, buffer);
5787}
5788
5789status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5790 int64_t pts) {
5791 if (!mTrack->isTimedTrack())
5792 return INVALID_OPERATION;
5793
5794 PlaybackThread::TimedTrack* tt =
5795 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5796 return tt->queueTimedBuffer(buffer, pts);
5797}
5798
5799status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5800 const LinearTransform& xform, int target) {
5801
5802 if (!mTrack->isTimedTrack())
5803 return INVALID_OPERATION;
5804
5805 PlaybackThread::TimedTrack* tt =
5806 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5807 return tt->setMediaTimeTransform(
5808 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5809}
5810
Mathias Agopian65ab4712010-07-14 17:59:35 -07005811status_t AudioFlinger::TrackHandle::onTransact(
5812 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5813{
5814 return BnAudioTrack::onTransact(code, data, reply, flags);
5815}
5816
5817// ----------------------------------------------------------------------------
5818
5819sp<IAudioRecord> AudioFlinger::openRecord(
5820 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005821 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005822 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005823 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005824 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005825 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005826 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07005827 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005828 int *sessionId,
5829 status_t *status)
5830{
5831 sp<RecordThread::RecordTrack> recordTrack;
5832 sp<RecordHandle> recordHandle;
5833 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005834 status_t lStatus;
5835 RecordThread *thread;
5836 size_t inFrameCount;
5837 int lSessionId;
5838
5839 // check calling permissions
5840 if (!recordingAllowed()) {
5841 lStatus = PERMISSION_DENIED;
5842 goto Exit;
5843 }
5844
5845 // add client to list
5846 { // scope for mLock
5847 Mutex::Autolock _l(mLock);
5848 thread = checkRecordThread_l(input);
5849 if (thread == NULL) {
5850 lStatus = BAD_VALUE;
5851 goto Exit;
5852 }
5853
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005854 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005855
5856 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005857 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005858 lSessionId = *sessionId;
5859 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005860 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005861 if (sessionId != NULL) {
5862 *sessionId = lSessionId;
5863 }
5864 }
5865 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07005866 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5867 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005868 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005869 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005870 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5871 // destructor is called by the TrackBase destructor with mLock held
5872 client.clear();
5873 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005874 goto Exit;
5875 }
5876
5877 // return to handle to client
5878 recordHandle = new RecordHandle(recordTrack);
5879 lStatus = NO_ERROR;
5880
5881Exit:
5882 if (status) {
5883 *status = lStatus;
5884 }
5885 return recordHandle;
5886}
5887
5888// ----------------------------------------------------------------------------
5889
5890AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5891 : BnAudioRecord(),
5892 mRecordTrack(recordTrack)
5893{
5894}
5895
5896AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005897 stop_nonvirtual();
Glenn Kasten510a3d62012-07-16 14:24:34 -07005898 mRecordTrack->destroy();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005899}
5900
Glenn Kasten90716c52012-01-26 13:40:12 -08005901sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5902 return mRecordTrack->getCblk();
5903}
5904
Glenn Kasten0ec23ce2012-07-10 12:56:08 -07005905status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005906 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005907 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005908}
5909
5910void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005911 stop_nonvirtual();
5912}
5913
5914void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01005915 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005916 mRecordTrack->stop();
5917}
5918
Mathias Agopian65ab4712010-07-14 17:59:35 -07005919status_t AudioFlinger::RecordHandle::onTransact(
5920 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5921{
5922 return BnAudioRecord::onTransact(code, data, reply, flags);
5923}
5924
5925// ----------------------------------------------------------------------------
5926
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005927AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5928 AudioStreamIn *input,
5929 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07005930 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005931 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07005932 audio_devices_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005933 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten510a3d62012-07-16 14:24:34 -07005934 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005935 // mRsmpInIndex and mInputBytes set by readInputParameters()
Glenn Kasten254af182012-07-03 14:59:05 -07005936 mReqChannelCount(popcount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005937 mReqSampleRate(sampleRate)
5938 // mBytesRead is only meaningful while active, and so is cleared in start()
5939 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005940{
Glenn Kasten480b4682012-02-28 12:30:08 -08005941 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005942
Mathias Agopian65ab4712010-07-14 17:59:35 -07005943 readInputParameters();
5944}
5945
5946
5947AudioFlinger::RecordThread::~RecordThread()
5948{
5949 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005950 delete mResampler;
5951 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005952}
5953
5954void AudioFlinger::RecordThread::onFirstRef()
5955{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005956 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005957}
5958
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005959status_t AudioFlinger::RecordThread::readyToRun()
5960{
5961 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005962 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005963 return status;
5964}
5965
Mathias Agopian65ab4712010-07-14 17:59:35 -07005966bool AudioFlinger::RecordThread::threadLoop()
5967{
5968 AudioBufferProvider::Buffer buffer;
5969 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005970 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005971
Eric Laurent44d98482010-09-30 16:12:31 -07005972 nsecs_t lastWarning = 0;
5973
Glenn Kastene4e2a372012-07-23 12:55:09 -07005974 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07005975 acquireWakeLock();
5976
Mathias Agopian65ab4712010-07-14 17:59:35 -07005977 // start recording
5978 while (!exitPending()) {
5979
5980 processConfigEvents();
5981
5982 { // scope for mLock
5983 Mutex::Autolock _l(mLock);
5984 checkForNewParameters_l();
5985 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07005986 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005987
5988 if (exitPending()) break;
5989
Eric Laurentfeb0db62011-07-22 09:04:31 -07005990 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005991 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005992 // go to sleep
5993 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005994 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07005995 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005996 continue;
5997 }
5998 if (mActiveTrack != 0) {
5999 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006000 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006001 mActiveTrack.clear();
6002 mStartStopCond.broadcast();
6003 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6004 if (mReqChannelCount != mActiveTrack->channelCount()) {
6005 mActiveTrack.clear();
6006 mStartStopCond.broadcast();
6007 } else if (mBytesRead != 0) {
6008 // record start succeeds only if first read from audio input
6009 // succeeds
6010 if (mBytesRead > 0) {
6011 mActiveTrack->mState = TrackBase::ACTIVE;
6012 } else {
6013 mActiveTrack.clear();
6014 }
6015 mStartStopCond.broadcast();
6016 }
6017 mStandby = false;
Glenn Kasten510a3d62012-07-16 14:24:34 -07006018 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
6019 removeTrack_l(mActiveTrack);
6020 mActiveTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006021 }
6022 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006023 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006024 }
6025
6026 if (mActiveTrack != 0) {
6027 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6028 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006029 unlockEffectChains(effectChains);
6030 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006031 continue;
6032 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006033 for (size_t i = 0; i < effectChains.size(); i ++) {
6034 effectChains[i]->process_l();
6035 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006036
Mathias Agopian65ab4712010-07-14 17:59:35 -07006037 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006038 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006039 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006040 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006041 // no resampling
6042 while (framesOut) {
6043 size_t framesIn = mFrameCount - mRsmpInIndex;
6044 if (framesIn) {
6045 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6046 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6047 if (framesIn > framesOut)
6048 framesIn = framesOut;
6049 mRsmpInIndex += framesIn;
6050 framesOut -= framesIn;
6051 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006052 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006053 memcpy(dst, src, framesIn * mFrameSize);
6054 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006055 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006056 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6057 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006058 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006059 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6060 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006061 }
6062 }
6063 }
6064 if (framesOut && mFrameCount == mRsmpInIndex) {
6065 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006066 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006067 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006068 framesOut = 0;
6069 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006070 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006071 mRsmpInIndex = 0;
6072 }
6073 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006074 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006075 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6076 // Force input into standby so that it tries to
6077 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006078 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006079 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006080 }
6081 mRsmpInIndex = mFrameCount;
6082 framesOut = 0;
6083 buffer.frameCount = 0;
6084 }
6085 }
6086 }
6087 } else {
6088 // resampling
6089
6090 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6091 // alter output frame count as if we were expecting stereo samples
6092 if (mChannelCount == 1 && mReqChannelCount == 1) {
6093 framesOut >>= 1;
6094 }
6095 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6096 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6097 // are 32 bit aligned which should be always true.
6098 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006099 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006100 // the resampler always outputs stereo samples: do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006101 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6102 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006103 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006104 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006105 }
6106
6107 }
Eric Laurenta011e352012-03-29 15:51:43 -07006108 if (mFramestoDrop == 0) {
6109 mActiveTrack->releaseBuffer(&buffer);
6110 } else {
6111 if (mFramestoDrop > 0) {
6112 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006113 if (mFramestoDrop <= 0) {
6114 clearSyncStartEvent();
6115 }
6116 } else {
6117 mFramestoDrop += buffer.frameCount;
6118 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6119 mSyncStartEvent->isCancelled()) {
6120 ALOGW("Synced record %s, session %d, trigger session %d",
6121 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6122 mActiveTrack->sessionId(),
6123 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6124 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006125 }
6126 }
6127 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006128 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006129 }
6130 // client isn't retrieving buffers fast enough
6131 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006132 if (!mActiveTrack->setOverflow()) {
6133 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006134 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006135 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006136 lastWarning = now;
6137 }
6138 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006139 // Release the processor for a while before asking for a new buffer.
6140 // This will give the application more chance to read from the buffer and
6141 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006142 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006143 }
6144 }
Eric Laurentec437d82011-07-26 20:54:46 -07006145 // enable changes in effect chain
6146 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006147 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006148 }
6149
Glenn Kastene4e2a372012-07-23 12:55:09 -07006150 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006151
Glenn Kasten33e6e352012-07-16 15:56:57 -07006152 {
6153 Mutex::Autolock _l(mLock);
6154 mActiveTrack.clear();
6155 mStartStopCond.broadcast();
6156 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006157
Eric Laurentfeb0db62011-07-22 09:04:31 -07006158 releaseWakeLock();
6159
Steve Block3856b092011-10-20 11:56:00 +01006160 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006161 return false;
6162}
6163
Glenn Kastene4e2a372012-07-23 12:55:09 -07006164void AudioFlinger::RecordThread::standby()
6165{
6166 if (!mStandby) {
6167 inputStandBy();
6168 mStandby = true;
6169 }
6170}
6171
6172void AudioFlinger::RecordThread::inputStandBy()
6173{
6174 mInput->stream->common.standby(&mInput->stream->common);
6175}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006176
6177sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6178 const sp<AudioFlinger::Client>& client,
6179 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006180 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006181 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006182 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006183 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006184 IAudioFlinger::track_flags_t flags,
6185 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006186 status_t *status)
6187{
6188 sp<RecordTrack> track;
6189 status_t lStatus;
6190
6191 lStatus = initCheck();
6192 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006193 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006194 goto Exit;
6195 }
6196
Glenn Kasten1879fff2012-07-11 15:36:59 -07006197 // FIXME use flags and tid similar to createTrack_l()
6198
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006199 { // scope for mLock
6200 Mutex::Autolock _l(mLock);
6201
6202 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006203 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006204
Glenn Kasten7378ca52012-01-20 13:44:40 -08006205 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006206 lStatus = NO_MEMORY;
6207 goto Exit;
6208 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006209 mTracks.add(track);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006210
Eric Laurent59bd0da2011-08-01 09:52:20 -07006211 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006212 bool suspend = audio_is_bluetooth_sco_device(mDevice & AUDIO_DEVICE_IN_ALL) &&
6213 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006214 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6215 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006216 }
6217 lStatus = NO_ERROR;
6218
6219Exit:
6220 if (status) {
6221 *status = lStatus;
6222 }
6223 return track;
6224}
6225
Eric Laurenta011e352012-03-29 15:51:43 -07006226status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006227 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006228 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006229{
Glenn Kasten58912562012-04-03 10:45:00 -07006230 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006231 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006232 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006233
6234 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006235 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006236 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6237 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6238 triggerSession,
6239 recordTrack->sessionId(),
6240 syncStartEventCallback,
6241 this);
Eric Laurent29864602012-05-08 18:57:51 -07006242 // Sync event can be cancelled by the trigger session if the track is not in a
6243 // compatible state in which case we start record immediately
6244 if (mSyncStartEvent->isCancelled()) {
6245 clearSyncStartEvent();
6246 } else {
6247 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6248 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6249 }
Eric Laurenta011e352012-03-29 15:51:43 -07006250 }
6251
Mathias Agopian65ab4712010-07-14 17:59:35 -07006252 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006253 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006254 if (mActiveTrack != 0) {
6255 if (recordTrack != mActiveTrack.get()) {
6256 status = -EBUSY;
6257 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6258 mActiveTrack->mState = TrackBase::ACTIVE;
6259 }
6260 return status;
6261 }
6262
6263 recordTrack->mState = TrackBase::IDLE;
6264 mActiveTrack = recordTrack;
6265 mLock.unlock();
6266 status_t status = AudioSystem::startInput(mId);
6267 mLock.lock();
6268 if (status != NO_ERROR) {
6269 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006270 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006271 return status;
6272 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006273 mRsmpInIndex = mFrameCount;
6274 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006275 if (mResampler != NULL) {
6276 mResampler->reset();
6277 }
6278 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006279 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006280 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006281 mWaitWorkCV.signal();
6282 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006283 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006284 mActiveTrack.clear();
6285 status = INVALID_OPERATION;
6286 goto startError;
6287 }
6288 mStartStopCond.wait(mLock);
6289 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006290 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006291 status = BAD_VALUE;
6292 goto startError;
6293 }
Steve Block3856b092011-10-20 11:56:00 +01006294 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006295 return status;
6296 }
6297startError:
6298 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006299 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006300 return status;
6301}
6302
Eric Laurenta011e352012-03-29 15:51:43 -07006303void AudioFlinger::RecordThread::clearSyncStartEvent()
6304{
6305 if (mSyncStartEvent != 0) {
6306 mSyncStartEvent->cancel();
6307 }
6308 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006309 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006310}
6311
6312void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6313{
6314 sp<SyncEvent> strongEvent = event.promote();
6315
6316 if (strongEvent != 0) {
6317 RecordThread *me = (RecordThread *)strongEvent->cookie();
6318 me->handleSyncStartEvent(strongEvent);
6319 }
6320}
6321
6322void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6323{
Eric Laurent29864602012-05-08 18:57:51 -07006324 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006325 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6326 // from audio HAL
6327 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006328 }
6329}
6330
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006331bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006332 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006333 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
6334 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006335 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006336 recordTrack->mState = TrackBase::PAUSING;
6337 // do not wait for mStartStopCond if exiting
6338 if (exitPending()) {
6339 return true;
6340 }
6341 mStartStopCond.wait(mLock);
6342 // if we have been restarted, recordTrack == mActiveTrack.get() here
6343 if (exitPending() || recordTrack != mActiveTrack.get()) {
6344 ALOGV("Record stopped OK");
6345 return true;
6346 }
6347 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006348}
6349
Eric Laurenta011e352012-03-29 15:51:43 -07006350bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event)
6351{
6352 return false;
6353}
6354
6355status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6356{
6357 if (!isValidSyncEvent(event)) {
6358 return BAD_VALUE;
6359 }
6360
Glenn Kasten510a3d62012-07-16 14:24:34 -07006361 int eventSession = event->triggerSession();
6362 status_t ret = NAME_NOT_FOUND;
6363
Eric Laurenta011e352012-03-29 15:51:43 -07006364 Mutex::Autolock _l(mLock);
6365
Glenn Kasten510a3d62012-07-16 14:24:34 -07006366 for (size_t i = 0; i < mTracks.size(); i++) {
6367 sp<RecordTrack> track = mTracks[i];
6368 if (eventSession == track->sessionId()) {
6369 track->setSyncEvent(event);
6370 ret = NO_ERROR;
6371 }
Eric Laurenta011e352012-03-29 15:51:43 -07006372 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006373 return ret;
6374}
6375
6376void AudioFlinger::RecordThread::RecordTrack::destroy()
6377{
6378 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
6379 sp<RecordTrack> keep(this);
6380 {
6381 sp<ThreadBase> thread = mThread.promote();
6382 if (thread != 0) {
6383 if (mState == ACTIVE || mState == RESUMING) {
6384 AudioSystem::stopInput(thread->id());
6385 }
6386 AudioSystem::releaseInput(thread->id());
6387 Mutex::Autolock _l(thread->mLock);
6388 RecordThread *recordThread = (RecordThread *) thread.get();
6389 recordThread->destroyTrack_l(this);
6390 }
6391 }
6392}
6393
6394// destroyTrack_l() must be called with ThreadBase::mLock held
6395void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6396{
6397 track->mState = TrackBase::TERMINATED;
6398 // active tracks are removed by threadLoop()
6399 if (mActiveTrack != track) {
6400 removeTrack_l(track);
6401 }
6402}
6403
6404void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6405{
6406 mTracks.remove(track);
6407 // need anything related to effects here?
Eric Laurenta011e352012-03-29 15:51:43 -07006408}
6409
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07006410void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006411{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006412 dumpInternals(fd, args);
6413 dumpTracks(fd, args);
6414 dumpEffectChains(fd, args);
6415}
6416
6417void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6418{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006419 const size_t SIZE = 256;
6420 char buffer[SIZE];
6421 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006422
6423 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6424 result.append(buffer);
6425
6426 if (mActiveTrack != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006427 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6428 result.append(buffer);
6429 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6430 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006431 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006432 result.append(buffer);
6433 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6434 result.append(buffer);
6435 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6436 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006437 } else {
Glenn Kasten510a3d62012-07-16 14:24:34 -07006438 result.append("No active record client\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006439 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006440
Mathias Agopian65ab4712010-07-14 17:59:35 -07006441 write(fd, result.string(), result.size());
6442
6443 dumpBase(fd, args);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006444}
6445
6446void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
6447{
6448 const size_t SIZE = 256;
6449 char buffer[SIZE];
6450 String8 result;
6451
6452 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
6453 result.append(buffer);
6454 RecordTrack::appendDumpHeader(result);
6455 for (size_t i = 0; i < mTracks.size(); ++i) {
6456 sp<RecordTrack> track = mTracks[i];
6457 if (track != 0) {
6458 track->dump(buffer, SIZE);
6459 result.append(buffer);
6460 }
6461 }
6462
6463 if (mActiveTrack != 0) {
6464 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
6465 result.append(buffer);
6466 RecordTrack::appendDumpHeader(result);
6467 mActiveTrack->dump(buffer, SIZE);
6468 result.append(buffer);
6469
6470 }
6471 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006472}
6473
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006474// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006475status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006476{
6477 size_t framesReq = buffer->frameCount;
6478 size_t framesReady = mFrameCount - mRsmpInIndex;
6479 int channelCount;
6480
6481 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006482 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006483 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006484 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006485 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6486 // Force input into standby so that it tries to
6487 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006488 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006489 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006490 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006491 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006492 buffer->frameCount = 0;
6493 return NOT_ENOUGH_DATA;
6494 }
6495 mRsmpInIndex = 0;
6496 framesReady = mFrameCount;
6497 }
6498
6499 if (framesReq > framesReady) {
6500 framesReq = framesReady;
6501 }
6502
6503 if (mChannelCount == 1 && mReqChannelCount == 2) {
6504 channelCount = 1;
6505 } else {
6506 channelCount = 2;
6507 }
6508 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6509 buffer->frameCount = framesReq;
6510 return NO_ERROR;
6511}
6512
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006513// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006514void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6515{
6516 mRsmpInIndex += buffer->frameCount;
6517 buffer->frameCount = 0;
6518}
6519
6520bool AudioFlinger::RecordThread::checkForNewParameters_l()
6521{
6522 bool reconfig = false;
6523
6524 while (!mNewParameters.isEmpty()) {
6525 status_t status = NO_ERROR;
6526 String8 keyValuePair = mNewParameters[0];
6527 AudioParameter param = AudioParameter(keyValuePair);
6528 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006529 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006530 int reqSamplingRate = mReqSampleRate;
6531 int reqChannelCount = mReqChannelCount;
6532
6533 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6534 reqSamplingRate = value;
6535 reconfig = true;
6536 }
6537 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006538 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006539 reconfig = true;
6540 }
6541 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006542 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006543 reconfig = true;
6544 }
6545 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6546 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006547 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006548 // if frame count is changed after track creation
6549 if (mActiveTrack != 0) {
6550 status = INVALID_OPERATION;
6551 } else {
6552 reconfig = true;
6553 }
6554 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006555 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6556 // forward device change to effects that have requested to be
6557 // aware of attached audio device.
6558 for (size_t i = 0; i < mEffectChains.size(); i++) {
6559 mEffectChains[i]->setDevice_l(value);
6560 }
6561 // store input device and output device but do not forward output device to audio HAL.
6562 // Note that status is ignored by the caller for output device
6563 // (see AudioFlinger::setParameters()
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006564 audio_devices_t newDevice = mDevice;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006565 if (value & AUDIO_DEVICE_OUT_ALL) {
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006566 newDevice &= ~(value & AUDIO_DEVICE_OUT_ALL);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006567 status = BAD_VALUE;
6568 } else {
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006569 newDevice &= ~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006570 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kasten510a3d62012-07-16 14:24:34 -07006571 if (mTracks.size() > 0) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07006572 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006573 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006574 for (size_t i = 0; i < mTracks.size(); i++) {
6575 sp<RecordTrack> track = mTracks[i];
6576 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6577 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6578 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07006579 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006580 }
Glenn Kasten01542f22012-07-02 12:46:15 -07006581 newDevice |= value;
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006582 mDevice = newDevice; // since mDevice is read by other threads, only write to it once
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006583 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006584 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006585 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006586 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006587 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006588 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6589 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006590 }
6591 if (reconfig) {
6592 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006593 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006594 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006595 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006596 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6597 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006598 status = NO_ERROR;
6599 }
6600 if (status == NO_ERROR) {
6601 readInputParameters();
6602 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6603 }
6604 }
6605 }
6606
6607 mNewParameters.removeAt(0);
6608
6609 mParamStatus = status;
6610 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006611 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6612 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006613 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006614 }
6615 return reconfig;
6616}
6617
6618String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6619{
Dima Zavinfce7a472011-04-19 22:30:36 -07006620 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006621 String8 out_s8 = String8();
6622
6623 Mutex::Autolock _l(mLock);
6624 if (initCheck() != NO_ERROR) {
6625 return out_s8;
6626 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006627
Dima Zavin799a70e2011-04-18 16:57:27 -07006628 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006629 out_s8 = String8(s);
6630 free(s);
6631 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006632}
6633
6634void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6635 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006636 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006637
6638 switch (event) {
6639 case AudioSystem::INPUT_OPENED:
6640 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006641 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006642 desc.samplingRate = mSampleRate;
6643 desc.format = mFormat;
6644 desc.frameCount = mFrameCount;
6645 desc.latency = 0;
6646 param2 = &desc;
6647 break;
6648
6649 case AudioSystem::INPUT_CLOSED:
6650 default:
6651 break;
6652 }
6653 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6654}
6655
6656void AudioFlinger::RecordThread::readInputParameters()
6657{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006658 delete mRsmpInBuffer;
6659 // mRsmpInBuffer is always assigned a new[] below
6660 delete mRsmpOutBuffer;
6661 mRsmpOutBuffer = NULL;
6662 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006663 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006664
Dima Zavin799a70e2011-04-18 16:57:27 -07006665 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006666 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6667 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006668 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006669 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006670 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006671 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006672 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006673 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6674
Glenn Kasten53d76db2012-03-08 12:32:47 -08006675 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006676 {
6677 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006678 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6679 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006680 if (mChannelCount == 1 && mReqChannelCount == 2) {
6681 channelCount = 1;
6682 } else {
6683 channelCount = 2;
6684 }
6685 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6686 mResampler->setSampleRate(mSampleRate);
6687 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6688 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6689
6690 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6691 if (mChannelCount == 1 && mReqChannelCount == 1) {
6692 mFrameCount >>= 1;
6693 }
6694
6695 }
6696 mRsmpInIndex = mFrameCount;
6697}
6698
6699unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6700{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006701 Mutex::Autolock _l(mLock);
6702 if (initCheck() != NO_ERROR) {
6703 return 0;
6704 }
6705
Dima Zavin799a70e2011-04-18 16:57:27 -07006706 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006707}
6708
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006709uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
6710{
6711 Mutex::Autolock _l(mLock);
6712 uint32_t result = 0;
6713 if (getEffectChain_l(sessionId) != 0) {
6714 result = EFFECT_SESSION;
6715 }
6716
Glenn Kasten510a3d62012-07-16 14:24:34 -07006717 for (size_t i = 0; i < mTracks.size(); ++i) {
6718 if (sessionId == mTracks[i]->sessionId()) {
6719 result |= TRACK_SESSION;
6720 break;
6721 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006722 }
6723
6724 return result;
6725}
6726
Glenn Kasten510a3d62012-07-16 14:24:34 -07006727KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds()
Eric Laurent59bd0da2011-08-01 09:52:20 -07006728{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006729 KeyedVector<int, bool> ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006730 Mutex::Autolock _l(mLock);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006731 for (size_t j = 0; j < mTracks.size(); ++j) {
6732 sp<RecordThread::RecordTrack> track = mTracks[j];
6733 int sessionId = track->sessionId();
6734 if (ids.indexOfKey(sessionId) < 0) {
6735 ids.add(sessionId, true);
6736 }
6737 }
6738 return ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006739}
6740
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006741AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6742{
6743 Mutex::Autolock _l(mLock);
6744 AudioStreamIn *input = mInput;
6745 mInput = NULL;
6746 return input;
6747}
6748
6749// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006750audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006751{
6752 if (mInput == NULL) {
6753 return NULL;
6754 }
6755 return &mInput->stream->common;
6756}
6757
6758
Mathias Agopian65ab4712010-07-14 17:59:35 -07006759// ----------------------------------------------------------------------------
6760
Eric Laurenta4c5a552012-03-29 10:12:40 -07006761audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6762{
6763 if (!settingsAllowed()) {
6764 return 0;
6765 }
6766 Mutex::Autolock _l(mLock);
6767 return loadHwModule_l(name);
6768}
6769
6770// loadHwModule_l() must be called with AudioFlinger::mLock held
6771audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6772{
6773 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6774 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6775 ALOGW("loadHwModule() module %s already loaded", name);
6776 return mAudioHwDevs.keyAt(i);
6777 }
6778 }
6779
Eric Laurenta4c5a552012-03-29 10:12:40 -07006780 audio_hw_device_t *dev;
6781
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006782 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006783 if (rc) {
6784 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6785 return 0;
6786 }
6787
6788 mHardwareStatus = AUDIO_HW_INIT;
6789 rc = dev->init_check(dev);
6790 mHardwareStatus = AUDIO_HW_IDLE;
6791 if (rc) {
6792 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6793 return 0;
6794 }
6795
John Grossmanee578c02012-07-23 17:05:46 -07006796 // Check and cache this HAL's level of support for master mute and master
6797 // volume. If this is the first HAL opened, and it supports the get
6798 // methods, use the initial values provided by the HAL as the current
6799 // master mute and volume settings.
6800
6801 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
6802 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07006803 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07006804
6805 if (0 == mAudioHwDevs.size()) {
6806 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6807 if (NULL != dev->get_master_volume) {
6808 float mv;
6809 if (OK == dev->get_master_volume(dev, &mv)) {
6810 mMasterVolume = mv;
6811 }
6812 }
6813
6814 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
6815 if (NULL != dev->get_master_mute) {
6816 bool mm;
6817 if (OK == dev->get_master_mute(dev, &mm)) {
6818 mMasterMute = mm;
6819 }
6820 }
6821 }
6822
Eric Laurenta4c5a552012-03-29 10:12:40 -07006823 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07006824 if ((NULL != dev->set_master_volume) &&
6825 (OK == dev->set_master_volume(dev, mMasterVolume))) {
6826 flags = static_cast<AudioHwDevice::Flags>(flags |
6827 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
6828 }
6829
6830 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
6831 if ((NULL != dev->set_master_mute) &&
6832 (OK == dev->set_master_mute(dev, mMasterMute))) {
6833 flags = static_cast<AudioHwDevice::Flags>(flags |
6834 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
6835 }
6836
Eric Laurenta4c5a552012-03-29 10:12:40 -07006837 mHardwareStatus = AUDIO_HW_IDLE;
6838 }
6839
6840 audio_module_handle_t handle = nextUniqueId();
John Grossmanee578c02012-07-23 17:05:46 -07006841 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07006842
6843 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006844 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006845
6846 return handle;
6847
6848}
6849
6850audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6851 audio_devices_t *pDevices,
6852 uint32_t *pSamplingRate,
6853 audio_format_t *pFormat,
6854 audio_channel_mask_t *pChannelMask,
6855 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006856 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006857{
6858 status_t status;
6859 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006860 struct audio_config config = {
6861 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6862 channel_mask: pChannelMask ? *pChannelMask : 0,
6863 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6864 };
6865 audio_stream_out_t *outStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07006866 AudioHwDevice *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006867
Eric Laurenta4c5a552012-03-29 10:12:40 -07006868 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6869 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006870 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006871 config.sample_rate,
6872 config.format,
6873 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006874 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006875
6876 if (pDevices == NULL || *pDevices == 0) {
6877 return 0;
6878 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006879
Mathias Agopian65ab4712010-07-14 17:59:35 -07006880 Mutex::Autolock _l(mLock);
6881
Eric Laurenta4c5a552012-03-29 10:12:40 -07006882 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006883 if (outHwDev == NULL)
6884 return 0;
6885
John Grossmanee578c02012-07-23 17:05:46 -07006886 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006887 audio_io_handle_t id = nextUniqueId();
6888
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006889 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006890
John Grossmanee578c02012-07-23 17:05:46 -07006891 status = hwDevHal->open_output_stream(hwDevHal,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006892 id,
6893 *pDevices,
6894 (audio_output_flags_t)flags,
6895 &config,
6896 &outStream);
6897
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006898 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006899 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006900 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006901 config.sample_rate,
6902 config.format,
6903 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006904 status);
6905
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006906 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006907 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006908
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006909 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006910 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6911 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006912 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006913 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006914 } else {
6915 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006916 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006917 }
6918 mPlaybackThreads.add(id, thread);
6919
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006920 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6921 if (pFormat != NULL) *pFormat = config.format;
6922 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006923 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006924
6925 // notify client processes of the new output creation
6926 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006927
6928 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006929 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006930 ALOGI("Using module %d has the primary audio interface", module);
6931 mPrimaryHardwareDev = outHwDev;
6932
6933 AutoMutex lock(mHardwareLock);
6934 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -07006935 hwDevHal->set_mode(hwDevHal, mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006936 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006937 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006938 return id;
6939 }
6940
6941 return 0;
6942}
6943
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006944audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6945 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006946{
6947 Mutex::Autolock _l(mLock);
6948 MixerThread *thread1 = checkMixerThread_l(output1);
6949 MixerThread *thread2 = checkMixerThread_l(output2);
6950
6951 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006952 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006953 return 0;
6954 }
6955
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006956 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006957 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6958 thread->addOutputTrack(thread2);
6959 mPlaybackThreads.add(id, thread);
6960 // notify client processes of the new output creation
6961 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6962 return id;
6963}
6964
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006965status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006966{
Glenn Kastend96c5722012-04-25 13:44:49 -07006967 return closeOutput_nonvirtual(output);
6968}
6969
6970status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
6971{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006972 // keep strong reference on the playback thread so that
6973 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006974 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006975 {
6976 Mutex::Autolock _l(mLock);
6977 thread = checkPlaybackThread_l(output);
6978 if (thread == NULL) {
6979 return BAD_VALUE;
6980 }
6981
Steve Block3856b092011-10-20 11:56:00 +01006982 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006983
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006984 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006985 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006986 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006987 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6988 dupThread->removeOutputTrack((MixerThread *)thread.get());
6989 }
6990 }
6991 }
Glenn Kastena1117922012-01-26 10:53:32 -08006992 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006993 mPlaybackThreads.removeItem(output);
6994 }
6995 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08006996 // The thread entity (active unit of execution) is no longer running here,
6997 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006998
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006999 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007000 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007001 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007002 // from now on thread->mOutput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007003 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007004 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007005 }
7006 return NO_ERROR;
7007}
7008
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007009status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007010{
7011 Mutex::Autolock _l(mLock);
7012 PlaybackThread *thread = checkPlaybackThread_l(output);
7013
7014 if (thread == NULL) {
7015 return BAD_VALUE;
7016 }
7017
Steve Block3856b092011-10-20 11:56:00 +01007018 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007019 thread->suspend();
7020
7021 return NO_ERROR;
7022}
7023
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007024status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007025{
7026 Mutex::Autolock _l(mLock);
7027 PlaybackThread *thread = checkPlaybackThread_l(output);
7028
7029 if (thread == NULL) {
7030 return BAD_VALUE;
7031 }
7032
Steve Block3856b092011-10-20 11:56:00 +01007033 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007034
7035 thread->restore();
7036
7037 return NO_ERROR;
7038}
7039
Eric Laurenta4c5a552012-03-29 10:12:40 -07007040audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
7041 audio_devices_t *pDevices,
7042 uint32_t *pSamplingRate,
7043 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07007044 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007045{
7046 status_t status;
7047 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007048 struct audio_config config = {
7049 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7050 channel_mask: pChannelMask ? *pChannelMask : 0,
7051 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7052 };
7053 uint32_t reqSamplingRate = config.sample_rate;
7054 audio_format_t reqFormat = config.format;
7055 audio_channel_mask_t reqChannels = config.channel_mask;
7056 audio_stream_in_t *inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007057 AudioHwDevice *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007058
7059 if (pDevices == NULL || *pDevices == 0) {
7060 return 0;
7061 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007062
Mathias Agopian65ab4712010-07-14 17:59:35 -07007063 Mutex::Autolock _l(mLock);
7064
Eric Laurenta4c5a552012-03-29 10:12:40 -07007065 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007066 if (inHwDev == NULL)
7067 return 0;
7068
John Grossmanee578c02012-07-23 17:05:46 -07007069 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007070 audio_io_handle_t id = nextUniqueId();
7071
John Grossmanee578c02012-07-23 17:05:46 -07007072 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007073 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007074 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007075 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007076 config.sample_rate,
7077 config.format,
7078 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007079 status);
7080
7081 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7082 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7083 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007084 if (status == BAD_VALUE &&
7085 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7086 (config.sample_rate <= 2 * reqSamplingRate) &&
7087 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007088 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007089 inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007090 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007091 }
7092
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007093 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007094 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7095
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007096 // Start record thread
7097 // RecorThread require both input and output device indication to forward to audio
7098 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007099 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007100 thread = new RecordThread(this,
7101 input,
7102 reqSamplingRate,
7103 reqChannels,
7104 id,
7105 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007106 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007107 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007108 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007109 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007110 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007111
Mathias Agopian65ab4712010-07-14 17:59:35 -07007112 // notify client processes of the new input creation
7113 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7114 return id;
7115 }
7116
7117 return 0;
7118}
7119
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007120status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007121{
Glenn Kastend96c5722012-04-25 13:44:49 -07007122 return closeInput_nonvirtual(input);
7123}
7124
7125status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7126{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007127 // keep strong reference on the record thread so that
7128 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007129 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007130 {
7131 Mutex::Autolock _l(mLock);
7132 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007133 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007134 return BAD_VALUE;
7135 }
7136
Steve Block3856b092011-10-20 11:56:00 +01007137 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007138 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007139 mRecordThreads.removeItem(input);
7140 }
7141 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007142 // The thread entity (active unit of execution) is no longer running here,
7143 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007144
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007145 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007146 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007147 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007148 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007149 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007150
7151 return NO_ERROR;
7152}
7153
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007154status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007155{
7156 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007157 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007158
7159 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7160 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007161 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007162 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007163
7164 return NO_ERROR;
7165}
7166
7167
7168int AudioFlinger::newAudioSessionId()
7169{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007170 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007171}
7172
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007173void AudioFlinger::acquireAudioSessionId(int audioSession)
7174{
7175 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007176 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007177 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007178 size_t num = mAudioSessionRefs.size();
7179 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007180 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007181 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7182 ref->mCnt++;
7183 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007184 return;
7185 }
7186 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007187 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7188 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007189}
7190
7191void AudioFlinger::releaseAudioSessionId(int audioSession)
7192{
7193 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007194 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007195 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007196 size_t num = mAudioSessionRefs.size();
7197 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007198 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007199 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7200 ref->mCnt--;
7201 ALOGV(" decremented refcount to %d", ref->mCnt);
7202 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007203 mAudioSessionRefs.removeAt(i);
7204 delete ref;
7205 purgeStaleEffects_l();
7206 }
7207 return;
7208 }
7209 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007210 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007211}
7212
7213void AudioFlinger::purgeStaleEffects_l() {
7214
Steve Block3856b092011-10-20 11:56:00 +01007215 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007216
7217 Vector< sp<EffectChain> > chains;
7218
7219 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7220 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7221 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7222 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007223 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7224 chains.push(ec);
7225 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007226 }
7227 }
7228 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7229 sp<RecordThread> t = mRecordThreads.valueAt(i);
7230 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7231 sp<EffectChain> ec = t->mEffectChains[j];
7232 chains.push(ec);
7233 }
7234 }
7235
7236 for (size_t i = 0; i < chains.size(); i++) {
7237 sp<EffectChain> ec = chains[i];
7238 int sessionid = ec->sessionId();
7239 sp<ThreadBase> t = ec->mThread.promote();
7240 if (t == 0) {
7241 continue;
7242 }
7243 size_t numsessionrefs = mAudioSessionRefs.size();
7244 bool found = false;
7245 for (size_t k = 0; k < numsessionrefs; k++) {
7246 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007247 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007248 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007249 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007250 found = true;
7251 break;
7252 }
7253 }
7254 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007255 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007256 // remove all effects from the chain
7257 while (ec->mEffects.size()) {
7258 sp<EffectModule> effect = ec->mEffects[0];
7259 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007260 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007261 if (effect->purgeHandles()) {
7262 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007263 }
7264 AudioSystem::unregisterEffect(effect->id());
7265 }
7266 }
7267 }
7268 return;
7269}
7270
Mathias Agopian65ab4712010-07-14 17:59:35 -07007271// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007272AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007273{
Glenn Kastena1117922012-01-26 10:53:32 -08007274 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007275}
7276
7277// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007278AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007279{
7280 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007281 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007282}
7283
7284// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007285AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007286{
Glenn Kastena1117922012-01-26 10:53:32 -08007287 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007288}
7289
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007290uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007291{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007292 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007293}
7294
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007295AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007296{
7297 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7298 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007299 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07007300 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007301 return thread;
7302 }
7303 }
7304 return NULL;
7305}
7306
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007307audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007308{
7309 PlaybackThread *thread = primaryPlaybackThread_l();
7310
7311 if (thread == NULL) {
7312 return 0;
7313 }
7314
7315 return thread->device();
7316}
7317
Eric Laurenta011e352012-03-29 15:51:43 -07007318sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7319 int triggerSession,
7320 int listenerSession,
7321 sync_event_callback_t callBack,
7322 void *cookie)
7323{
7324 Mutex::Autolock _l(mLock);
7325
7326 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7327 status_t playStatus = NAME_NOT_FOUND;
7328 status_t recStatus = NAME_NOT_FOUND;
7329 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7330 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7331 if (playStatus == NO_ERROR) {
7332 return event;
7333 }
7334 }
7335 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7336 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7337 if (recStatus == NO_ERROR) {
7338 return event;
7339 }
7340 }
7341 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7342 mPendingSyncEvents.add(event);
7343 } else {
7344 ALOGV("createSyncEvent() invalid event %d", event->type());
7345 event.clear();
7346 }
7347 return event;
7348}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007349
Mathias Agopian65ab4712010-07-14 17:59:35 -07007350// ----------------------------------------------------------------------------
7351// Effect management
7352// ----------------------------------------------------------------------------
7353
7354
Glenn Kastenf587ba52012-01-26 16:25:10 -08007355status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007356{
7357 Mutex::Autolock _l(mLock);
7358 return EffectQueryNumberEffects(numEffects);
7359}
7360
Glenn Kastenf587ba52012-01-26 16:25:10 -08007361status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007362{
7363 Mutex::Autolock _l(mLock);
7364 return EffectQueryEffect(index, descriptor);
7365}
7366
Glenn Kasten5e92a782012-01-30 07:40:52 -08007367status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007368 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007369{
7370 Mutex::Autolock _l(mLock);
7371 return EffectGetDescriptor(pUuid, descriptor);
7372}
7373
7374
Mathias Agopian65ab4712010-07-14 17:59:35 -07007375sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7376 effect_descriptor_t *pDesc,
7377 const sp<IEffectClient>& effectClient,
7378 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007379 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007380 int sessionId,
7381 status_t *status,
7382 int *id,
7383 int *enabled)
7384{
7385 status_t lStatus = NO_ERROR;
7386 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007387 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007388
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007389 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007390 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007391
7392 if (pDesc == NULL) {
7393 lStatus = BAD_VALUE;
7394 goto Exit;
7395 }
7396
Eric Laurent84e9a102010-09-23 16:10:16 -07007397 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007398 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007399 lStatus = PERMISSION_DENIED;
7400 goto Exit;
7401 }
7402
Dima Zavinfce7a472011-04-19 22:30:36 -07007403 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007404 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007405 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007406 lStatus = PERMISSION_DENIED;
7407 goto Exit;
7408 }
7409
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007410 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007411 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007412 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007413 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007414 lStatus = BAD_VALUE;
7415 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007416 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007417 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007418 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007419 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007420 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007421 }
7422 }
7423
Mathias Agopian65ab4712010-07-14 17:59:35 -07007424 {
7425 Mutex::Autolock _l(mLock);
7426
Mathias Agopian65ab4712010-07-14 17:59:35 -07007427
7428 if (!EffectIsNullUuid(&pDesc->uuid)) {
7429 // if uuid is specified, request effect descriptor
7430 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7431 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007432 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007433 goto Exit;
7434 }
7435 } else {
7436 // if uuid is not specified, look for an available implementation
7437 // of the required type in effect factory
7438 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007439 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007440 lStatus = BAD_VALUE;
7441 goto Exit;
7442 }
7443 uint32_t numEffects = 0;
7444 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007445 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007446 bool found = false;
7447
7448 lStatus = EffectQueryNumberEffects(&numEffects);
7449 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007450 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007451 goto Exit;
7452 }
7453 for (uint32_t i = 0; i < numEffects; i++) {
7454 lStatus = EffectQueryEffect(i, &desc);
7455 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007456 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007457 continue;
7458 }
7459 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7460 // If matching type found save effect descriptor. If the session is
7461 // 0 and the effect is not auxiliary, continue enumeration in case
7462 // an auxiliary version of this effect type is available
7463 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08007464 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07007465 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007466 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7467 break;
7468 }
7469 }
7470 }
7471 if (!found) {
7472 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007473 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007474 goto Exit;
7475 }
7476 // For same effect type, chose auxiliary version over insert version if
7477 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007478 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007479 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08007480 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007481 }
7482 }
7483
7484 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007485 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007486 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7487 lStatus = INVALID_OPERATION;
7488 goto Exit;
7489 }
7490
Eric Laurent59255e42011-07-27 19:49:51 -07007491 // check recording permission for visualizer
7492 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7493 !recordingAllowed()) {
7494 lStatus = PERMISSION_DENIED;
7495 goto Exit;
7496 }
7497
Mathias Agopian65ab4712010-07-14 17:59:35 -07007498 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08007499 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007500
7501 // If output is not specified try to find a matching audio session ID in one of the
7502 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007503 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7504 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007505 // Note: io is never 0 when creating an effect on an input
7506 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007507 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007508 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7509 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007510 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007511 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007512 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007513 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007514 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007515 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7516 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7517 io = mRecordThreads.keyAt(i);
7518 break;
7519 }
7520 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007521 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007522 // If no output thread contains the requested session ID, default to
7523 // first output. The effect chain will be moved to the correct output
7524 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007525 if (io == 0 && mPlaybackThreads.size()) {
7526 io = mPlaybackThreads.keyAt(0);
7527 }
Steve Block3856b092011-10-20 11:56:00 +01007528 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007529 }
7530 ThreadBase *thread = checkRecordThread_l(io);
7531 if (thread == NULL) {
7532 thread = checkPlaybackThread_l(io);
7533 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007534 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007535 lStatus = BAD_VALUE;
7536 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007537 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007538 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007539
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007540 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007541
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007542 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007543 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7544 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007545 if (handle != 0 && id != NULL) {
7546 *id = handle->id();
7547 }
7548 }
7549
7550Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007551 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007552 *status = lStatus;
7553 }
7554 return handle;
7555}
7556
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007557status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7558 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007559{
Steve Block3856b092011-10-20 11:56:00 +01007560 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007561 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007562 Mutex::Autolock _l(mLock);
7563 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007564 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007565 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007566 }
Eric Laurentde070132010-07-13 04:45:46 -07007567 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7568 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007569 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007570 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007571 }
Eric Laurentde070132010-07-13 04:45:46 -07007572 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7573 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007574 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007575 return BAD_VALUE;
7576 }
7577
7578 Mutex::Autolock _dl(dstThread->mLock);
7579 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007580 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007581
Mathias Agopian65ab4712010-07-14 17:59:35 -07007582 return NO_ERROR;
7583}
7584
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007585// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007586status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007587 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007588 AudioFlinger::PlaybackThread *dstThread,
7589 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007590{
Steve Block3856b092011-10-20 11:56:00 +01007591 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007592 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007593
Eric Laurent59255e42011-07-27 19:49:51 -07007594 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007595 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007596 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007597 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007598 return INVALID_OPERATION;
7599 }
7600
Eric Laurent39e94f82010-07-28 01:32:47 -07007601 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007602 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007603 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007604 // removed.
7605 srcThread->removeEffectChain_l(chain);
7606
7607 // transfer all effects one by one so that new effect chain is created on new thread with
7608 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007609 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007610 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007611 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007612 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7613 while (effect != 0) {
7614 srcThread->removeEffect_l(effect);
7615 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007616 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7617 if (effect->state() == EffectModule::ACTIVE ||
7618 effect->state() == EffectModule::STOPPING) {
7619 effect->start();
7620 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007621 // if the move request is not received from audio policy manager, the effect must be
7622 // re-registered with the new strategy and output
7623 if (dstChain == 0) {
7624 dstChain = effect->chain().promote();
7625 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007626 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007627 srcThread->addEffect_l(effect);
7628 return NO_INIT;
7629 }
7630 strategy = dstChain->strategy();
7631 }
7632 if (reRegister) {
7633 AudioSystem::unregisterEffect(effect->id());
7634 AudioSystem::registerEffect(&effect->desc(),
7635 dstOutput,
7636 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007637 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007638 effect->id());
7639 }
Eric Laurentde070132010-07-13 04:45:46 -07007640 effect = chain->getEffectFromId_l(0);
7641 }
7642
7643 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007644}
7645
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007646
Mathias Agopian65ab4712010-07-14 17:59:35 -07007647// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007648sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007649 const sp<AudioFlinger::Client>& client,
7650 const sp<IEffectClient>& effectClient,
7651 int32_t priority,
7652 int sessionId,
7653 effect_descriptor_t *desc,
7654 int *enabled,
7655 status_t *status
7656 )
7657{
7658 sp<EffectModule> effect;
7659 sp<EffectHandle> handle;
7660 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007661 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007662 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007663 bool effectCreated = false;
7664 bool effectRegistered = false;
7665
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007666 lStatus = initCheck();
7667 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007668 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007669 goto Exit;
7670 }
7671
7672 // Do not allow effects with session ID 0 on direct output or duplicating threads
7673 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007674 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007675 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007676 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007677 lStatus = BAD_VALUE;
7678 goto Exit;
7679 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007680 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007681 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007682 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007683 desc->name, desc->flags, mType);
7684 lStatus = BAD_VALUE;
7685 goto Exit;
7686 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007687
Steve Block3856b092011-10-20 11:56:00 +01007688 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007689
7690 { // scope for mLock
7691 Mutex::Autolock _l(mLock);
7692
7693 // check for existing effect chain with the requested audio session
7694 chain = getEffectChain_l(sessionId);
7695 if (chain == 0) {
7696 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007697 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007698 chain = new EffectChain(this, sessionId);
7699 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007700 chain->setStrategy(getStrategyForSession_l(sessionId));
7701 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007702 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007703 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007704 }
7705
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007706 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007707
7708 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007709 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007710 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007711 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007712 if (lStatus != NO_ERROR) {
7713 goto Exit;
7714 }
7715 effectRegistered = true;
7716 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007717 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007718 lStatus = effect->status();
7719 if (lStatus != NO_ERROR) {
7720 goto Exit;
7721 }
Eric Laurentcab11242010-07-15 12:50:15 -07007722 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007723 if (lStatus != NO_ERROR) {
7724 goto Exit;
7725 }
7726 effectCreated = true;
7727
7728 effect->setDevice(mDevice);
7729 effect->setMode(mAudioFlinger->getMode());
7730 }
7731 // create effect handle and connect it to effect module
7732 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007733 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007734 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007735 *enabled = (int)effect->isEnabled();
7736 }
7737 }
7738
7739Exit:
7740 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007741 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007742 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007743 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007744 }
7745 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007746 AudioSystem::unregisterEffect(effect->id());
7747 }
7748 if (chainCreated) {
7749 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007750 }
7751 handle.clear();
7752 }
7753
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007754 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007755 *status = lStatus;
7756 }
7757 return handle;
7758}
7759
Eric Laurent717e1282012-06-29 16:36:52 -07007760sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7761{
7762 Mutex::Autolock _l(mLock);
7763 return getEffect_l(sessionId, effectId);
7764}
7765
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007766sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7767{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007768 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007769 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007770}
7771
Eric Laurentde070132010-07-13 04:45:46 -07007772// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7773// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007774status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007775{
7776 // check for existing effect chain with the requested audio session
7777 int sessionId = effect->sessionId();
7778 sp<EffectChain> chain = getEffectChain_l(sessionId);
7779 bool chainCreated = false;
7780
7781 if (chain == 0) {
7782 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007783 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007784 chain = new EffectChain(this, sessionId);
7785 addEffectChain_l(chain);
7786 chain->setStrategy(getStrategyForSession_l(sessionId));
7787 chainCreated = true;
7788 }
Steve Block3856b092011-10-20 11:56:00 +01007789 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007790
7791 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007792 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007793 this, effect->desc().name, chain.get());
7794 return BAD_VALUE;
7795 }
7796
7797 status_t status = chain->addEffect_l(effect);
7798 if (status != NO_ERROR) {
7799 if (chainCreated) {
7800 removeEffectChain_l(chain);
7801 }
7802 return status;
7803 }
7804
7805 effect->setDevice(mDevice);
7806 effect->setMode(mAudioFlinger->getMode());
7807 return NO_ERROR;
7808}
7809
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007810void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007811
Steve Block3856b092011-10-20 11:56:00 +01007812 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007813 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007814 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7815 detachAuxEffect_l(effect->id());
7816 }
7817
7818 sp<EffectChain> chain = effect->chain().promote();
7819 if (chain != 0) {
7820 // remove effect chain if removing last effect
7821 if (chain->removeEffect_l(effect) == 0) {
7822 removeEffectChain_l(chain);
7823 }
7824 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007825 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007826 }
7827}
7828
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007829void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007830 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007831{
7832 effectChains = mEffectChains;
7833 for (size_t i = 0; i < mEffectChains.size(); i++) {
7834 mEffectChains[i]->lock();
7835 }
7836}
7837
7838void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007839 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007840{
7841 for (size_t i = 0; i < effectChains.size(); i++) {
7842 effectChains[i]->unlock();
7843 }
7844}
7845
7846sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7847{
7848 Mutex::Autolock _l(mLock);
7849 return getEffectChain_l(sessionId);
7850}
7851
7852sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
7853{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007854 size_t size = mEffectChains.size();
7855 for (size_t i = 0; i < size; i++) {
7856 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007857 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007858 }
7859 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007860 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007861}
7862
Glenn Kastenf78aee72012-01-04 11:00:47 -08007863void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007864{
7865 Mutex::Autolock _l(mLock);
7866 size_t size = mEffectChains.size();
7867 for (size_t i = 0; i < size; i++) {
7868 mEffectChains[i]->setMode_l(mode);
7869 }
7870}
7871
7872void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007873 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007874 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007875
Mathias Agopian65ab4712010-07-14 17:59:35 -07007876 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007877 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007878 // delete the effect module if removing last handle on it
7879 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007880 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007881 removeEffect_l(effect);
7882 AudioSystem::unregisterEffect(effect->id());
7883 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007884 }
7885}
7886
7887status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7888{
7889 int session = chain->sessionId();
7890 int16_t *buffer = mMixBuffer;
7891 bool ownsBuffer = false;
7892
Steve Block3856b092011-10-20 11:56:00 +01007893 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007894 if (session > 0) {
7895 // Only one effect chain can be present in direct output thread and it uses
7896 // the mix buffer as input
7897 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007898 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007899 buffer = new int16_t[numSamples];
7900 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007901 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007902 ownsBuffer = true;
7903 }
7904
7905 // Attach all tracks with same session ID to this chain.
7906 for (size_t i = 0; i < mTracks.size(); ++i) {
7907 sp<Track> track = mTracks[i];
7908 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007909 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007910 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007911 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007912 }
7913 }
7914
7915 // indicate all active tracks in the chain
7916 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7917 sp<Track> track = mActiveTracks[i].promote();
7918 if (track == 0) continue;
7919 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007920 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007921 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007922 }
7923 }
7924 }
7925
7926 chain->setInBuffer(buffer, ownsBuffer);
7927 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007928 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007929 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007930 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7931 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007932 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007933 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7934 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007935 // Effect chain for other sessions are inserted at beginning of effect
7936 // chains list to be processed before output mix effects. Relative order between other
7937 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007938 size_t size = mEffectChains.size();
7939 size_t i = 0;
7940 for (i = 0; i < size; i++) {
7941 if (mEffectChains[i]->sessionId() < session) break;
7942 }
7943 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007944 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007945
7946 return NO_ERROR;
7947}
7948
7949size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7950{
7951 int session = chain->sessionId();
7952
Steve Block3856b092011-10-20 11:56:00 +01007953 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007954
7955 for (size_t i = 0; i < mEffectChains.size(); i++) {
7956 if (chain == mEffectChains[i]) {
7957 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007958 // detach all active tracks from the chain
7959 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7960 sp<Track> track = mActiveTracks[i].promote();
7961 if (track == 0) continue;
7962 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007963 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007964 chain.get(), session);
7965 chain->decActiveTrackCnt();
7966 }
7967 }
7968
Mathias Agopian65ab4712010-07-14 17:59:35 -07007969 // detach all tracks with same session ID from this chain
7970 for (size_t i = 0; i < mTracks.size(); ++i) {
7971 sp<Track> track = mTracks[i];
7972 if (session == track->sessionId()) {
7973 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007974 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007975 }
7976 }
Eric Laurentde070132010-07-13 04:45:46 -07007977 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007978 }
7979 }
7980 return mEffectChains.size();
7981}
7982
Eric Laurentde070132010-07-13 04:45:46 -07007983status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7984 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007985{
7986 Mutex::Autolock _l(mLock);
7987 return attachAuxEffect_l(track, EffectId);
7988}
7989
Eric Laurentde070132010-07-13 04:45:46 -07007990status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
7991 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007992{
7993 status_t status = NO_ERROR;
7994
7995 if (EffectId == 0) {
7996 track->setAuxBuffer(0, NULL);
7997 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07007998 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
7999 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008000 if (effect != 0) {
8001 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8002 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
8003 } else {
8004 status = INVALID_OPERATION;
8005 }
8006 } else {
8007 status = BAD_VALUE;
8008 }
8009 }
8010 return status;
8011}
8012
8013void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
8014{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008015 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008016 sp<Track> track = mTracks[i];
8017 if (track->auxEffectId() == effectId) {
8018 attachAuxEffect_l(track, 0);
8019 }
8020 }
8021}
8022
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008023status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8024{
8025 // only one chain per input thread
8026 if (mEffectChains.size() != 0) {
8027 return INVALID_OPERATION;
8028 }
Steve Block3856b092011-10-20 11:56:00 +01008029 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008030
8031 chain->setInBuffer(NULL);
8032 chain->setOutBuffer(NULL);
8033
Eric Laurent59255e42011-07-27 19:49:51 -07008034 checkSuspendOnAddEffectChain_l(chain);
8035
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008036 mEffectChains.add(chain);
8037
8038 return NO_ERROR;
8039}
8040
8041size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8042{
Steve Block3856b092011-10-20 11:56:00 +01008043 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00008044 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008045 "removeEffectChain_l() %p invalid chain size %d on thread %p",
8046 chain.get(), mEffectChains.size(), this);
8047 if (mEffectChains.size() == 1) {
8048 mEffectChains.removeAt(0);
8049 }
8050 return 0;
8051}
8052
Mathias Agopian65ab4712010-07-14 17:59:35 -07008053// ----------------------------------------------------------------------------
8054// EffectModule implementation
8055// ----------------------------------------------------------------------------
8056
8057#undef LOG_TAG
8058#define LOG_TAG "AudioFlinger::EffectModule"
8059
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008060AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008061 const wp<AudioFlinger::EffectChain>& chain,
8062 effect_descriptor_t *desc,
8063 int id,
8064 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07008065 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
8066 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07008067 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07008068 // mConfig is set by configure() and not used before then
8069 mEffectInterface(NULL),
8070 mStatus(NO_INIT), mState(IDLE),
8071 // mMaxDisableWaitCnt is set by configure() and not used before then
8072 // mDisableWaitCnt is set by process() and updateState() and not used before then
8073 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008074{
Steve Block3856b092011-10-20 11:56:00 +01008075 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008076 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008077
8078 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008079 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008080
8081 if (mStatus != NO_ERROR) {
8082 return;
8083 }
8084 lStatus = init();
8085 if (lStatus < 0) {
8086 mStatus = lStatus;
8087 goto Error;
8088 }
8089
Steve Block3856b092011-10-20 11:56:00 +01008090 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008091 return;
8092Error:
8093 EffectRelease(mEffectInterface);
8094 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008095 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008096}
8097
8098AudioFlinger::EffectModule::~EffectModule()
8099{
Steve Block3856b092011-10-20 11:56:00 +01008100 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008101 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008102 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8103 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8104 sp<ThreadBase> thread = mThread.promote();
8105 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008106 audio_stream_t *stream = thread->stream();
8107 if (stream != NULL) {
8108 stream->remove_audio_effect(stream, mEffectInterface);
8109 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008110 }
8111 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008112 // release effect engine
8113 EffectRelease(mEffectInterface);
8114 }
8115}
8116
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008117status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008118{
8119 status_t status;
8120
8121 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008122 int priority = handle->priority();
8123 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008124 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008125 size_t i;
8126 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008127 EffectHandle *h = mHandles[i];
8128 if (h == NULL || h->destroyed_l()) continue;
8129 // first non destroyed handle is considered in control
8130 if (controlHandle == NULL)
8131 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008132 if (h->priority() <= priority) break;
8133 }
8134 // if inserted in first place, move effect control from previous owner to this handle
8135 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008136 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008137 if (controlHandle != NULL) {
8138 enabled = controlHandle->enabled();
8139 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008140 }
Eric Laurent59255e42011-07-27 19:49:51 -07008141 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008142 status = NO_ERROR;
8143 } else {
8144 status = ALREADY_EXISTS;
8145 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008146 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008147 mHandles.insertAt(handle, i);
8148 return status;
8149}
8150
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008151size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008152{
8153 Mutex::Autolock _l(mLock);
8154 size_t size = mHandles.size();
8155 size_t i;
8156 for (i = 0; i < size; i++) {
8157 if (mHandles[i] == handle) break;
8158 }
8159 if (i == size) {
8160 return size;
8161 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008162 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008163
Mathias Agopian65ab4712010-07-14 17:59:35 -07008164 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008165 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008166 if (i == 0) {
8167 EffectHandle *h = controlHandle_l();
8168 if (h != NULL) {
8169 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008170 }
8171 }
8172
Eric Laurentec437d82011-07-26 20:54:46 -07008173 // Prevent calls to process() and other functions on effect interface from now on.
8174 // The effect engine will be released by the destructor when the last strong reference on
8175 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008176 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008177 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008178 }
8179
Eric Laurente65c8912012-07-20 15:57:23 -07008180 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008181}
8182
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008183// must be called with EffectModule::mLock held
8184AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008185{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008186 // the first valid handle in the list has control over the module
8187 for (size_t i = 0; i < mHandles.size(); i++) {
8188 EffectHandle *h = mHandles[i];
8189 if (h != NULL && !h->destroyed_l()) {
8190 return h;
8191 }
8192 }
8193
8194 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008195}
8196
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008197size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008198{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008199 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008200 // keep a strong reference on this EffectModule to avoid calling the
8201 // destructor before we exit
8202 sp<EffectModule> keep(this);
8203 {
8204 sp<ThreadBase> thread = mThread.promote();
8205 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008206 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008207 }
8208 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008209 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008210}
8211
8212void AudioFlinger::EffectModule::updateState() {
8213 Mutex::Autolock _l(mLock);
8214
8215 switch (mState) {
8216 case RESTART:
8217 reset_l();
8218 // FALL THROUGH
8219
8220 case STARTING:
8221 // clear auxiliary effect input buffer for next accumulation
8222 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8223 memset(mConfig.inputCfg.buffer.raw,
8224 0,
8225 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8226 }
8227 start_l();
8228 mState = ACTIVE;
8229 break;
8230 case STOPPING:
8231 stop_l();
8232 mDisableWaitCnt = mMaxDisableWaitCnt;
8233 mState = STOPPED;
8234 break;
8235 case STOPPED:
8236 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8237 // turn off sequence.
8238 if (--mDisableWaitCnt == 0) {
8239 reset_l();
8240 mState = IDLE;
8241 }
8242 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008243 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008244 break;
8245 }
8246}
8247
8248void AudioFlinger::EffectModule::process()
8249{
8250 Mutex::Autolock _l(mLock);
8251
Eric Laurentec437d82011-07-26 20:54:46 -07008252 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008253 mConfig.inputCfg.buffer.raw == NULL ||
8254 mConfig.outputCfg.buffer.raw == NULL) {
8255 return;
8256 }
8257
Eric Laurent8f45bd72010-08-31 13:50:07 -07008258 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008259 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8260 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008261 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008262 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008263 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008264 }
8265
8266 // do the actual processing in the effect engine
8267 int ret = (*mEffectInterface)->process(mEffectInterface,
8268 &mConfig.inputCfg.buffer,
8269 &mConfig.outputCfg.buffer);
8270
8271 // force transition to IDLE state when engine is ready
8272 if (mState == STOPPED && ret == -ENODATA) {
8273 mDisableWaitCnt = 1;
8274 }
8275
8276 // clear auxiliary effect input buffer for next accumulation
8277 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008278 memset(mConfig.inputCfg.buffer.raw, 0,
8279 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008280 }
8281 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008282 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8283 // If an insert effect is idle and input buffer is different from output buffer,
8284 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008285 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008286 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008287 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8288 int16_t *in = mConfig.inputCfg.buffer.s16;
8289 int16_t *out = mConfig.outputCfg.buffer.s16;
8290 for (size_t i = 0; i < frameCnt; i++) {
8291 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008292 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008293 }
8294 }
8295}
8296
8297void AudioFlinger::EffectModule::reset_l()
8298{
8299 if (mEffectInterface == NULL) {
8300 return;
8301 }
8302 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8303}
8304
8305status_t AudioFlinger::EffectModule::configure()
8306{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008307 if (mEffectInterface == NULL) {
8308 return NO_INIT;
8309 }
8310
8311 sp<ThreadBase> thread = mThread.promote();
8312 if (thread == 0) {
8313 return DEAD_OBJECT;
8314 }
8315
8316 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07008317 audio_channel_mask_t channelMask = thread->channelMask();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008318
8319 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008320 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008321 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07008322 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008323 }
Glenn Kasten254af182012-07-03 14:59:05 -07008324 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07008325 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8326 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008327 mConfig.inputCfg.samplingRate = thread->sampleRate();
8328 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8329 mConfig.inputCfg.bufferProvider.cookie = NULL;
8330 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8331 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8332 mConfig.outputCfg.bufferProvider.cookie = NULL;
8333 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8334 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8335 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8336 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008337 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008338 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008339 // - in other sessions:
8340 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8341 // other effect: overwrites output buffer: input buffer == output buffer
8342 // Auxiliary effect:
8343 // accumulates in output buffer: input buffer != output buffer
8344 // Therefore: accumulate <=> input buffer != output buffer
8345 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8346 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8347 } else {
8348 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8349 }
8350 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8351 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8352 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8353 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8354
Steve Block3856b092011-10-20 11:56:00 +01008355 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008356 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8357
Mathias Agopian65ab4712010-07-14 17:59:35 -07008358 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008359 uint32_t size = sizeof(int);
8360 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008361 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008362 sizeof(effect_config_t),
8363 &mConfig,
8364 &size,
8365 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008366 if (status == 0) {
8367 status = cmdStatus;
8368 }
8369
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008370 if (status == 0 &&
8371 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8372 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8373 effect_param_t *p = (effect_param_t *)buf32;
8374
8375 p->psize = sizeof(uint32_t);
8376 p->vsize = sizeof(uint32_t);
8377 size = sizeof(int);
8378 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8379
8380 uint32_t latency = 0;
8381 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8382 if (pbt != NULL) {
8383 latency = pbt->latency_l();
8384 }
8385
8386 *((int32_t *)p->data + 1)= latency;
8387 (*mEffectInterface)->command(mEffectInterface,
8388 EFFECT_CMD_SET_PARAM,
8389 sizeof(effect_param_t) + 8,
8390 &buf32,
8391 &size,
8392 &cmdStatus);
8393 }
8394
Mathias Agopian65ab4712010-07-14 17:59:35 -07008395 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8396 (1000 * mConfig.outputCfg.buffer.frameCount);
8397
8398 return status;
8399}
8400
8401status_t AudioFlinger::EffectModule::init()
8402{
8403 Mutex::Autolock _l(mLock);
8404 if (mEffectInterface == NULL) {
8405 return NO_INIT;
8406 }
8407 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008408 uint32_t size = sizeof(status_t);
8409 status_t status = (*mEffectInterface)->command(mEffectInterface,
8410 EFFECT_CMD_INIT,
8411 0,
8412 NULL,
8413 &size,
8414 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008415 if (status == 0) {
8416 status = cmdStatus;
8417 }
8418 return status;
8419}
8420
Eric Laurentec35a142011-10-05 17:42:25 -07008421status_t AudioFlinger::EffectModule::start()
8422{
8423 Mutex::Autolock _l(mLock);
8424 return start_l();
8425}
8426
Mathias Agopian65ab4712010-07-14 17:59:35 -07008427status_t AudioFlinger::EffectModule::start_l()
8428{
8429 if (mEffectInterface == NULL) {
8430 return NO_INIT;
8431 }
8432 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008433 uint32_t size = sizeof(status_t);
8434 status_t status = (*mEffectInterface)->command(mEffectInterface,
8435 EFFECT_CMD_ENABLE,
8436 0,
8437 NULL,
8438 &size,
8439 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008440 if (status == 0) {
8441 status = cmdStatus;
8442 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008443 if (status == 0 &&
8444 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8445 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8446 sp<ThreadBase> thread = mThread.promote();
8447 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008448 audio_stream_t *stream = thread->stream();
8449 if (stream != NULL) {
8450 stream->add_audio_effect(stream, mEffectInterface);
8451 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008452 }
8453 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008454 return status;
8455}
8456
Eric Laurentec437d82011-07-26 20:54:46 -07008457status_t AudioFlinger::EffectModule::stop()
8458{
8459 Mutex::Autolock _l(mLock);
8460 return stop_l();
8461}
8462
Mathias Agopian65ab4712010-07-14 17:59:35 -07008463status_t AudioFlinger::EffectModule::stop_l()
8464{
8465 if (mEffectInterface == NULL) {
8466 return NO_INIT;
8467 }
8468 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008469 uint32_t size = sizeof(status_t);
8470 status_t status = (*mEffectInterface)->command(mEffectInterface,
8471 EFFECT_CMD_DISABLE,
8472 0,
8473 NULL,
8474 &size,
8475 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008476 if (status == 0) {
8477 status = cmdStatus;
8478 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008479 if (status == 0 &&
8480 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8481 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8482 sp<ThreadBase> thread = mThread.promote();
8483 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008484 audio_stream_t *stream = thread->stream();
8485 if (stream != NULL) {
8486 stream->remove_audio_effect(stream, mEffectInterface);
8487 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008488 }
8489 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008490 return status;
8491}
8492
Eric Laurent25f43952010-07-28 05:40:18 -07008493status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8494 uint32_t cmdSize,
8495 void *pCmdData,
8496 uint32_t *replySize,
8497 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008498{
8499 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008500// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008501
Eric Laurentec437d82011-07-26 20:54:46 -07008502 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008503 return NO_INIT;
8504 }
Eric Laurent25f43952010-07-28 05:40:18 -07008505 status_t status = (*mEffectInterface)->command(mEffectInterface,
8506 cmdCode,
8507 cmdSize,
8508 pCmdData,
8509 replySize,
8510 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008511 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008512 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008513 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008514 EffectHandle *h = mHandles[i];
8515 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008516 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8517 }
8518 }
8519 }
8520 return status;
8521}
8522
8523status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8524{
8525 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008526 return setEnabled_l(enabled);
8527}
8528
8529// must be called with EffectModule::mLock held
8530status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8531{
8532
Steve Block3856b092011-10-20 11:56:00 +01008533 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008534
8535 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008536 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8537 if (enabled && status != NO_ERROR) {
8538 return status;
8539 }
8540
Mathias Agopian65ab4712010-07-14 17:59:35 -07008541 switch (mState) {
8542 // going from disabled to enabled
8543 case IDLE:
8544 mState = STARTING;
8545 break;
8546 case STOPPED:
8547 mState = RESTART;
8548 break;
8549 case STOPPING:
8550 mState = ACTIVE;
8551 break;
8552
8553 // going from enabled to disabled
8554 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008555 mState = STOPPED;
8556 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008557 case STARTING:
8558 mState = IDLE;
8559 break;
8560 case ACTIVE:
8561 mState = STOPPING;
8562 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008563 case DESTROYED:
8564 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008565 }
8566 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008567 EffectHandle *h = mHandles[i];
8568 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008569 h->setEnabled(enabled);
8570 }
8571 }
8572 }
8573 return NO_ERROR;
8574}
8575
Glenn Kastenc59c0042012-02-02 14:06:11 -08008576bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008577{
8578 switch (mState) {
8579 case RESTART:
8580 case STARTING:
8581 case ACTIVE:
8582 return true;
8583 case IDLE:
8584 case STOPPING:
8585 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008586 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008587 default:
8588 return false;
8589 }
8590}
8591
Glenn Kastenc59c0042012-02-02 14:06:11 -08008592bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008593{
8594 switch (mState) {
8595 case RESTART:
8596 case ACTIVE:
8597 case STOPPING:
8598 case STOPPED:
8599 return true;
8600 case IDLE:
8601 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008602 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008603 default:
8604 return false;
8605 }
8606}
8607
Mathias Agopian65ab4712010-07-14 17:59:35 -07008608status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8609{
8610 Mutex::Autolock _l(mLock);
8611 status_t status = NO_ERROR;
8612
8613 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8614 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008615 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008616 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8617 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008618 status_t cmdStatus;
8619 uint32_t volume[2];
8620 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008621 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008622 volume[0] = *left;
8623 volume[1] = *right;
8624 if (controller) {
8625 pVolume = volume;
8626 }
Eric Laurent25f43952010-07-28 05:40:18 -07008627 status = (*mEffectInterface)->command(mEffectInterface,
8628 EFFECT_CMD_SET_VOLUME,
8629 size,
8630 volume,
8631 &size,
8632 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008633 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8634 *left = volume[0];
8635 *right = volume[1];
8636 }
8637 }
8638 return status;
8639}
8640
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008641status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008642{
8643 Mutex::Autolock _l(mLock);
8644 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008645 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8646 // audio pre processing modules on RecordThread can receive both output and
8647 // input device indication in the same call
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008648 audio_devices_t dev = device & AUDIO_DEVICE_OUT_ALL;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008649 if (dev) {
8650 status_t cmdStatus;
8651 uint32_t size = sizeof(status_t);
8652
8653 status = (*mEffectInterface)->command(mEffectInterface,
8654 EFFECT_CMD_SET_DEVICE,
8655 sizeof(uint32_t),
8656 &dev,
8657 &size,
8658 &cmdStatus);
8659 if (status == NO_ERROR) {
8660 status = cmdStatus;
8661 }
8662 }
8663 dev = device & AUDIO_DEVICE_IN_ALL;
8664 if (dev) {
8665 status_t cmdStatus;
8666 uint32_t size = sizeof(status_t);
8667
8668 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8669 EFFECT_CMD_SET_INPUT_DEVICE,
8670 sizeof(uint32_t),
8671 &dev,
8672 &size,
8673 &cmdStatus);
8674 if (status2 == NO_ERROR) {
8675 status2 = cmdStatus;
8676 }
8677 if (status == NO_ERROR) {
8678 status = status2;
8679 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008680 }
8681 }
8682 return status;
8683}
8684
Glenn Kastenf78aee72012-01-04 11:00:47 -08008685status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008686{
8687 Mutex::Autolock _l(mLock);
8688 status_t status = NO_ERROR;
8689 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008690 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008691 uint32_t size = sizeof(status_t);
8692 status = (*mEffectInterface)->command(mEffectInterface,
8693 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008694 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008695 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008696 &size,
8697 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008698 if (status == NO_ERROR) {
8699 status = cmdStatus;
8700 }
8701 }
8702 return status;
8703}
8704
Eric Laurent59255e42011-07-27 19:49:51 -07008705void AudioFlinger::EffectModule::setSuspended(bool suspended)
8706{
8707 Mutex::Autolock _l(mLock);
8708 mSuspended = suspended;
8709}
Glenn Kastena3a85482012-01-04 11:01:11 -08008710
8711bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008712{
8713 Mutex::Autolock _l(mLock);
8714 return mSuspended;
8715}
8716
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008717bool AudioFlinger::EffectModule::purgeHandles()
8718{
8719 bool enabled = false;
8720 Mutex::Autolock _l(mLock);
8721 for (size_t i = 0; i < mHandles.size(); i++) {
8722 EffectHandle *handle = mHandles[i];
8723 if (handle != NULL && !handle->destroyed_l()) {
8724 handle->effect().clear();
8725 if (handle->hasControl()) {
8726 enabled = handle->enabled();
8727 }
8728 }
8729 }
8730 return enabled;
8731}
8732
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07008733void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008734{
8735 const size_t SIZE = 256;
8736 char buffer[SIZE];
8737 String8 result;
8738
8739 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8740 result.append(buffer);
8741
8742 bool locked = tryLock(mLock);
8743 // failed to lock - AudioFlinger is probably deadlocked
8744 if (!locked) {
8745 result.append("\t\tCould not lock Fx mutex:\n");
8746 }
8747
8748 result.append("\t\tSession Status State Engine:\n");
8749 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8750 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8751 result.append(buffer);
8752
8753 result.append("\t\tDescriptor:\n");
8754 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8755 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8756 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8757 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8758 result.append(buffer);
8759 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8760 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8761 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8762 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8763 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008764 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008765 mDescriptor.apiVersion,
8766 mDescriptor.flags);
8767 result.append(buffer);
8768 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8769 mDescriptor.name);
8770 result.append(buffer);
8771 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8772 mDescriptor.implementor);
8773 result.append(buffer);
8774
8775 result.append("\t\t- Input configuration:\n");
8776 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8777 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8778 (uint32_t)mConfig.inputCfg.buffer.raw,
8779 mConfig.inputCfg.buffer.frameCount,
8780 mConfig.inputCfg.samplingRate,
8781 mConfig.inputCfg.channels,
8782 mConfig.inputCfg.format);
8783 result.append(buffer);
8784
8785 result.append("\t\t- Output configuration:\n");
8786 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8787 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8788 (uint32_t)mConfig.outputCfg.buffer.raw,
8789 mConfig.outputCfg.buffer.frameCount,
8790 mConfig.outputCfg.samplingRate,
8791 mConfig.outputCfg.channels,
8792 mConfig.outputCfg.format);
8793 result.append(buffer);
8794
8795 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8796 result.append(buffer);
8797 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8798 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008799 EffectHandle *handle = mHandles[i];
8800 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008801 handle->dump(buffer, SIZE);
8802 result.append(buffer);
8803 }
8804 }
8805
8806 result.append("\n");
8807
8808 write(fd, result.string(), result.length());
8809
8810 if (locked) {
8811 mLock.unlock();
8812 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008813}
8814
8815// ----------------------------------------------------------------------------
8816// EffectHandle implementation
8817// ----------------------------------------------------------------------------
8818
8819#undef LOG_TAG
8820#define LOG_TAG "AudioFlinger::EffectHandle"
8821
8822AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8823 const sp<AudioFlinger::Client>& client,
8824 const sp<IEffectClient>& effectClient,
8825 int32_t priority)
8826 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008827 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008828 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008829{
Steve Block3856b092011-10-20 11:56:00 +01008830 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008831
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008832 if (client == 0) {
8833 return;
8834 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008835 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8836 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8837 if (mCblkMemory != 0) {
8838 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8839
Glenn Kastena0d68332012-01-27 16:47:15 -08008840 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008841 new(mCblk) effect_param_cblk_t();
8842 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008843 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008844 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008845 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008846 return;
8847 }
8848}
8849
8850AudioFlinger::EffectHandle::~EffectHandle()
8851{
Steve Block3856b092011-10-20 11:56:00 +01008852 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008853
8854 if (mEffect == 0) {
8855 mDestroyed = true;
8856 return;
8857 }
8858 mEffect->lock();
8859 mDestroyed = true;
8860 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008861 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008862}
8863
8864status_t AudioFlinger::EffectHandle::enable()
8865{
Steve Block3856b092011-10-20 11:56:00 +01008866 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008867 if (!mHasControl) return INVALID_OPERATION;
8868 if (mEffect == 0) return DEAD_OBJECT;
8869
Eric Laurentdb7c0792011-08-10 10:37:50 -07008870 if (mEnabled) {
8871 return NO_ERROR;
8872 }
8873
Eric Laurent59255e42011-07-27 19:49:51 -07008874 mEnabled = true;
8875
8876 sp<ThreadBase> thread = mEffect->thread().promote();
8877 if (thread != 0) {
8878 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8879 }
8880
8881 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8882 if (mEffect->suspended()) {
8883 return NO_ERROR;
8884 }
8885
Eric Laurentdb7c0792011-08-10 10:37:50 -07008886 status_t status = mEffect->setEnabled(true);
8887 if (status != NO_ERROR) {
8888 if (thread != 0) {
8889 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8890 }
8891 mEnabled = false;
8892 }
8893 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008894}
8895
8896status_t AudioFlinger::EffectHandle::disable()
8897{
Steve Block3856b092011-10-20 11:56:00 +01008898 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008899 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008900 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008901
Eric Laurentdb7c0792011-08-10 10:37:50 -07008902 if (!mEnabled) {
8903 return NO_ERROR;
8904 }
Eric Laurent59255e42011-07-27 19:49:51 -07008905 mEnabled = false;
8906
8907 if (mEffect->suspended()) {
8908 return NO_ERROR;
8909 }
8910
8911 status_t status = mEffect->setEnabled(false);
8912
8913 sp<ThreadBase> thread = mEffect->thread().promote();
8914 if (thread != 0) {
8915 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8916 }
8917
8918 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008919}
8920
8921void AudioFlinger::EffectHandle::disconnect()
8922{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008923 disconnect(true);
8924}
8925
Glenn Kasten58123c32012-02-03 10:32:24 -08008926void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008927{
Glenn Kasten58123c32012-02-03 10:32:24 -08008928 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008929 if (mEffect == 0) {
8930 return;
8931 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008932 // restore suspended effects if the disconnected handle was enabled and the last one.
8933 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008934 sp<ThreadBase> thread = mEffect->thread().promote();
8935 if (thread != 0) {
8936 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8937 }
Eric Laurent59255e42011-07-27 19:49:51 -07008938 }
8939
Mathias Agopian65ab4712010-07-14 17:59:35 -07008940 // release sp on module => module destructor can be called now
8941 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008942 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008943 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008944 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008945 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8946 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008947 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008948 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008949 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8950 mClient.clear();
8951 }
8952}
8953
Eric Laurent25f43952010-07-28 05:40:18 -07008954status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8955 uint32_t cmdSize,
8956 void *pCmdData,
8957 uint32_t *replySize,
8958 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008959{
Steve Block3856b092011-10-20 11:56:00 +01008960// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008961// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008962
8963 // only get parameter command is permitted for applications not controlling the effect
8964 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8965 return INVALID_OPERATION;
8966 }
8967 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008968 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008969
8970 // handle commands that are not forwarded transparently to effect engine
8971 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8972 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8973 // no risk to block the whole media server process or mixer threads is we are stuck here
8974 Mutex::Autolock _l(mCblk->lock);
8975 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8976 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8977 mCblk->serverIndex = 0;
8978 mCblk->clientIndex = 0;
8979 return BAD_VALUE;
8980 }
8981 status_t status = NO_ERROR;
8982 while (mCblk->serverIndex < mCblk->clientIndex) {
8983 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008984 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008985 int *p = (int *)(mBuffer + mCblk->serverIndex);
8986 int size = *p++;
8987 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008988 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008989 break;
8990 }
8991 effect_param_t *param = (effect_param_t *)p;
8992 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008993 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008994 mCblk->serverIndex += size;
8995 continue;
8996 }
Eric Laurent25f43952010-07-28 05:40:18 -07008997 uint32_t psize = sizeof(effect_param_t) +
8998 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
8999 param->vsize;
9000 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
9001 psize,
9002 p,
9003 &rsize,
9004 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07009005 // stop at first error encountered
9006 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009007 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07009008 *(int *)pReplyData = reply;
9009 break;
9010 } else if (reply != NO_ERROR) {
9011 *(int *)pReplyData = reply;
9012 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009013 }
9014 mCblk->serverIndex += size;
9015 }
9016 mCblk->serverIndex = 0;
9017 mCblk->clientIndex = 0;
9018 return status;
9019 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009020 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009021 return enable();
9022 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009023 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009024 return disable();
9025 }
9026
9027 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9028}
9029
Eric Laurent59255e42011-07-27 19:49:51 -07009030void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009031{
Steve Block3856b092011-10-20 11:56:00 +01009032 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009033
9034 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07009035 mEnabled = enabled;
9036
Mathias Agopian65ab4712010-07-14 17:59:35 -07009037 if (signal && mEffectClient != 0) {
9038 mEffectClient->controlStatusChanged(hasControl);
9039 }
9040}
9041
Eric Laurent25f43952010-07-28 05:40:18 -07009042void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
9043 uint32_t cmdSize,
9044 void *pCmdData,
9045 uint32_t replySize,
9046 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009047{
9048 if (mEffectClient != 0) {
9049 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9050 }
9051}
9052
9053
9054
9055void AudioFlinger::EffectHandle::setEnabled(bool enabled)
9056{
9057 if (mEffectClient != 0) {
9058 mEffectClient->enableStatusChanged(enabled);
9059 }
9060}
9061
9062status_t AudioFlinger::EffectHandle::onTransact(
9063 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9064{
9065 return BnEffect::onTransact(code, data, reply, flags);
9066}
9067
9068
9069void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
9070{
Glenn Kastena0d68332012-01-27 16:47:15 -08009071 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009072
9073 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08009074 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07009075 mPriority,
9076 mHasControl,
9077 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009078 mCblk ? mCblk->clientIndex : 0,
9079 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07009080 );
9081
9082 if (locked) {
9083 mCblk->lock.unlock();
9084 }
9085}
9086
9087#undef LOG_TAG
9088#define LOG_TAG "AudioFlinger::EffectChain"
9089
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009090AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009091 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009092 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07009093 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9094 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009095{
Dima Zavinfce7a472011-04-19 22:30:36 -07009096 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009097 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009098 return;
9099 }
9100 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9101 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009102}
9103
9104AudioFlinger::EffectChain::~EffectChain()
9105{
9106 if (mOwnInBuffer) {
9107 delete mInBuffer;
9108 }
9109
9110}
9111
Eric Laurent59255e42011-07-27 19:49:51 -07009112// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009113sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009114{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009115 size_t size = mEffects.size();
9116
9117 for (size_t i = 0; i < size; i++) {
9118 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009119 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009120 }
9121 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009122 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009123}
9124
Eric Laurent59255e42011-07-27 19:49:51 -07009125// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009126sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009127{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009128 size_t size = mEffects.size();
9129
9130 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009131 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9132 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009133 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009134 }
9135 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009136 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009137}
9138
Eric Laurent59255e42011-07-27 19:49:51 -07009139// getEffectFromType_l() must be called with ThreadBase::mLock held
9140sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9141 const effect_uuid_t *type)
9142{
Eric Laurent59255e42011-07-27 19:49:51 -07009143 size_t size = mEffects.size();
9144
9145 for (size_t i = 0; i < size; i++) {
9146 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009147 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009148 }
9149 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009150 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009151}
9152
Eric Laurent91b14c42012-05-30 12:30:29 -07009153void AudioFlinger::EffectChain::clearInputBuffer()
9154{
9155 Mutex::Autolock _l(mLock);
9156 sp<ThreadBase> thread = mThread.promote();
9157 if (thread == 0) {
9158 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9159 return;
9160 }
9161 clearInputBuffer_l(thread);
9162}
9163
9164// Must be called with EffectChain::mLock locked
9165void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9166{
9167 size_t numSamples = thread->frameCount() * thread->channelCount();
9168 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9169
9170}
9171
Mathias Agopian65ab4712010-07-14 17:59:35 -07009172// Must be called with EffectChain::mLock locked
9173void AudioFlinger::EffectChain::process_l()
9174{
Eric Laurentdac69112010-09-28 14:09:57 -07009175 sp<ThreadBase> thread = mThread.promote();
9176 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009177 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009178 return;
9179 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009180 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9181 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009182 // always process effects unless no more tracks are on the session and the effect tail
9183 // has been rendered
9184 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009185 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009186 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009187
Eric Laurent544fe9b2011-11-11 15:42:52 -08009188 if (!tracksOnSession && mTailBufferCount == 0) {
9189 doProcess = false;
9190 }
9191
9192 if (activeTrackCnt() == 0) {
9193 // if no track is active and the effect tail has not been rendered,
9194 // the input buffer must be cleared here as the mixer process will not do it
9195 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009196 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009197 if (mTailBufferCount > 0) {
9198 mTailBufferCount--;
9199 }
9200 }
9201 }
Eric Laurentdac69112010-09-28 14:09:57 -07009202 }
9203
Mathias Agopian65ab4712010-07-14 17:59:35 -07009204 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009205 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009206 for (size_t i = 0; i < size; i++) {
9207 mEffects[i]->process();
9208 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009209 }
9210 for (size_t i = 0; i < size; i++) {
9211 mEffects[i]->updateState();
9212 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009213}
9214
Eric Laurentcab11242010-07-15 12:50:15 -07009215// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009216status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009217{
9218 effect_descriptor_t desc = effect->desc();
9219 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9220
9221 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009222 effect->setChain(this);
9223 sp<ThreadBase> thread = mThread.promote();
9224 if (thread == 0) {
9225 return NO_INIT;
9226 }
9227 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009228
9229 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9230 // Auxiliary effects are inserted at the beginning of mEffects vector as
9231 // they are processed first and accumulated in chain input buffer
9232 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009233
Mathias Agopian65ab4712010-07-14 17:59:35 -07009234 // the input buffer for auxiliary effect contains mono samples in
9235 // 32 bit format. This is to avoid saturation in AudoMixer
9236 // accumulation stage. Saturation is done in EffectModule::process() before
9237 // calling the process in effect engine
9238 size_t numSamples = thread->frameCount();
9239 int32_t *buffer = new int32_t[numSamples];
9240 memset(buffer, 0, numSamples * sizeof(int32_t));
9241 effect->setInBuffer((int16_t *)buffer);
9242 // auxiliary effects output samples to chain input buffer for further processing
9243 // by insert effects
9244 effect->setOutBuffer(mInBuffer);
9245 } else {
9246 // Insert effects are inserted at the end of mEffects vector as they are processed
9247 // after track and auxiliary effects.
9248 // Insert effect order as a function of indicated preference:
9249 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9250 // another effect is present
9251 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9252 // last effect claiming first position
9253 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9254 // first effect claiming last position
9255 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9256 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9257 // already present
9258
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009259 size_t size = mEffects.size();
9260 size_t idx_insert = size;
9261 ssize_t idx_insert_first = -1;
9262 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009263
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009264 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009265 effect_descriptor_t d = mEffects[i]->desc();
9266 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9267 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9268 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9269 // check invalid effect chaining combinations
9270 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9271 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009272 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009273 return INVALID_OPERATION;
9274 }
9275 // remember position of first insert effect and by default
9276 // select this as insert position for new effect
9277 if (idx_insert == size) {
9278 idx_insert = i;
9279 }
9280 // remember position of last insert effect claiming
9281 // first position
9282 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9283 idx_insert_first = i;
9284 }
9285 // remember position of first insert effect claiming
9286 // last position
9287 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9288 idx_insert_last == -1) {
9289 idx_insert_last = i;
9290 }
9291 }
9292 }
9293
9294 // modify idx_insert from first position if needed
9295 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9296 if (idx_insert_last != -1) {
9297 idx_insert = idx_insert_last;
9298 } else {
9299 idx_insert = size;
9300 }
9301 } else {
9302 if (idx_insert_first != -1) {
9303 idx_insert = idx_insert_first + 1;
9304 }
9305 }
9306
9307 // always read samples from chain input buffer
9308 effect->setInBuffer(mInBuffer);
9309
9310 // if last effect in the chain, output samples to chain
9311 // output buffer, otherwise to chain input buffer
9312 if (idx_insert == size) {
9313 if (idx_insert != 0) {
9314 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9315 mEffects[idx_insert-1]->configure();
9316 }
9317 effect->setOutBuffer(mOutBuffer);
9318 } else {
9319 effect->setOutBuffer(mInBuffer);
9320 }
9321 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009322
Steve Block3856b092011-10-20 11:56:00 +01009323 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009324 }
9325 effect->configure();
9326 return NO_ERROR;
9327}
9328
Eric Laurentcab11242010-07-15 12:50:15 -07009329// removeEffect_l() must be called with PlaybackThread::mLock held
9330size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009331{
9332 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009333 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009334 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9335
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009336 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009337 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009338 // calling stop here will remove pre-processing effect from the audio HAL.
9339 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9340 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009341 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9342 mEffects[i]->state() == EffectModule::STOPPING) {
9343 mEffects[i]->stop();
9344 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009345 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9346 delete[] effect->inBuffer();
9347 } else {
9348 if (i == size - 1 && i != 0) {
9349 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9350 mEffects[i - 1]->configure();
9351 }
9352 }
9353 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009354 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009355 break;
9356 }
9357 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009358
9359 return mEffects.size();
9360}
9361
Eric Laurentcab11242010-07-15 12:50:15 -07009362// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009363void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009364{
9365 size_t size = mEffects.size();
9366 for (size_t i = 0; i < size; i++) {
9367 mEffects[i]->setDevice(device);
9368 }
9369}
9370
Eric Laurentcab11242010-07-15 12:50:15 -07009371// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009372void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009373{
9374 size_t size = mEffects.size();
9375 for (size_t i = 0; i < size; i++) {
9376 mEffects[i]->setMode(mode);
9377 }
9378}
9379
Eric Laurentcab11242010-07-15 12:50:15 -07009380// setVolume_l() must be called with PlaybackThread::mLock held
9381bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009382{
9383 uint32_t newLeft = *left;
9384 uint32_t newRight = *right;
9385 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009386 int ctrlIdx = -1;
9387 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009388
Eric Laurentcab11242010-07-15 12:50:15 -07009389 // first update volume controller
9390 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009391 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009392 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9393 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009394 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009395 break;
9396 }
9397 }
9398
9399 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009400 if (hasControl) {
9401 *left = mNewLeftVolume;
9402 *right = mNewRightVolume;
9403 }
9404 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009405 }
9406
9407 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009408 mLeftVolume = newLeft;
9409 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009410
9411 // second get volume update from volume controller
9412 if (ctrlIdx >= 0) {
9413 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009414 mNewLeftVolume = newLeft;
9415 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009416 }
9417 // then indicate volume to all other effects in chain.
9418 // Pass altered volume to effects before volume controller
9419 // and requested volume to effects after controller
9420 uint32_t lVol = newLeft;
9421 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009422
Mathias Agopian65ab4712010-07-14 17:59:35 -07009423 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009424 if ((int)i == ctrlIdx) continue;
9425 // this also works for ctrlIdx == -1 when there is no volume controller
9426 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009427 lVol = *left;
9428 rVol = *right;
9429 }
9430 mEffects[i]->setVolume(&lVol, &rVol, false);
9431 }
9432 *left = newLeft;
9433 *right = newRight;
9434
9435 return hasControl;
9436}
9437
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009438void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009439{
9440 const size_t SIZE = 256;
9441 char buffer[SIZE];
9442 String8 result;
9443
9444 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9445 result.append(buffer);
9446
9447 bool locked = tryLock(mLock);
9448 // failed to lock - AudioFlinger is probably deadlocked
9449 if (!locked) {
9450 result.append("\tCould not lock mutex:\n");
9451 }
9452
Eric Laurentcab11242010-07-15 12:50:15 -07009453 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9454 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009455 mEffects.size(),
9456 (uint32_t)mInBuffer,
9457 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009458 mActiveTrackCnt);
9459 result.append(buffer);
9460 write(fd, result.string(), result.size());
9461
9462 for (size_t i = 0; i < mEffects.size(); ++i) {
9463 sp<EffectModule> effect = mEffects[i];
9464 if (effect != 0) {
9465 effect->dump(fd, args);
9466 }
9467 }
9468
9469 if (locked) {
9470 mLock.unlock();
9471 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009472}
9473
Eric Laurent59255e42011-07-27 19:49:51 -07009474// must be called with ThreadBase::mLock held
9475void AudioFlinger::EffectChain::setEffectSuspended_l(
9476 const effect_uuid_t *type, bool suspend)
9477{
9478 sp<SuspendedEffectDesc> desc;
9479 // use effect type UUID timelow as key as there is no real risk of identical
9480 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009481 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009482 if (suspend) {
9483 if (index >= 0) {
9484 desc = mSuspendedEffects.valueAt(index);
9485 } else {
9486 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -08009487 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07009488 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009489 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009490 }
9491 if (desc->mRefCount++ == 0) {
9492 sp<EffectModule> effect = getEffectIfEnabled(type);
9493 if (effect != 0) {
9494 desc->mEffect = effect;
9495 effect->setSuspended(true);
9496 effect->setEnabled(false);
9497 }
9498 }
9499 } else {
9500 if (index < 0) {
9501 return;
9502 }
9503 desc = mSuspendedEffects.valueAt(index);
9504 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009505 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009506 desc->mRefCount = 1;
9507 }
9508 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009509 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009510 if (desc->mEffect != 0) {
9511 sp<EffectModule> effect = desc->mEffect.promote();
9512 if (effect != 0) {
9513 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009514 effect->lock();
9515 EffectHandle *handle = effect->controlHandle_l();
9516 if (handle != NULL && !handle->destroyed_l()) {
9517 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009518 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009519 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009520 }
9521 desc->mEffect.clear();
9522 }
9523 mSuspendedEffects.removeItemsAt(index);
9524 }
9525 }
9526}
9527
9528// must be called with ThreadBase::mLock held
9529void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9530{
9531 sp<SuspendedEffectDesc> desc;
9532
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009533 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009534 if (suspend) {
9535 if (index >= 0) {
9536 desc = mSuspendedEffects.valueAt(index);
9537 } else {
9538 desc = new SuspendedEffectDesc();
9539 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009540 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009541 }
9542 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009543 Vector< sp<EffectModule> > effects;
9544 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009545 for (size_t i = 0; i < effects.size(); i++) {
9546 setEffectSuspended_l(&effects[i]->desc().type, true);
9547 }
9548 }
9549 } else {
9550 if (index < 0) {
9551 return;
9552 }
9553 desc = mSuspendedEffects.valueAt(index);
9554 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009555 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009556 desc->mRefCount = 1;
9557 }
9558 if (--desc->mRefCount == 0) {
9559 Vector<const effect_uuid_t *> types;
9560 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9561 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9562 continue;
9563 }
9564 types.add(&mSuspendedEffects.valueAt(i)->mType);
9565 }
9566 for (size_t i = 0; i < types.size(); i++) {
9567 setEffectSuspended_l(types[i], false);
9568 }
Steve Block3856b092011-10-20 11:56:00 +01009569 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009570 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9571 }
9572 }
9573}
9574
Eric Laurent6bffdb82011-09-23 08:40:41 -07009575
9576// The volume effect is used for automated tests only
9577#ifndef OPENSL_ES_H_
9578static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9579 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9580const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9581#endif //OPENSL_ES_H_
9582
Eric Laurentdb7c0792011-08-10 10:37:50 -07009583bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9584{
9585 // auxiliary effects and visualizer are never suspended on output mix
9586 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9587 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009588 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9589 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009590 return false;
9591 }
9592 return true;
9593}
9594
Glenn Kastend0539712012-01-30 12:56:03 -08009595void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009596{
Glenn Kastend0539712012-01-30 12:56:03 -08009597 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009598 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009599 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9600 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009601 }
Eric Laurent59255e42011-07-27 19:49:51 -07009602 }
Eric Laurent59255e42011-07-27 19:49:51 -07009603}
9604
9605sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9606 const effect_uuid_t *type)
9607{
Glenn Kasten090f0192012-01-30 13:00:02 -08009608 sp<EffectModule> effect = getEffectFromType_l(type);
9609 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009610}
9611
9612void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9613 bool enabled)
9614{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009615 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009616 if (enabled) {
9617 if (index < 0) {
9618 // if the effect is not suspend check if all effects are suspended
9619 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9620 if (index < 0) {
9621 return;
9622 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009623 if (!isEffectEligibleForSuspend(effect->desc())) {
9624 return;
9625 }
Eric Laurent59255e42011-07-27 19:49:51 -07009626 setEffectSuspended_l(&effect->desc().type, enabled);
9627 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009628 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009629 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009630 return;
9631 }
Eric Laurent59255e42011-07-27 19:49:51 -07009632 }
Steve Block3856b092011-10-20 11:56:00 +01009633 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009634 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009635 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9636 // if effect is requested to suspended but was not yet enabled, supend it now.
9637 if (desc->mEffect == 0) {
9638 desc->mEffect = effect;
9639 effect->setEnabled(false);
9640 effect->setSuspended(true);
9641 }
9642 } else {
9643 if (index < 0) {
9644 return;
9645 }
Steve Block3856b092011-10-20 11:56:00 +01009646 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009647 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009648 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9649 desc->mEffect.clear();
9650 effect->setSuspended(false);
9651 }
9652}
9653
Mathias Agopian65ab4712010-07-14 17:59:35 -07009654#undef LOG_TAG
9655#define LOG_TAG "AudioFlinger"
9656
9657// ----------------------------------------------------------------------------
9658
9659status_t AudioFlinger::onTransact(
9660 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9661{
9662 return BnAudioFlinger::onTransact(code, data, reply, flags);
9663}
9664
Mathias Agopian65ab4712010-07-14 17:59:35 -07009665}; // namespace android