blob: a44fb3e1d3ac81c9311b79615e9ec783c2fa4f5b [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
Glenn Kasten2dd4bdd2012-08-29 11:10:32 -070079#include <media/nbaio/AudioStreamOutSink.h>
80#include <media/nbaio/MonoPipe.h>
81#include <media/nbaio/MonoPipeReader.h>
82#include <media/nbaio/Pipe.h>
83#include <media/nbaio/PipeReader.h>
84#include <media/nbaio/SourceAudioBufferProvider.h>
Glenn Kasten58912562012-04-03 10:45:00 -070085
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
Glenn Kasten3ed29202012-08-07 15:24:44 -0700168// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
169// for the track. The client then sub-divides this into smaller buffers for its use.
170// Currently the client uses double-buffering by default, but doesn't tell us about that.
171// So for now we just assume that client is double-buffered.
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700172// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
173// N-buffering, so AudioFlinger could allocate the right amount of memory.
Glenn Kasten3ed29202012-08-07 15:24:44 -0700174// See the client's minBufCount and mNotificationFramesAct calculations for details.
175static const int kFastTrackMultiplier = 2;
176
Mathias Agopian65ab4712010-07-14 17:59:35 -0700177// ----------------------------------------------------------------------------
178
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700179#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800180// To collect the amplifier usage
181static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800182 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
183 if (service == NULL) {
184 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800185 return;
186 }
187
188 service->addBatteryData(params);
189}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700190#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800191
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700192static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700193{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700194 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700195 int rc;
196
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700197 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
198 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
199 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
200 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700201 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700202 }
203 rc = audio_hw_device_open(mod, dev);
204 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
205 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
206 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700207 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700208 }
209 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
210 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
211 rc = BAD_VALUE;
212 goto out;
213 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700214 return 0;
215
216out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700217 *dev = NULL;
218 return rc;
219}
220
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221// ----------------------------------------------------------------------------
222
223AudioFlinger::AudioFlinger()
224 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800225 mPrimaryHardwareDev(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700226 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800227 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800228 mMasterMute(false),
229 mNextUniqueId(1),
230 mMode(AUDIO_MODE_INVALID),
231 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700232{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700233}
234
235void AudioFlinger::onFirstRef()
236{
Dima Zavin799a70e2011-04-18 16:57:27 -0700237 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700238
Eric Laurent93575202011-01-18 18:39:02 -0800239 Mutex::Autolock _l(mLock);
240
Dima Zavin799a70e2011-04-18 16:57:27 -0700241 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800242 char val_str[PROPERTY_VALUE_MAX] = { 0 };
243 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
244 uint32_t int_val;
245 if (1 == sscanf(val_str, "%u", &int_val)) {
246 mStandbyTimeInNsecs = milliseconds(int_val);
247 ALOGI("Using %u mSec as standby time.", int_val);
248 } else {
249 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
250 ALOGI("Using default %u mSec as standby time.",
251 (uint32_t)(mStandbyTimeInNsecs / 1000000));
252 }
253 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700254
Eric Laurenta4c5a552012-03-29 10:12:40 -0700255 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700256}
257
258AudioFlinger::~AudioFlinger()
259{
260 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700261 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700262 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700263 }
264 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700265 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700266 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700267 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700268
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800269 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
270 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700271 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
272 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700273 }
274}
275
Eric Laurenta4c5a552012-03-29 10:12:40 -0700276static const char * const audio_interfaces[] = {
277 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
278 AUDIO_HARDWARE_MODULE_ID_A2DP,
279 AUDIO_HARDWARE_MODULE_ID_USB,
280};
281#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
282
John Grossmanee578c02012-07-23 17:05:46 -0700283AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
284 audio_module_handle_t module,
285 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700286{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700287 // if module is 0, the request comes from an old policy manager and we should load
288 // well known modules
289 if (module == 0) {
290 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
291 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
292 loadHwModule_l(audio_interfaces[i]);
293 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700294 // then try to find a module supporting the requested device.
295 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
296 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
297 audio_hw_device_t *dev = audioHwDevice->hwDevice();
298 if ((dev->get_supported_devices != NULL) &&
299 (dev->get_supported_devices(dev) & devices) == devices)
300 return audioHwDevice;
301 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700302 } else {
303 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700304 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
305 if (audioHwDevice != NULL) {
306 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700307 }
308 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700309
Dima Zavin799a70e2011-04-18 16:57:27 -0700310 return NULL;
311}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700312
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700313void AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700314{
315 const size_t SIZE = 256;
316 char buffer[SIZE];
317 String8 result;
318
319 result.append("Clients:\n");
320 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800321 sp<Client> client = mClients.valueAt(i).promote();
322 if (client != 0) {
323 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
324 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700325 }
326 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700327
328 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800329 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700330 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
331 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800332 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700333 result.append(buffer);
334 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700336}
337
338
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700339void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700340{
341 const size_t SIZE = 256;
342 char buffer[SIZE];
343 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800344 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700345
John Grossman4ff14ba2012-02-08 16:37:41 -0800346 snprintf(buffer, SIZE, "Hardware status: %d\n"
347 "Standby Time mSec: %u\n",
348 hardwareStatus,
349 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700350 result.append(buffer);
351 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700352}
353
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700354void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700355{
356 const size_t SIZE = 256;
357 char buffer[SIZE];
358 String8 result;
359 snprintf(buffer, SIZE, "Permission Denial: "
360 "can't dump AudioFlinger from pid=%d, uid=%d\n",
361 IPCThreadState::self()->getCallingPid(),
362 IPCThreadState::self()->getCallingUid());
363 result.append(buffer);
364 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700365}
366
367static bool tryLock(Mutex& mutex)
368{
369 bool locked = false;
370 for (int i = 0; i < kDumpLockRetries; ++i) {
371 if (mutex.tryLock() == NO_ERROR) {
372 locked = true;
373 break;
374 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800375 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700376 }
377 return locked;
378}
379
380status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
381{
Glenn Kasten44deb052012-02-05 18:09:08 -0800382 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700383 dumpPermissionDenial(fd, args);
384 } else {
385 // get state of hardware lock
386 bool hardwareLocked = tryLock(mHardwareLock);
387 if (!hardwareLocked) {
388 String8 result(kHardwareLockedString);
389 write(fd, result.string(), result.size());
390 } else {
391 mHardwareLock.unlock();
392 }
393
394 bool locked = tryLock(mLock);
395
396 // failed to lock - AudioFlinger is probably deadlocked
397 if (!locked) {
398 String8 result(kDeadlockedString);
399 write(fd, result.string(), result.size());
400 }
401
402 dumpClients(fd, args);
403 dumpInternals(fd, args);
404
405 // dump playback threads
406 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
407 mPlaybackThreads.valueAt(i)->dump(fd, args);
408 }
409
410 // dump record threads
411 for (size_t i = 0; i < mRecordThreads.size(); i++) {
412 mRecordThreads.valueAt(i)->dump(fd, args);
413 }
414
Dima Zavin799a70e2011-04-18 16:57:27 -0700415 // dump all hardware devs
416 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700417 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700418 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700419 }
420 if (locked) mLock.unlock();
421 }
422 return NO_ERROR;
423}
424
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800425sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
426{
427 // If pid is already in the mClients wp<> map, then use that entry
428 // (for which promote() is always != 0), otherwise create a new entry and Client.
429 sp<Client> client = mClients.valueFor(pid).promote();
430 if (client == 0) {
431 client = new Client(this, pid);
432 mClients.add(pid, client);
433 }
434
435 return client;
436}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437
438// IAudioFlinger interface
439
440
441sp<IAudioTrack> AudioFlinger::createTrack(
442 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800443 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800445 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700446 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700447 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800448 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700449 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800450 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800451 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452 int *sessionId,
453 status_t *status)
454{
455 sp<PlaybackThread::Track> track;
456 sp<TrackHandle> trackHandle;
457 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700458 status_t lStatus;
459 int lSessionId;
460
Glenn Kasten263709e2012-01-06 08:40:01 -0800461 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
462 // but if someone uses binder directly they could bypass that and cause us to crash
463 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000464 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700465 lStatus = BAD_VALUE;
466 goto Exit;
467 }
468
469 {
470 Mutex::Autolock _l(mLock);
471 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700472 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700473 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000474 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700475 lStatus = BAD_VALUE;
476 goto Exit;
477 }
478
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800479 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700480
Steve Block3856b092011-10-20 11:56:00 +0100481 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700482 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700483 // check if an effect chain with the same session ID is present on another
484 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700485 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700486 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
487 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700488 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700489 if (sessions & PlaybackThread::EFFECT_SESSION) {
490 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700491 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700492 }
Eric Laurentde070132010-07-13 04:45:46 -0700493 }
494 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700495 lSessionId = *sessionId;
496 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700497 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700498 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700499 if (sessionId != NULL) {
500 *sessionId = lSessionId;
501 }
502 }
Steve Block3856b092011-10-20 11:56:00 +0100503 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700504
505 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800506 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700507
508 // move effect chain to this output thread if an effect on same session was waiting
509 // for a track to be created
510 if (lStatus == NO_ERROR && effectThread != NULL) {
511 Mutex::Autolock _dl(thread->mLock);
512 Mutex::Autolock _sl(effectThread->mLock);
513 moveEffectChain_l(lSessionId, effectThread, thread, true);
514 }
Eric Laurenta011e352012-03-29 15:51:43 -0700515
516 // Look for sync events awaiting for a session to be used.
517 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
518 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
519 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700520 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700521 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700522 } else {
523 mPendingSyncEvents[i]->cancel();
524 }
Eric Laurenta011e352012-03-29 15:51:43 -0700525 mPendingSyncEvents.removeAt(i);
526 i--;
527 }
528 }
529 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700530 }
531 if (lStatus == NO_ERROR) {
532 trackHandle = new TrackHandle(track);
533 } else {
534 // remove local strong reference to Client before deleting the Track so that the Client
535 // destructor is called by the TrackBase destructor with mLock held
536 client.clear();
537 track.clear();
538 }
539
540Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700541 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700542 *status = lStatus;
543 }
544 return trackHandle;
545}
546
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800547uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700548{
549 Mutex::Autolock _l(mLock);
550 PlaybackThread *thread = checkPlaybackThread_l(output);
551 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000552 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553 return 0;
554 }
555 return thread->sampleRate();
556}
557
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800558int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700559{
560 Mutex::Autolock _l(mLock);
561 PlaybackThread *thread = checkPlaybackThread_l(output);
562 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000563 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700564 return 0;
565 }
566 return thread->channelCount();
567}
568
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800569audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700570{
571 Mutex::Autolock _l(mLock);
572 PlaybackThread *thread = checkPlaybackThread_l(output);
573 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000574 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800575 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700576 }
577 return thread->format();
578}
579
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800580size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700581{
582 Mutex::Autolock _l(mLock);
583 PlaybackThread *thread = checkPlaybackThread_l(output);
584 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000585 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700586 return 0;
587 }
Glenn Kasten58912562012-04-03 10:45:00 -0700588 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
589 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700590 return thread->frameCount();
591}
592
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800593uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700594{
595 Mutex::Autolock _l(mLock);
596 PlaybackThread *thread = checkPlaybackThread_l(output);
597 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000598 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700599 return 0;
600 }
601 return thread->latency();
602}
603
604status_t AudioFlinger::setMasterVolume(float value)
605{
Eric Laurenta1884f92011-08-23 08:25:03 -0700606 status_t ret = initCheck();
607 if (ret != NO_ERROR) {
608 return ret;
609 }
610
Mathias Agopian65ab4712010-07-14 17:59:35 -0700611 // check calling permissions
612 if (!settingsAllowed()) {
613 return PERMISSION_DENIED;
614 }
615
Eric Laurenta4c5a552012-03-29 10:12:40 -0700616 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700617 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700618
John Grossmanee578c02012-07-23 17:05:46 -0700619 // Set master volume in the HALs which support it.
620 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
621 AutoMutex lock(mHardwareLock);
622 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800623
John Grossmanee578c02012-07-23 17:05:46 -0700624 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
625 if (dev->canSetMasterVolume()) {
626 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800627 }
John Grossmanee578c02012-07-23 17:05:46 -0700628 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700629 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700630
John Grossmanee578c02012-07-23 17:05:46 -0700631 // Now set the master volume in each playback thread. Playback threads
632 // assigned to HALs which do not have master volume support will apply
633 // master volume during the mix operation. Threads with HALs which do
634 // support master volume will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800635 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700636 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700637
638 return NO_ERROR;
639}
640
Glenn Kastenf78aee72012-01-04 11:00:47 -0800641status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700642{
Eric Laurenta1884f92011-08-23 08:25:03 -0700643 status_t ret = initCheck();
644 if (ret != NO_ERROR) {
645 return ret;
646 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700647
648 // check calling permissions
649 if (!settingsAllowed()) {
650 return PERMISSION_DENIED;
651 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800652 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000653 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700654 return BAD_VALUE;
655 }
656
657 { // scope for the lock
658 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700659 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700660 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700661 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700662 mHardwareStatus = AUDIO_HW_IDLE;
663 }
664
665 if (NO_ERROR == ret) {
666 Mutex::Autolock _l(mLock);
667 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800668 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700669 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700670 }
671
672 return ret;
673}
674
675status_t AudioFlinger::setMicMute(bool state)
676{
Eric Laurenta1884f92011-08-23 08:25:03 -0700677 status_t ret = initCheck();
678 if (ret != NO_ERROR) {
679 return ret;
680 }
681
Mathias Agopian65ab4712010-07-14 17:59:35 -0700682 // check calling permissions
683 if (!settingsAllowed()) {
684 return PERMISSION_DENIED;
685 }
686
687 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700688 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700689 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700690 ret = dev->set_mic_mute(dev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700691 mHardwareStatus = AUDIO_HW_IDLE;
692 return ret;
693}
694
695bool AudioFlinger::getMicMute() const
696{
Eric Laurenta1884f92011-08-23 08:25:03 -0700697 status_t ret = initCheck();
698 if (ret != NO_ERROR) {
699 return false;
700 }
701
Dima Zavinfce7a472011-04-19 22:30:36 -0700702 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800703 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700704 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700705 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700706 dev->get_mic_mute(dev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700707 mHardwareStatus = AUDIO_HW_IDLE;
708 return state;
709}
710
711status_t AudioFlinger::setMasterMute(bool muted)
712{
John Grossmand8f178d2012-07-20 14:51:35 -0700713 status_t ret = initCheck();
714 if (ret != NO_ERROR) {
715 return ret;
716 }
717
Mathias Agopian65ab4712010-07-14 17:59:35 -0700718 // check calling permissions
719 if (!settingsAllowed()) {
720 return PERMISSION_DENIED;
721 }
722
John Grossmanee578c02012-07-23 17:05:46 -0700723 Mutex::Autolock _l(mLock);
724 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700725
John Grossmanee578c02012-07-23 17:05:46 -0700726 // Set master mute in the HALs which support it.
727 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
728 AutoMutex lock(mHardwareLock);
729 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700730
John Grossmanee578c02012-07-23 17:05:46 -0700731 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
732 if (dev->canSetMasterMute()) {
733 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700734 }
John Grossmanee578c02012-07-23 17:05:46 -0700735 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700736 }
737
John Grossmanee578c02012-07-23 17:05:46 -0700738 // Now set the master mute in each playback thread. Playback threads
739 // assigned to HALs which do not have master mute support will apply master
740 // mute during the mix operation. Threads with HALs which do support master
741 // mute will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800742 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700743 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700744
745 return NO_ERROR;
746}
747
748float AudioFlinger::masterVolume() const
749{
Glenn Kasten98067102011-12-13 11:47:54 -0800750 Mutex::Autolock _l(mLock);
751 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700752}
753
754bool AudioFlinger::masterMute() const
755{
Glenn Kasten98067102011-12-13 11:47:54 -0800756 Mutex::Autolock _l(mLock);
757 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700758}
759
John Grossman4ff14ba2012-02-08 16:37:41 -0800760float AudioFlinger::masterVolume_l() const
761{
John Grossman4ff14ba2012-02-08 16:37:41 -0800762 return mMasterVolume;
763}
764
John Grossmand8f178d2012-07-20 14:51:35 -0700765bool AudioFlinger::masterMute_l() const
766{
John Grossmanee578c02012-07-23 17:05:46 -0700767 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700768}
769
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800770status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
771 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700772{
773 // check calling permissions
774 if (!settingsAllowed()) {
775 return PERMISSION_DENIED;
776 }
777
Glenn Kasten263709e2012-01-06 08:40:01 -0800778 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000779 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700780 return BAD_VALUE;
781 }
782
783 AutoMutex lock(mLock);
784 PlaybackThread *thread = NULL;
785 if (output) {
786 thread = checkPlaybackThread_l(output);
787 if (thread == NULL) {
788 return BAD_VALUE;
789 }
790 }
791
792 mStreamTypes[stream].volume = value;
793
794 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800795 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700796 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700797 }
798 } else {
799 thread->setStreamVolume(stream, value);
800 }
801
802 return NO_ERROR;
803}
804
Glenn Kastenfff6d712012-01-12 16:38:12 -0800805status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700806{
807 // check calling permissions
808 if (!settingsAllowed()) {
809 return PERMISSION_DENIED;
810 }
811
Glenn Kasten263709e2012-01-06 08:40:01 -0800812 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700813 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000814 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700815 return BAD_VALUE;
816 }
817
Eric Laurent93575202011-01-18 18:39:02 -0800818 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700819 mStreamTypes[stream].mute = muted;
820 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700821 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822
823 return NO_ERROR;
824}
825
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800826float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700827{
Glenn Kasten263709e2012-01-06 08:40:01 -0800828 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700829 return 0.0f;
830 }
831
832 AutoMutex lock(mLock);
833 float volume;
834 if (output) {
835 PlaybackThread *thread = checkPlaybackThread_l(output);
836 if (thread == NULL) {
837 return 0.0f;
838 }
839 volume = thread->streamVolume(stream);
840 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800841 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700842 }
843
844 return volume;
845}
846
Glenn Kastenfff6d712012-01-12 16:38:12 -0800847bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700848{
Glenn Kasten263709e2012-01-06 08:40:01 -0800849 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700850 return true;
851 }
852
Glenn Kasten6637baa2012-01-09 09:40:36 -0800853 AutoMutex lock(mLock);
854 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700855}
856
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800857status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700858{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800859 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700860 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
861 // check calling permissions
862 if (!settingsAllowed()) {
863 return PERMISSION_DENIED;
864 }
865
Mathias Agopian65ab4712010-07-14 17:59:35 -0700866 // ioHandle == 0 means the parameters are global to the audio hardware interface
867 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700868 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700869 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800870 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700871 AutoMutex lock(mHardwareLock);
872 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
873 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
874 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
875 status_t result = dev->set_parameters(dev, keyValuePairs.string());
876 final_result = result ?: final_result;
877 }
878 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800879 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700880 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
881 AudioParameter param = AudioParameter(keyValuePairs);
882 String8 value;
883 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700884 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
885 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700886 for (size_t i = 0; i < mRecordThreads.size(); i++) {
887 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -0700888 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -0700889 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
890 // collect all of the thread's session IDs
891 KeyedVector<int, bool> ids = thread->sessionIds();
892 // suspend effects associated with those session IDs
893 for (size_t j = 0; j < ids.size(); ++j) {
894 int sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700895 thread->setEffectSuspended(FX_IID_AEC,
896 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700897 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700898 thread->setEffectSuspended(FX_IID_NS,
899 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700900 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700901 }
902 }
Eric Laurentbee53372011-08-29 12:42:48 -0700903 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700904 }
905 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700906 String8 screenState;
907 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
908 bool isOff = screenState == "off";
909 if (isOff != (gScreenState & 1)) {
910 gScreenState = ((gScreenState & ~1) + 2) | isOff;
911 }
912 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700913 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700914 }
915
916 // hold a strong ref on thread in case closeOutput() or closeInput() is called
917 // and the thread is exited once the lock is released
918 sp<ThreadBase> thread;
919 {
920 Mutex::Autolock _l(mLock);
921 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -0700922 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700923 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800924 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700925 // indicate output device change to all input threads for pre processing
926 AudioParameter param = AudioParameter(keyValuePairs);
927 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700928 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
929 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700930 for (size_t i = 0; i < mRecordThreads.size(); i++) {
931 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
932 }
933 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700934 }
935 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800936 if (thread != 0) {
937 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700938 }
939 return BAD_VALUE;
940}
941
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800942String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700943{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800944// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700945// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
946
Eric Laurenta4c5a552012-03-29 10:12:40 -0700947 Mutex::Autolock _l(mLock);
948
Mathias Agopian65ab4712010-07-14 17:59:35 -0700949 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700950 String8 out_s8;
951
Dima Zavin799a70e2011-04-18 16:57:27 -0700952 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800953 char *s;
954 {
955 AutoMutex lock(mHardwareLock);
956 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700957 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800958 s = dev->get_parameters(dev, keys.string());
959 mHardwareStatus = AUDIO_HW_IDLE;
960 }
John Grossmanef7740b2012-02-09 11:28:36 -0800961 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700962 free(s);
963 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700964 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700965 }
966
Mathias Agopian65ab4712010-07-14 17:59:35 -0700967 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
968 if (playbackThread != NULL) {
969 return playbackThread->getParameters(keys);
970 }
971 RecordThread *recordThread = checkRecordThread_l(ioHandle);
972 if (recordThread != NULL) {
973 return recordThread->getParameters(keys);
974 }
975 return String8("");
976}
977
Glenn Kastendd8104c2012-07-02 12:42:44 -0700978size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
979 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700980{
Eric Laurenta1884f92011-08-23 08:25:03 -0700981 status_t ret = initCheck();
982 if (ret != NO_ERROR) {
983 return 0;
984 }
985
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800986 AutoMutex lock(mHardwareLock);
987 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700988 struct audio_config config = {
989 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -0700990 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700991 format: format,
992 };
John Grossmanee578c02012-07-23 17:05:46 -0700993 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
994 size_t size = dev->get_input_buffer_size(dev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800995 mHardwareStatus = AUDIO_HW_IDLE;
996 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700997}
998
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800999unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001000{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001001 Mutex::Autolock _l(mLock);
1002
1003 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1004 if (recordThread != NULL) {
1005 return recordThread->getInputFramesLost();
1006 }
1007 return 0;
1008}
1009
1010status_t AudioFlinger::setVoiceVolume(float value)
1011{
Eric Laurenta1884f92011-08-23 08:25:03 -07001012 status_t ret = initCheck();
1013 if (ret != NO_ERROR) {
1014 return ret;
1015 }
1016
Mathias Agopian65ab4712010-07-14 17:59:35 -07001017 // check calling permissions
1018 if (!settingsAllowed()) {
1019 return PERMISSION_DENIED;
1020 }
1021
1022 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001023 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001024 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001025 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001026 mHardwareStatus = AUDIO_HW_IDLE;
1027
1028 return ret;
1029}
1030
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001031status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1032 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001033{
1034 status_t status;
1035
1036 Mutex::Autolock _l(mLock);
1037
1038 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1039 if (playbackThread != NULL) {
1040 return playbackThread->getRenderPosition(halFrames, dspFrames);
1041 }
1042
1043 return BAD_VALUE;
1044}
1045
1046void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1047{
1048
1049 Mutex::Autolock _l(mLock);
1050
Glenn Kastenbb001922012-02-03 11:10:26 -08001051 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001052 if (mNotificationClients.indexOfKey(pid) < 0) {
1053 sp<NotificationClient> notificationClient = new NotificationClient(this,
1054 client,
1055 pid);
Steve Block3856b092011-10-20 11:56:00 +01001056 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001057
1058 mNotificationClients.add(pid, notificationClient);
1059
1060 sp<IBinder> binder = client->asBinder();
1061 binder->linkToDeath(notificationClient);
1062
1063 // the config change is always sent from playback or record threads to avoid deadlock
1064 // with AudioSystem::gLock
1065 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1066 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1067 }
1068
1069 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1070 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1071 }
1072 }
1073}
1074
1075void AudioFlinger::removeNotificationClient(pid_t pid)
1076{
1077 Mutex::Autolock _l(mLock);
1078
Glenn Kastena3b09252012-01-20 09:19:01 -08001079 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001080
Steve Block3856b092011-10-20 11:56:00 +01001081 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001082 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001083 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001084 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001085 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001086 ALOGV(" pid %d @ %d", ref->mPid, i);
1087 if (ref->mPid == pid) {
1088 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001089 mAudioSessionRefs.removeAt(i);
1090 delete ref;
1091 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001092 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001093 } else {
1094 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001095 }
1096 }
1097 if (removed) {
1098 purgeStaleEffects_l();
1099 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001100}
1101
1102// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001103void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001104{
1105 size_t size = mNotificationClients.size();
1106 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001107 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1108 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001109 }
1110}
1111
1112// removeClient_l() must be called with AudioFlinger::mLock held
1113void AudioFlinger::removeClient_l(pid_t pid)
1114{
Steve Block3856b092011-10-20 11:56:00 +01001115 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116 mClients.removeItem(pid);
1117}
1118
Eric Laurent717e1282012-06-29 16:36:52 -07001119// getEffectThread_l() must be called with AudioFlinger::mLock held
1120sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1121{
1122 sp<PlaybackThread> thread;
1123
1124 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1125 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1126 ALOG_ASSERT(thread == 0);
1127 thread = mPlaybackThreads.valueAt(i);
1128 }
1129 }
1130
1131 return thread;
1132}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133
1134// ----------------------------------------------------------------------------
1135
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001136AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurentf1c04f92012-08-28 14:26:53 -07001137 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001138 : Thread(false /*canCallJava*/),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001139 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001140 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001141 // mChannelMask
1142 mChannelCount(0),
1143 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1144 mParamStatus(NO_ERROR),
Eric Laurentf1c04f92012-08-28 14:26:53 -07001145 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
1146 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001147 // mName will be set by concrete (non-virtual) subclass
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001148 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001149{
1150}
1151
1152AudioFlinger::ThreadBase::~ThreadBase()
1153{
1154 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001155 // do not lock the mutex in destructor
1156 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001157 if (mPowerManager != 0) {
1158 sp<IBinder> binder = mPowerManager->asBinder();
1159 binder->unlinkToDeath(mDeathRecipient);
1160 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001161}
1162
1163void AudioFlinger::ThreadBase::exit()
1164{
Steve Block3856b092011-10-20 11:56:00 +01001165 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001167 // This lock prevents the following race in thread (uniprocessor for illustration):
1168 // if (!exitPending()) {
1169 // // context switch from here to exit()
1170 // // exit() calls requestExit(), what exitPending() observes
1171 // // exit() calls signal(), which is dropped since no waiters
1172 // // context switch back from exit() to here
1173 // mWaitWorkCV.wait(...);
1174 // // now thread is hung
1175 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001176 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001177 requestExit();
1178 mWaitWorkCV.signal();
1179 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001180 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1181 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001182 requestExitAndWait();
1183}
1184
Mathias Agopian65ab4712010-07-14 17:59:35 -07001185status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1186{
1187 status_t status;
1188
Steve Block3856b092011-10-20 11:56:00 +01001189 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001190 Mutex::Autolock _l(mLock);
1191
1192 mNewParameters.add(keyValuePairs);
1193 mWaitWorkCV.signal();
1194 // wait condition with timeout in case the thread loop has exited
1195 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001196 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001197 status = mParamStatus;
1198 mWaitWorkCV.signal();
1199 } else {
1200 status = TIMED_OUT;
1201 }
1202 return status;
1203}
1204
1205void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1206{
1207 Mutex::Autolock _l(mLock);
1208 sendConfigEvent_l(event, param);
1209}
1210
1211// sendConfigEvent_l() must be called with ThreadBase::mLock held
1212void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1213{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001214 ConfigEvent configEvent;
1215 configEvent.mEvent = event;
1216 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001217 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001218 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001219 mWaitWorkCV.signal();
1220}
1221
1222void AudioFlinger::ThreadBase::processConfigEvents()
1223{
1224 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001225 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001226 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001227 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001228 mConfigEvents.removeAt(0);
1229 // release mLock before locking AudioFlinger mLock: lock order is always
1230 // AudioFlinger then ThreadBase to avoid cross deadlock
1231 mLock.unlock();
1232 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001233 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001234 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001235 mLock.lock();
1236 }
1237 mLock.unlock();
1238}
1239
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001240void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001241{
1242 const size_t SIZE = 256;
1243 char buffer[SIZE];
1244 String8 result;
1245
1246 bool locked = tryLock(mLock);
1247 if (!locked) {
1248 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1249 write(fd, buffer, strlen(buffer));
1250 }
1251
Eric Laurent612bbb52012-03-14 15:03:26 -07001252 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1253 result.append(buffer);
1254 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1255 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001256 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1257 result.append(buffer);
1258 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1259 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001260 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1261 result.append(buffer);
1262 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001263 result.append(buffer);
1264 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1265 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001266 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1267 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001268 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1269 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001270 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001271 result.append(buffer);
1272
1273 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1274 result.append(buffer);
1275 result.append(" Index Command");
1276 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1277 snprintf(buffer, SIZE, "\n %02d ", i);
1278 result.append(buffer);
1279 result.append(mNewParameters[i]);
1280 }
1281
1282 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1283 result.append(buffer);
1284 snprintf(buffer, SIZE, " Index event param\n");
1285 result.append(buffer);
1286 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001287 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001288 result.append(buffer);
1289 }
1290 result.append("\n");
1291
1292 write(fd, result.string(), result.size());
1293
1294 if (locked) {
1295 mLock.unlock();
1296 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001297}
1298
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001299void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001300{
1301 const size_t SIZE = 256;
1302 char buffer[SIZE];
1303 String8 result;
1304
1305 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1306 write(fd, buffer, strlen(buffer));
1307
1308 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1309 sp<EffectChain> chain = mEffectChains[i];
1310 if (chain != 0) {
1311 chain->dump(fd, args);
1312 }
1313 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001314}
1315
Eric Laurentfeb0db62011-07-22 09:04:31 -07001316void AudioFlinger::ThreadBase::acquireWakeLock()
1317{
1318 Mutex::Autolock _l(mLock);
1319 acquireWakeLock_l();
1320}
1321
1322void AudioFlinger::ThreadBase::acquireWakeLock_l()
1323{
1324 if (mPowerManager == 0) {
1325 // use checkService() to avoid blocking if power service is not up yet
1326 sp<IBinder> binder =
1327 defaultServiceManager()->checkService(String16("power"));
1328 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001329 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001330 } else {
1331 mPowerManager = interface_cast<IPowerManager>(binder);
1332 binder->linkToDeath(mDeathRecipient);
1333 }
1334 }
1335 if (mPowerManager != 0) {
1336 sp<IBinder> binder = new BBinder();
1337 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1338 binder,
1339 String16(mName));
1340 if (status == NO_ERROR) {
1341 mWakeLockToken = binder;
1342 }
Steve Block3856b092011-10-20 11:56:00 +01001343 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001344 }
1345}
1346
1347void AudioFlinger::ThreadBase::releaseWakeLock()
1348{
1349 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001350 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001351}
1352
1353void AudioFlinger::ThreadBase::releaseWakeLock_l()
1354{
1355 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001356 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001357 if (mPowerManager != 0) {
1358 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1359 }
1360 mWakeLockToken.clear();
1361 }
1362}
1363
1364void AudioFlinger::ThreadBase::clearPowerManager()
1365{
1366 Mutex::Autolock _l(mLock);
1367 releaseWakeLock_l();
1368 mPowerManager.clear();
1369}
1370
1371void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1372{
1373 sp<ThreadBase> thread = mThread.promote();
1374 if (thread != 0) {
1375 thread->clearPowerManager();
1376 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001377 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001378}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001379
Eric Laurent59255e42011-07-27 19:49:51 -07001380void AudioFlinger::ThreadBase::setEffectSuspended(
1381 const effect_uuid_t *type, bool suspend, int sessionId)
1382{
1383 Mutex::Autolock _l(mLock);
1384 setEffectSuspended_l(type, suspend, sessionId);
1385}
1386
1387void AudioFlinger::ThreadBase::setEffectSuspended_l(
1388 const effect_uuid_t *type, bool suspend, int sessionId)
1389{
Glenn Kasten090f0192012-01-30 13:00:02 -08001390 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001391 if (chain != 0) {
1392 if (type != NULL) {
1393 chain->setEffectSuspended_l(type, suspend);
1394 } else {
1395 chain->setEffectSuspendedAll_l(suspend);
1396 }
1397 }
1398
1399 updateSuspendedSessions_l(type, suspend, sessionId);
1400}
1401
1402void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1403{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001404 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001405 if (index < 0) {
1406 return;
1407 }
1408
Glenn Kasten0a7af182012-07-09 16:09:19 -07001409 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1410 mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001411
1412 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001413 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001414 for (int j = 0; j < desc->mRefCount; j++) {
1415 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1416 chain->setEffectSuspendedAll_l(true);
1417 } else {
Steve Block3856b092011-10-20 11:56:00 +01001418 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001419 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001420 chain->setEffectSuspended_l(&desc->mType, true);
1421 }
1422 }
1423 }
1424}
1425
Eric Laurent59255e42011-07-27 19:49:51 -07001426void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1427 bool suspend,
1428 int sessionId)
1429{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001430 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001431
1432 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1433
1434 if (suspend) {
1435 if (index >= 0) {
Glenn Kasten0a7af182012-07-09 16:09:19 -07001436 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001437 } else {
1438 mSuspendedSessions.add(sessionId, sessionEffects);
1439 }
1440 } else {
1441 if (index < 0) {
1442 return;
1443 }
Glenn Kasten0a7af182012-07-09 16:09:19 -07001444 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001445 }
1446
1447
1448 int key = EffectChain::kKeyForSuspendAll;
1449 if (type != NULL) {
1450 key = type->timeLow;
1451 }
1452 index = sessionEffects.indexOfKey(key);
1453
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001454 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001455 if (suspend) {
1456 if (index >= 0) {
1457 desc = sessionEffects.valueAt(index);
1458 } else {
1459 desc = new SuspendedSessionDesc();
1460 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001461 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001462 }
1463 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001464 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001465 }
1466 desc->mRefCount++;
1467 } else {
1468 if (index < 0) {
1469 return;
1470 }
1471 desc = sessionEffects.valueAt(index);
1472 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001473 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001474 sessionEffects.removeItemsAt(index);
1475 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001476 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001477 sessionId);
1478 mSuspendedSessions.removeItem(sessionId);
1479 }
1480 }
1481 }
1482 if (!sessionEffects.isEmpty()) {
1483 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1484 }
1485}
1486
1487void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1488 bool enabled,
1489 int sessionId)
1490{
1491 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001492 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1493}
Eric Laurent59255e42011-07-27 19:49:51 -07001494
Eric Laurenta85a74a2011-10-19 11:44:54 -07001495void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1496 bool enabled,
1497 int sessionId)
1498{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001499 if (mType != RECORD) {
1500 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1501 // another session. This gives the priority to well behaved effect control panels
1502 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001503 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1504 // global effects
1505 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001506 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1507 }
1508 }
Eric Laurent59255e42011-07-27 19:49:51 -07001509
1510 sp<EffectChain> chain = getEffectChain_l(sessionId);
1511 if (chain != 0) {
1512 chain->checkSuspendOnEffectEnabled(effect, enabled);
1513 }
1514}
1515
Mathias Agopian65ab4712010-07-14 17:59:35 -07001516// ----------------------------------------------------------------------------
1517
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001518AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1519 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001520 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001521 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001522 type_t type)
Eric Laurentf1c04f92012-08-28 14:26:53 -07001523 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001524 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001525 // mStreamTypes[] initialized in constructor body
1526 mOutput(output),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001527 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001528 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001529 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001530 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001531 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001532 // index 0 is reserved for normal mixer's submix
1533 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001534{
Glenn Kasten480b4682012-02-28 12:30:08 -08001535 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001536
John Grossmanee578c02012-07-23 17:05:46 -07001537 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1538 // it would be safer to explicitly pass initial masterVolume/masterMute as
1539 // parameter.
1540 //
1541 // If the HAL we are using has support for master volume or master mute,
1542 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1543 // and the mute set to false).
1544 mMasterVolume = audioFlinger->masterVolume_l();
1545 mMasterMute = audioFlinger->masterMute_l();
1546 if (mOutput && mOutput->audioHwDev) {
1547 if (mOutput->audioHwDev->canSetMasterVolume()) {
1548 mMasterVolume = 1.0;
1549 }
1550
1551 if (mOutput->audioHwDev->canSetMasterMute()) {
1552 mMasterMute = false;
1553 }
1554 }
1555
Mathias Agopian65ab4712010-07-14 17:59:35 -07001556 readOutputParameters();
1557
Glenn Kasten263709e2012-01-06 08:40:01 -08001558 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001559 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1560 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1561 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001562 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1563 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001564 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001565 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1566 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001567}
1568
1569AudioFlinger::PlaybackThread::~PlaybackThread()
1570{
1571 delete [] mMixBuffer;
1572}
1573
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001574void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001575{
1576 dumpInternals(fd, args);
1577 dumpTracks(fd, args);
1578 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001579}
1580
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001581void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001582{
1583 const size_t SIZE = 256;
1584 char buffer[SIZE];
1585 String8 result;
1586
Glenn Kasten58912562012-04-03 10:45:00 -07001587 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1588 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1589 const stream_type_t *st = &mStreamTypes[i];
1590 if (i > 0) {
1591 result.appendFormat(", ");
1592 }
1593 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1594 if (st->mute) {
1595 result.append("M");
1596 }
1597 }
1598 result.append("\n");
1599 write(fd, result.string(), result.length());
1600 result.clear();
1601
Mathias Agopian65ab4712010-07-14 17:59:35 -07001602 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1603 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001604 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001605 for (size_t i = 0; i < mTracks.size(); ++i) {
1606 sp<Track> track = mTracks[i];
1607 if (track != 0) {
1608 track->dump(buffer, SIZE);
1609 result.append(buffer);
1610 }
1611 }
1612
1613 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1614 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001615 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001616 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001617 sp<Track> track = mActiveTracks[i].promote();
1618 if (track != 0) {
1619 track->dump(buffer, SIZE);
1620 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001621 }
1622 }
1623 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001624
1625 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1626 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1627 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1628 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001629}
1630
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001631void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001632{
1633 const size_t SIZE = 256;
1634 char buffer[SIZE];
1635 String8 result;
1636
1637 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1638 result.append(buffer);
1639 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1640 result.append(buffer);
1641 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1642 result.append(buffer);
1643 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1644 result.append(buffer);
1645 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1646 result.append(buffer);
1647 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1648 result.append(buffer);
1649 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1650 result.append(buffer);
1651 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001652 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001653
1654 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001655}
1656
1657// Thread virtuals
1658status_t AudioFlinger::PlaybackThread::readyToRun()
1659{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001660 status_t status = initCheck();
1661 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001662 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001663 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001664 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001665 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001666 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001667}
1668
1669void AudioFlinger::PlaybackThread::onFirstRef()
1670{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001671 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001672}
1673
1674// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001675sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001676 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001677 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001678 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001679 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001680 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001681 int frameCount,
1682 const sp<IMemory>& sharedBuffer,
1683 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001684 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001685 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001686 status_t *status)
1687{
1688 sp<Track> track;
1689 status_t lStatus;
1690
Glenn Kasten73d22752012-03-19 13:38:30 -07001691 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1692
1693 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001694 if (flags & IAudioFlinger::TRACK_FAST) {
1695 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001696 // not timed
1697 (!isTimed) &&
1698 // either of these use cases:
1699 (
1700 // use case 1: shared buffer with any frame count
1701 (
1702 (sharedBuffer != 0)
1703 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001704 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001705 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001706 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001707 ((frameCount == 0) ||
Glenn Kasten3ed29202012-08-07 15:24:44 -07001708 (frameCount >= (int) (mFrameCount * kFastTrackMultiplier)))
Glenn Kasten73d22752012-03-19 13:38:30 -07001709 )
1710 ) &&
1711 // PCM data
1712 audio_is_linear_pcm(format) &&
1713 // mono or stereo
1714 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1715 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001716#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001717 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001718 (sampleRate == mSampleRate) &&
1719#endif
1720 // normal mixer has an associated fast mixer
1721 hasFastMixer() &&
1722 // there are sufficient fast track slots available
1723 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001724 // FIXME test that MixerThread for this fast track has a capable output HAL
1725 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001726 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001727 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1728 if (frameCount == 0) {
Glenn Kasten3ed29202012-08-07 15:24:44 -07001729 frameCount = mFrameCount * kFastTrackMultiplier;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001730 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001731 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001732 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001733 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001734 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07001735 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001736 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1737 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1738 audio_is_linear_pcm(format),
1739 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001740 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001741 // For compatibility with AudioTrack calculation, buffer depth is forced
1742 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1743 // This is probably too conservative, but legacy application code may depend on it.
1744 // If you change this calculation, also review the start threshold which is related.
1745 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1746 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1747 if (minBufCount < 2) {
1748 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001749 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001750 int minFrameCount = mNormalFrameCount * minBufCount;
1751 if (frameCount < minFrameCount) {
1752 frameCount = minFrameCount;
1753 }
1754 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001755 }
1756
Mathias Agopian65ab4712010-07-14 17:59:35 -07001757 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001758 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1759 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001760 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001761 "for output %p with format %d",
1762 sampleRate, format, channelMask, mOutput, mFormat);
1763 lStatus = BAD_VALUE;
1764 goto Exit;
1765 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001766 }
1767 } else {
1768 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1769 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001770 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001771 lStatus = BAD_VALUE;
1772 goto Exit;
1773 }
1774 }
1775
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001776 lStatus = initCheck();
1777 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001778 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779 goto Exit;
1780 }
1781
1782 { // scope for mLock
1783 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001784
1785 // all tracks in same audio session must share the same routing strategy otherwise
1786 // conflicts will happen when tracks are moved from one output to another by audio policy
1787 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001788 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001789 for (size_t i = 0; i < mTracks.size(); ++i) {
1790 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001791 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001792 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001793 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001794 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001795 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001796 lStatus = BAD_VALUE;
1797 goto Exit;
1798 }
1799 }
1800 }
1801
John Grossman4ff14ba2012-02-08 16:37:41 -08001802 if (!isTimed) {
1803 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001804 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001805 } else {
1806 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1807 channelMask, frameCount, sharedBuffer, sessionId);
1808 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001809 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001810 lStatus = NO_MEMORY;
1811 goto Exit;
1812 }
1813 mTracks.add(track);
1814
1815 sp<EffectChain> chain = getEffectChain_l(sessionId);
1816 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001817 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001818 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001819 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001820 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001821 }
1822 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001823
Glenn Kasten3acbd052012-02-28 10:39:56 -08001824 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1825 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1826 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1827 // so ask activity manager to do this on our behalf
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07001828 int err = requestPriority(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001829 if (err != 0) {
1830 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07001831 kPriorityAudioApp, callingPid, tid, err);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001832 }
1833 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001834
Mathias Agopian65ab4712010-07-14 17:59:35 -07001835 lStatus = NO_ERROR;
1836
1837Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001838 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001839 *status = lStatus;
1840 }
1841 return track;
1842}
1843
Eric Laurente737cda2012-05-22 18:55:44 -07001844uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1845{
1846 if (mFastMixer != NULL) {
1847 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1848 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1849 }
1850 return latency;
1851}
1852
1853uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1854{
1855 return latency;
1856}
1857
Mathias Agopian65ab4712010-07-14 17:59:35 -07001858uint32_t AudioFlinger::PlaybackThread::latency() const
1859{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001860 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001861 return latency_l();
1862}
1863uint32_t AudioFlinger::PlaybackThread::latency_l() const
1864{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001865 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001866 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001867 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868 return 0;
1869 }
1870}
1871
Glenn Kasten6637baa2012-01-09 09:40:36 -08001872void AudioFlinger::PlaybackThread::setMasterVolume(float value)
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 volume in SW if our HAL can do it for us.
1876 if (mOutput && mOutput->audioHwDev &&
1877 mOutput->audioHwDev->canSetMasterVolume()) {
1878 mMasterVolume = 1.0;
1879 } else {
1880 mMasterVolume = value;
1881 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001882}
1883
Glenn Kasten6637baa2012-01-09 09:40:36 -08001884void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001885{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001886 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001887 // Don't apply master mute in SW if our HAL can do it for us.
1888 if (mOutput && mOutput->audioHwDev &&
1889 mOutput->audioHwDev->canSetMasterMute()) {
1890 mMasterMute = false;
1891 } else {
1892 mMasterMute = muted;
1893 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001894}
1895
Glenn Kasten6637baa2012-01-09 09:40:36 -08001896void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
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 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001900}
1901
Glenn Kasten6637baa2012-01-09 09:40:36 -08001902void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001903{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001904 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001905 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001906}
1907
Glenn Kastenfff6d712012-01-12 16:38:12 -08001908float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001909{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001910 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001911 return mStreamTypes[stream].volume;
1912}
1913
Mathias Agopian65ab4712010-07-14 17:59:35 -07001914// addTrack_l() must be called with ThreadBase::mLock held
1915status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1916{
1917 status_t status = ALREADY_EXISTS;
1918
1919 // set retry count for buffer fill
1920 track->mRetryCount = kMaxTrackStartupRetries;
1921 if (mActiveTracks.indexOf(track) < 0) {
1922 // the track is newly added, make sure it fills up all its
1923 // buffers before playing. This is to ensure the client will
1924 // effectively get the latency it requested.
1925 track->mFillingUpStatus = Track::FS_FILLING;
1926 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001927 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001928 mActiveTracks.add(track);
1929 if (track->mainBuffer() != mMixBuffer) {
1930 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1931 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001932 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001933 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001934 }
1935 }
1936
1937 status = NO_ERROR;
1938 }
1939
Steve Block3856b092011-10-20 11:56:00 +01001940 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001941 mWaitWorkCV.broadcast();
1942
1943 return status;
1944}
1945
1946// destroyTrack_l() must be called with ThreadBase::mLock held
1947void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1948{
1949 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001950 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001952 removeTrack_l(track);
1953 }
1954}
1955
1956void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1957{
Eric Laurent29864602012-05-08 18:57:51 -07001958 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001959 mTracks.remove(track);
1960 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001961 // redundant as track is about to be destroyed, for dumpsys only
1962 track->mName = -1;
1963 if (track->isFastTrack()) {
1964 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001965 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001966 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1967 mFastTrackAvailMask |= 1 << index;
1968 // redundant as track is about to be destroyed, for dumpsys only
1969 track->mFastIndex = -1;
1970 }
Eric Laurentb469b942011-05-09 12:09:06 -07001971 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1972 if (chain != 0) {
1973 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001974 }
1975}
1976
1977String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1978{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001979 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001980 char *s;
1981
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001982 Mutex::Autolock _l(mLock);
1983 if (initCheck() != NO_ERROR) {
1984 return out_s8;
1985 }
1986
Dima Zavin799a70e2011-04-18 16:57:27 -07001987 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001988 out_s8 = String8(s);
1989 free(s);
1990 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001991}
1992
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001993// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001994void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1995 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001996 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001997
Steve Block3856b092011-10-20 11:56:00 +01001998 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001999
2000 switch (event) {
2001 case AudioSystem::OUTPUT_OPENED:
2002 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002003 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002004 desc.samplingRate = mSampleRate;
2005 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07002006 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002007 desc.latency = latency();
2008 param2 = &desc;
2009 break;
2010
2011 case AudioSystem::STREAM_CONFIG_CHANGED:
2012 param2 = &param;
2013 case AudioSystem::OUTPUT_CLOSED:
2014 default:
2015 break;
2016 }
2017 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2018}
2019
2020void AudioFlinger::PlaybackThread::readOutputParameters()
2021{
Dima Zavin799a70e2011-04-18 16:57:27 -07002022 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002023 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2024 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07002025 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002026 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002027 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002028 if (mFrameCount & 15) {
2029 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2030 mFrameCount);
2031 }
2032
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002033 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002034 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002035 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002036 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002037 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2038 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2039 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2040 maxNormalFrameCount = maxNormalFrameCount & ~15;
2041 if (maxNormalFrameCount < minNormalFrameCount) {
2042 maxNormalFrameCount = minNormalFrameCount;
2043 }
2044 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2045 if (multiplier <= 1.0) {
2046 multiplier = 1.0;
2047 } else if (multiplier <= 2.0) {
2048 if (2 * mFrameCount <= maxNormalFrameCount) {
2049 multiplier = 2.0;
2050 } else {
2051 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2052 }
2053 } else {
2054 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2055 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2056 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2057 // FIXME this rounding up should not be done if no HAL SRC
2058 uint32_t truncMult = (uint32_t) multiplier;
2059 if ((truncMult & 1)) {
2060 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2061 ++truncMult;
2062 }
2063 }
2064 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002065 }
Glenn Kasten58912562012-04-03 10:45:00 -07002066 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002067 mNormalFrameCount = multiplier * mFrameCount;
2068 // round up to nearest 16 frames to satisfy AudioMixer
2069 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002070 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002071
Glenn Kastene9dd0172012-01-27 18:08:45 -08002072 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002073 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2074 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002075
Eric Laurentde070132010-07-13 04:45:46 -07002076 // force reconfiguration of effect chains and engines to take new buffer size and audio
2077 // parameters into account
2078 // Note that mLock is not held when readOutputParameters() is called from the constructor
2079 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2080 // matter.
2081 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2082 Vector< sp<EffectChain> > effectChains = mEffectChains;
2083 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002084 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002085 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002086}
2087
Eric Laurente737cda2012-05-22 18:55:44 -07002088
Mathias Agopian65ab4712010-07-14 17:59:35 -07002089status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2090{
Glenn Kastena0d68332012-01-27 16:47:15 -08002091 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002092 return BAD_VALUE;
2093 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002094 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002095 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002096 return INVALID_OPERATION;
2097 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002098 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002099
Dima Zavin799a70e2011-04-18 16:57:27 -07002100 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002101}
2102
Glenn Kasten106e8a42012-08-02 13:37:12 -07002103uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002104{
2105 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002106 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002107 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002108 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002109 }
2110
2111 for (size_t i = 0; i < mTracks.size(); ++i) {
2112 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002113 if (sessionId == track->sessionId() &&
2114 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002115 result |= TRACK_SESSION;
2116 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002117 }
2118 }
2119
Eric Laurent39e94f82010-07-28 01:32:47 -07002120 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002121}
2122
Eric Laurentde070132010-07-13 04:45:46 -07002123uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2124{
Dima Zavinfce7a472011-04-19 22:30:36 -07002125 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002126 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002127 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2128 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002129 }
2130 for (size_t i = 0; i < mTracks.size(); i++) {
2131 sp<Track> track = mTracks[i];
2132 if (sessionId == track->sessionId() &&
2133 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002134 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002135 }
2136 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002137 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002138}
2139
Mathias Agopian65ab4712010-07-14 17:59:35 -07002140
Glenn Kastenaed850d2012-01-26 09:46:34 -08002141AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002142{
2143 Mutex::Autolock _l(mLock);
2144 return mOutput;
2145}
2146
2147AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2148{
2149 Mutex::Autolock _l(mLock);
2150 AudioStreamOut *output = mOutput;
2151 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002152 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2153 // must push a NULL and wait for ack
2154 mOutputSink.clear();
2155 mPipeSink.clear();
2156 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002157 return output;
2158}
2159
2160// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002161audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002162{
2163 if (mOutput == NULL) {
2164 return NULL;
2165 }
2166 return &mOutput->stream->common;
2167}
2168
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002169uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002170{
Eric Laurentab9071b2012-06-04 13:45:29 -07002171 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002172}
2173
Eric Laurenta011e352012-03-29 15:51:43 -07002174status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2175{
2176 if (!isValidSyncEvent(event)) {
2177 return BAD_VALUE;
2178 }
2179
2180 Mutex::Autolock _l(mLock);
2181
2182 for (size_t i = 0; i < mTracks.size(); ++i) {
2183 sp<Track> track = mTracks[i];
2184 if (event->triggerSession() == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07002185 (void) track->setSyncEvent(event);
Eric Laurenta011e352012-03-29 15:51:43 -07002186 return NO_ERROR;
2187 }
2188 }
2189
2190 return NAME_NOT_FOUND;
2191}
2192
Glenn Kasten106e8a42012-08-02 13:37:12 -07002193bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07002194{
Glenn Kasten0dbb3562012-08-02 16:36:50 -07002195 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
Eric Laurenta011e352012-03-29 15:51:43 -07002196}
2197
Eric Laurent44a957f2012-05-15 15:26:05 -07002198void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2199{
2200 size_t count = tracksToRemove.size();
2201 if (CC_UNLIKELY(count)) {
2202 for (size_t i = 0 ; i < count ; i++) {
2203 const sp<Track>& track = tracksToRemove.itemAt(i);
2204 if ((track->sharedBuffer() != 0) &&
2205 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2206 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2207 }
2208 }
2209 }
2210
2211}
2212
Mathias Agopian65ab4712010-07-14 17:59:35 -07002213// ----------------------------------------------------------------------------
2214
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002215AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002216 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002217 : PlaybackThread(audioFlinger, output, id, device, type),
2218 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002219 // mFastMixer below
2220 mFastMixerFutex(0)
2221 // mOutputSink below
2222 // mPipeSink below
2223 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002224{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002225 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002226 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002227 "mFrameCount=%d, mNormalFrameCount=%d",
2228 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2229 mNormalFrameCount);
2230 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2231
Mathias Agopian65ab4712010-07-14 17:59:35 -07002232 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002233 if (mChannelCount != FCC_2) {
2234 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002235 }
Glenn Kasten58912562012-04-03 10:45:00 -07002236
2237 // create an NBAIO sink for the HAL output stream, and negotiate
2238 mOutputSink = new AudioStreamOutSink(output->stream);
2239 size_t numCounterOffers = 0;
2240 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2241 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2242 ALOG_ASSERT(index == 0);
2243
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002244 // initialize fast mixer depending on configuration
2245 bool initFastMixer;
2246 switch (kUseFastMixer) {
2247 case FastMixer_Never:
2248 initFastMixer = false;
2249 break;
2250 case FastMixer_Always:
2251 initFastMixer = true;
2252 break;
2253 case FastMixer_Static:
2254 case FastMixer_Dynamic:
2255 initFastMixer = mFrameCount < mNormalFrameCount;
2256 break;
2257 }
2258 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002259
2260 // create a MonoPipe to connect our submix to FastMixer
2261 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002262 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2263 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2264 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2265 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002266 const NBAIO_Format offers[1] = {format};
2267 size_t numCounterOffers = 0;
2268 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2269 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002270 monoPipe->setAvgFrames((mScreenState & 1) ?
2271 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002272 mPipeSink = monoPipe;
2273
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002274#ifdef TEE_SINK_FRAMES
2275 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2276 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2277 numCounterOffers = 0;
2278 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2279 ALOG_ASSERT(index == 0);
2280 mTeeSink = teeSink;
2281 PipeReader *teeSource = new PipeReader(*teeSink);
2282 numCounterOffers = 0;
2283 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2284 ALOG_ASSERT(index == 0);
2285 mTeeSource = teeSource;
2286#endif
2287
Glenn Kasten58912562012-04-03 10:45:00 -07002288 // create fast mixer and configure it initially with just one fast track for our submix
2289 mFastMixer = new FastMixer();
2290 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002291#ifdef STATE_QUEUE_DUMP
2292 sq->setObserverDump(&mStateQueueObserverDump);
2293 sq->setMutatorDump(&mStateQueueMutatorDump);
2294#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002295 FastMixerState *state = sq->begin();
2296 FastTrack *fastTrack = &state->mFastTracks[0];
2297 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2298 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2299 fastTrack->mVolumeProvider = NULL;
2300 fastTrack->mGeneration++;
2301 state->mFastTracksGen++;
2302 state->mTrackMask = 1;
2303 // fast mixer will use the HAL output sink
2304 state->mOutputSink = mOutputSink.get();
2305 state->mOutputSinkGen++;
2306 state->mFrameCount = mFrameCount;
2307 state->mCommand = FastMixerState::COLD_IDLE;
2308 // already done in constructor initialization list
2309 //mFastMixerFutex = 0;
2310 state->mColdFutexAddr = &mFastMixerFutex;
2311 state->mColdGen++;
2312 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002313 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002314 sq->end();
2315 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2316
2317 // start the fast mixer
2318 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002319 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002320 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002321 if (err != 0) {
2322 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002323 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002324 }
Glenn Kasten58912562012-04-03 10:45:00 -07002325
Glenn Kastenc15d6652012-05-30 14:52:57 -07002326#ifdef AUDIO_WATCHDOG
2327 // create and start the watchdog
2328 mAudioWatchdog = new AudioWatchdog();
2329 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2330 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2331 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002332 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002333 if (err != 0) {
2334 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002335 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002336 }
2337#endif
2338
Glenn Kasten58912562012-04-03 10:45:00 -07002339 } else {
2340 mFastMixer = NULL;
2341 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002342
2343 switch (kUseFastMixer) {
2344 case FastMixer_Never:
2345 case FastMixer_Dynamic:
2346 mNormalSink = mOutputSink;
2347 break;
2348 case FastMixer_Always:
2349 mNormalSink = mPipeSink;
2350 break;
2351 case FastMixer_Static:
2352 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2353 break;
2354 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002355}
2356
2357AudioFlinger::MixerThread::~MixerThread()
2358{
Glenn Kasten58912562012-04-03 10:45:00 -07002359 if (mFastMixer != NULL) {
2360 FastMixerStateQueue *sq = mFastMixer->sq();
2361 FastMixerState *state = sq->begin();
2362 if (state->mCommand == FastMixerState::COLD_IDLE) {
2363 int32_t old = android_atomic_inc(&mFastMixerFutex);
2364 if (old == -1) {
2365 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2366 }
2367 }
2368 state->mCommand = FastMixerState::EXIT;
2369 sq->end();
2370 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2371 mFastMixer->join();
2372 // Though the fast mixer thread has exited, it's state queue is still valid.
2373 // We'll use that extract the final state which contains one remaining fast track
2374 // corresponding to our sub-mix.
2375 state = sq->begin();
2376 ALOG_ASSERT(state->mTrackMask == 1);
2377 FastTrack *fastTrack = &state->mFastTracks[0];
2378 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2379 delete fastTrack->mBufferProvider;
2380 sq->end(false /*didModify*/);
2381 delete mFastMixer;
Glenn Kastenc15d6652012-05-30 14:52:57 -07002382 if (mAudioWatchdog != 0) {
2383 mAudioWatchdog->requestExit();
2384 mAudioWatchdog->requestExitAndWait();
2385 mAudioWatchdog.clear();
2386 }
Glenn Kasten58912562012-04-03 10:45:00 -07002387 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002388 delete mAudioMixer;
2389}
2390
Glenn Kasten83efdd02012-02-24 07:21:32 -08002391class CpuStats {
2392public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002393 CpuStats();
2394 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002395#ifdef DEBUG_CPU_USAGE
2396private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002397 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2398 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2399
2400 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2401
2402 int mCpuNum; // thread's current CPU number
2403 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002404#endif
2405};
2406
Glenn Kasten190a46f2012-03-06 11:27:10 -08002407CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002408#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002409 : mCpuNum(-1), mCpukHz(-1)
2410#endif
2411{
2412}
2413
2414void CpuStats::sample(const String8 &title) {
2415#ifdef DEBUG_CPU_USAGE
2416 // get current thread's delta CPU time in wall clock ns
2417 double wcNs;
2418 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2419
2420 // record sample for wall clock statistics
2421 if (valid) {
2422 mWcStats.sample(wcNs);
2423 }
2424
2425 // get the current CPU number
2426 int cpuNum = sched_getcpu();
2427
2428 // get the current CPU frequency in kHz
2429 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2430
2431 // check if either CPU number or frequency changed
2432 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2433 mCpuNum = cpuNum;
2434 mCpukHz = cpukHz;
2435 // ignore sample for purposes of cycles
2436 valid = false;
2437 }
2438
2439 // if no change in CPU number or frequency, then record sample for cycle statistics
2440 if (valid && mCpukHz > 0) {
2441 double cycles = wcNs * cpukHz * 0.000001;
2442 mHzStats.sample(cycles);
2443 }
2444
2445 unsigned n = mWcStats.n();
2446 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002447 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002448 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002449 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2450 double perLoop = elapsed / (double) n;
2451 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002452 double perLoop1k = perLoop * 0.001;
2453 double mean = mWcStats.mean();
2454 double stddev = mWcStats.stddev();
2455 double minimum = mWcStats.minimum();
2456 double maximum = mWcStats.maximum();
2457 double meanCycles = mHzStats.mean();
2458 double stddevCycles = mHzStats.stddev();
2459 double minCycles = mHzStats.minimum();
2460 double maxCycles = mHzStats.maximum();
2461 mCpuUsage.resetElapsed();
2462 mWcStats.reset();
2463 mHzStats.reset();
2464 ALOGD("CPU usage for %s over past %.1f secs\n"
2465 " (%u mixer loops at %.1f mean ms per loop):\n"
2466 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2467 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2468 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2469 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002470 elapsed * .000000001, n, perLoop * .000001,
2471 mean * .001,
2472 stddev * .001,
2473 minimum * .001,
2474 maximum * .001,
2475 mean / perLoop100,
2476 stddev / perLoop100,
2477 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002478 maximum / perLoop100,
2479 meanCycles / perLoop1k,
2480 stddevCycles / perLoop1k,
2481 minCycles / perLoop1k,
2482 maxCycles / perLoop1k);
2483
Glenn Kasten83efdd02012-02-24 07:21:32 -08002484 }
2485 }
2486#endif
2487};
2488
Glenn Kasten37d825e2012-02-24 07:21:48 -08002489void AudioFlinger::PlaybackThread::checkSilentMode_l()
2490{
2491 if (!mMasterMute) {
2492 char value[PROPERTY_VALUE_MAX];
2493 if (property_get("ro.audio.silent", value, "0") > 0) {
2494 char *endptr;
2495 unsigned long ul = strtoul(value, &endptr, 0);
2496 if (*endptr == '\0' && ul != 0) {
2497 ALOGD("Silence is golden");
2498 // The setprop command will not allow a property to be changed after
2499 // the first time it is set, so we don't have to worry about un-muting.
2500 setMasterMute_l(true);
2501 }
2502 }
2503 }
2504}
2505
Glenn Kasten000f0e32012-03-01 17:10:56 -08002506bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002507{
2508 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002509
Glenn Kasten000f0e32012-03-01 17:10:56 -08002510 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002511
2512 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002513 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002514
Glenn Kasten000f0e32012-03-01 17:10:56 -08002515 // DUPLICATING
2516 // FIXME could this be made local to while loop?
2517 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002518
Glenn Kasten66fcab92012-02-24 14:59:21 -08002519 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002520 sleepTime = idleSleepTime;
2521
Glenn Kasten9f34a362012-03-20 16:46:41 -07002522 if (mType == MIXER) {
2523 sleepTimeShift = 0;
2524 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002525
Glenn Kasten83efdd02012-02-24 07:21:32 -08002526 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002527 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002528
Eric Laurentfeb0db62011-07-22 09:04:31 -07002529 acquireWakeLock();
2530
Mathias Agopian65ab4712010-07-14 17:59:35 -07002531 while (!exitPending())
2532 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002533 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002534
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002535 Vector< sp<EffectChain> > effectChains;
2536
Mathias Agopian65ab4712010-07-14 17:59:35 -07002537 processConfigEvents();
2538
Mathias Agopian65ab4712010-07-14 17:59:35 -07002539 { // scope for mLock
2540
2541 Mutex::Autolock _l(mLock);
2542
2543 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002544 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002545 }
2546
Glenn Kastenfa26a852012-03-06 11:28:04 -08002547 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002548
Mathias Agopian65ab4712010-07-14 17:59:35 -07002549 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002550 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002551 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002552 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002553
2554 threadLoop_standby();
2555
Mathias Agopian65ab4712010-07-14 17:59:35 -07002556 mStandby = true;
2557 mBytesWritten = 0;
2558 }
2559
Glenn Kasten3e074702012-02-28 18:40:35 -08002560 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002561 // we're about to wait, flush the binder command buffer
2562 IPCThreadState::self()->flushCommands();
2563
Glenn Kastenfa26a852012-03-06 11:28:04 -08002564 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002565
Mathias Agopian65ab4712010-07-14 17:59:35 -07002566 if (exitPending()) break;
2567
Eric Laurentfeb0db62011-07-22 09:04:31 -07002568 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002569 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002570 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002571 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002572 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002573 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002574
Eric Laurentda747442012-04-25 18:53:13 -07002575 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002576 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002577
Glenn Kasten37d825e2012-02-24 07:21:48 -08002578 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002579
Glenn Kasten000f0e32012-03-01 17:10:56 -08002580 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002582 if (mType == MIXER) {
2583 sleepTimeShift = 0;
2584 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002585
Mathias Agopian65ab4712010-07-14 17:59:35 -07002586 continue;
2587 }
2588 }
2589
Glenn Kasten81028042012-04-30 18:15:12 -07002590 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002591 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002592
2593 // prevent any changes in effect chain list and in each effect chain
2594 // during mixing and effect process as the audio buffers could be deleted
2595 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002596 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002597 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002598
Glenn Kastenfec279f2012-03-08 07:47:15 -08002599 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002600 threadLoop_mix();
2601 } else {
2602 threadLoop_sleepTime();
2603 }
2604
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002605 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002606 sleepTime = suspendSleepTimeUs();
2607 }
2608
2609 // only process effects if we're going to write
2610 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002611 for (size_t i = 0; i < effectChains.size(); i ++) {
2612 effectChains[i]->process_l();
2613 }
2614 }
2615
2616 // enable changes in effect chain
2617 unlockEffectChains(effectChains);
2618
2619 // sleepTime == 0 means we must write to audio hardware
2620 if (sleepTime == 0) {
2621
2622 threadLoop_write();
2623
2624if (mType == MIXER) {
2625 // write blocked detection
2626 nsecs_t now = systemTime();
2627 nsecs_t delta = now - mLastWriteTime;
2628 if (!mStandby && delta > maxPeriod) {
2629 mNumDelayedWrites++;
2630 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002631#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002632 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002633#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002634 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2635 ns2ms(delta), mNumDelayedWrites, this);
2636 lastWarning = now;
2637 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002638 }
2639}
2640
2641 mStandby = false;
2642 } else {
2643 usleep(sleepTime);
2644 }
2645
Glenn Kasten58912562012-04-03 10:45:00 -07002646 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002647 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002648 // same lock. This will also mutate and push a new fast mixer state.
2649 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002650 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002651
Glenn Kastenfa26a852012-03-06 11:28:04 -08002652 // FIXME I don't understand the need for this here;
2653 // it was in the original code but maybe the
2654 // assignment in saveOutputTracks() makes this unnecessary?
2655 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002656
2657 // Effect chains will be actually deleted here if they were removed from
2658 // mEffectChains list during mixing or effects processing
2659 effectChains.clear();
2660
2661 // FIXME Note that the above .clear() is no longer necessary since effectChains
2662 // is now local to this block, but will keep it for now (at least until merge done).
2663 }
2664
Glenn Kasten9f34a362012-03-20 16:46:41 -07002665 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2666 if (mType == MIXER || mType == DIRECT) {
2667 // put output stream into standby mode
2668 if (!mStandby) {
2669 mOutput->stream->common.standby(&mOutput->stream->common);
2670 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002671 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002672
2673 releaseWakeLock();
2674
2675 ALOGV("Thread %p type %d exiting", this, mType);
2676 return false;
2677}
2678
Glenn Kasten58912562012-04-03 10:45:00 -07002679void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2680{
Glenn Kasten58912562012-04-03 10:45:00 -07002681 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2682}
2683
2684void AudioFlinger::MixerThread::threadLoop_write()
2685{
2686 // FIXME we should only do one push per cycle; confirm this is true
2687 // Start the fast mixer if it's not already running
2688 if (mFastMixer != NULL) {
2689 FastMixerStateQueue *sq = mFastMixer->sq();
2690 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002691 if (state->mCommand != FastMixerState::MIX_WRITE &&
2692 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002693 if (state->mCommand == FastMixerState::COLD_IDLE) {
2694 int32_t old = android_atomic_inc(&mFastMixerFutex);
2695 if (old == -1) {
2696 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2697 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002698 if (mAudioWatchdog != 0) {
2699 mAudioWatchdog->resume();
2700 }
Glenn Kasten58912562012-04-03 10:45:00 -07002701 }
2702 state->mCommand = FastMixerState::MIX_WRITE;
2703 sq->end();
2704 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002705 if (kUseFastMixer == FastMixer_Dynamic) {
2706 mNormalSink = mPipeSink;
2707 }
Glenn Kasten58912562012-04-03 10:45:00 -07002708 } else {
2709 sq->end(false /*didModify*/);
2710 }
2711 }
2712 PlaybackThread::threadLoop_write();
2713}
2714
Glenn Kasten000f0e32012-03-01 17:10:56 -08002715// shared by MIXER and DIRECT, overridden by DUPLICATING
2716void AudioFlinger::PlaybackThread::threadLoop_write()
2717{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002718 // FIXME rewrite to reduce number of system calls
2719 mLastWriteTime = systemTime();
2720 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002721 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002722
Eric Laurent67c0a582012-05-01 19:31:12 -07002723 // If an NBAIO sink is present, use it to write the normal mixer's submix
2724 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002725#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002726 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002727#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002728 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002729#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002730 // update the setpoint when gScreenState changes
2731 uint32_t screenState = gScreenState;
2732 if (screenState != mScreenState) {
2733 mScreenState = screenState;
2734 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2735 if (pipe != NULL) {
2736 pipe->setAvgFrames((mScreenState & 1) ?
2737 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2738 }
2739 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002740 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002741#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002742 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002743#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002744 if (framesWritten > 0) {
2745 bytesWritten = framesWritten << mBitShift;
2746 } else {
2747 bytesWritten = framesWritten;
2748 }
2749 // otherwise use the HAL / AudioStreamOut directly
2750 } else {
2751 // Direct output thread.
2752 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002753 }
2754
Eric Laurent67c0a582012-05-01 19:31:12 -07002755 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002756 mNumWrites++;
2757 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002758}
2759
Glenn Kasten58912562012-04-03 10:45:00 -07002760void AudioFlinger::MixerThread::threadLoop_standby()
2761{
2762 // Idle the fast mixer if it's currently running
2763 if (mFastMixer != NULL) {
2764 FastMixerStateQueue *sq = mFastMixer->sq();
2765 FastMixerState *state = sq->begin();
2766 if (!(state->mCommand & FastMixerState::IDLE)) {
2767 state->mCommand = FastMixerState::COLD_IDLE;
2768 state->mColdFutexAddr = &mFastMixerFutex;
2769 state->mColdGen++;
2770 mFastMixerFutex = 0;
2771 sq->end();
2772 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2773 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002774 if (kUseFastMixer == FastMixer_Dynamic) {
2775 mNormalSink = mOutputSink;
2776 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002777 if (mAudioWatchdog != 0) {
2778 mAudioWatchdog->pause();
2779 }
Glenn Kasten58912562012-04-03 10:45:00 -07002780 } else {
2781 sq->end(false /*didModify*/);
2782 }
2783 }
2784 PlaybackThread::threadLoop_standby();
2785}
2786
Glenn Kasten000f0e32012-03-01 17:10:56 -08002787// shared by MIXER and DIRECT, overridden by DUPLICATING
2788void AudioFlinger::PlaybackThread::threadLoop_standby()
2789{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002790 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002791 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002792}
2793
2794void AudioFlinger::MixerThread::threadLoop_mix()
2795{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002796 // obtain the presentation timestamp of the next output buffer
2797 int64_t pts;
2798 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002799
John Grossman2c3b2da2012-08-02 17:08:54 -07002800 if (mNormalSink != 0) {
2801 status = mNormalSink->getNextWriteTimestamp(&pts);
2802 } else {
2803 status = mOutputSink->getNextWriteTimestamp(&pts);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002804 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002805
Glenn Kasten952eeb22012-03-06 11:30:57 -08002806 if (status != NO_ERROR) {
2807 pts = AudioBufferProvider::kInvalidPTS;
2808 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002809
Glenn Kasten952eeb22012-03-06 11:30:57 -08002810 // mix buffers...
2811 mAudioMixer->process(pts);
2812 // increase sleep time progressively when application underrun condition clears.
2813 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2814 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2815 // such that we would underrun the audio HAL.
2816 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2817 sleepTimeShift--;
2818 }
2819 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002820 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002821 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002822}
2823
2824void AudioFlinger::MixerThread::threadLoop_sleepTime()
2825{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002826 // If no tracks are ready, sleep once for the duration of an output
2827 // buffer size, then write 0s to the output
2828 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002829 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002830 sleepTime = activeSleepTime >> sleepTimeShift;
2831 if (sleepTime < kMinThreadSleepTimeUs) {
2832 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002833 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002834 // reduce sleep time in case of consecutive application underruns to avoid
2835 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2836 // duration we would end up writing less data than needed by the audio HAL if
2837 // the condition persists.
2838 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2839 sleepTimeShift++;
2840 }
2841 } else {
2842 sleepTime = idleSleepTime;
2843 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002844 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002845 memset (mMixBuffer, 0, mixBufferSize);
2846 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002847 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002848 }
2849 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002850}
2851
2852// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002853AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002854 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002855{
2856
Glenn Kasten29c23c32012-01-26 13:37:52 -08002857 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002858 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002859 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002860 size_t mixedTracks = 0;
2861 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002862 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002863 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002864 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002865
2866 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002867 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002868
Eric Laurent571d49c2010-08-11 05:20:11 -07002869 if (masterMute) {
2870 masterVolume = 0;
2871 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002872 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002873 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002874 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002875 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002876 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002877 masterVolume = (float)((v + (1 << 23)) >> 24);
2878 chain.clear();
2879 }
2880
Glenn Kasten288ed212012-04-25 17:52:27 -07002881 // prepare a new state to push
2882 FastMixerStateQueue *sq = NULL;
2883 FastMixerState *state = NULL;
2884 bool didModify = false;
2885 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2886 if (mFastMixer != NULL) {
2887 sq = mFastMixer->sq();
2888 state = sq->begin();
2889 }
2890
Mathias Agopian65ab4712010-07-14 17:59:35 -07002891 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002892 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002893 if (t == 0) continue;
2894
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002895 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002896 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002897
Glenn Kasten288ed212012-04-25 17:52:27 -07002898 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002899 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002900
2901 // It's theoretically possible (though unlikely) for a fast track to be created
2902 // and then removed within the same normal mix cycle. This is not a problem, as
2903 // the track never becomes active so it's fast mixer slot is never touched.
2904 // The converse, of removing an (active) track and then creating a new track
2905 // at the identical fast mixer slot within the same normal mix cycle,
2906 // is impossible because the slot isn't marked available until the end of each cycle.
2907 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002908 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2909 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002910 FastTrack *fastTrack = &state->mFastTracks[j];
2911
2912 // Determine whether the track is currently in underrun condition,
2913 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002914 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2915 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002916 uint32_t recentFull = (underruns.mBitFields.mFull -
2917 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2918 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2919 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2920 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2921 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2922 uint32_t recentUnderruns = recentPartial + recentEmpty;
2923 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002924 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002925 // or stopped which can occur when flush() is called while active
2926 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002927 track->mUnderrunCount += recentUnderruns;
2928 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002929
Glenn Kastend08f48c2012-05-01 18:14:02 -07002930 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002931 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002932 bool isActive = true;
2933 switch (track->mState) {
2934 case TrackBase::STOPPING_1:
2935 // track stays active in STOPPING_1 state until first underrun
2936 if (recentUnderruns > 0) {
2937 track->mState = TrackBase::STOPPING_2;
2938 }
2939 break;
2940 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002941 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002942 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002943 break;
2944 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002945 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002946 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002947 break;
2948 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002949 if (recentFull > 0 || recentPartial > 0) {
2950 // track has provided at least some frames recently: reset retry count
2951 track->mRetryCount = kMaxTrackRetries;
2952 }
2953 if (recentUnderruns == 0) {
2954 // no recent underruns: stay active
2955 break;
2956 }
2957 // there has recently been an underrun of some kind
2958 if (track->sharedBuffer() == 0) {
2959 // were any of the recent underruns "empty" (no frames available)?
2960 if (recentEmpty == 0) {
2961 // no, then ignore the partial underruns as they are allowed indefinitely
2962 break;
2963 }
2964 // there has recently been an "empty" underrun: decrement the retry counter
2965 if (--(track->mRetryCount) > 0) {
2966 break;
2967 }
2968 // indicate to client process that the track was disabled because of underrun;
2969 // it will then automatically call start() when data is available
2970 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2971 // remove from active list, but state remains ACTIVE [confusing but true]
2972 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002973 break;
2974 }
2975 // fall through
2976 case TrackBase::STOPPING_2:
2977 case TrackBase::PAUSED:
2978 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002979 case TrackBase::STOPPED:
2980 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002981 // Check for presentation complete if track is inactive
2982 // We have consumed all the buffers of this track.
2983 // This would be incomplete if we auto-paused on underrun
2984 {
2985 size_t audioHALFrames =
2986 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2987 size_t framesWritten =
2988 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2989 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2990 // track stays in active list until presentation is complete
2991 break;
2992 }
2993 }
2994 if (track->isStopping_2()) {
2995 track->mState = TrackBase::STOPPED;
2996 }
2997 if (track->isStopped()) {
2998 // Can't reset directly, as fast mixer is still polling this track
2999 // track->reset();
3000 // So instead mark this track as needing to be reset after push with ack
3001 resetMask |= 1 << i;
3002 }
3003 isActive = false;
3004 break;
3005 case TrackBase::IDLE:
3006 default:
3007 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003008 }
3009
3010 if (isActive) {
3011 // was it previously inactive?
3012 if (!(state->mTrackMask & (1 << j))) {
3013 ExtendedAudioBufferProvider *eabp = track;
3014 VolumeProvider *vp = track;
3015 fastTrack->mBufferProvider = eabp;
3016 fastTrack->mVolumeProvider = vp;
3017 fastTrack->mSampleRate = track->mSampleRate;
3018 fastTrack->mChannelMask = track->mChannelMask;
3019 fastTrack->mGeneration++;
3020 state->mTrackMask |= 1 << j;
3021 didModify = true;
3022 // no acknowledgement required for newly active tracks
3023 }
3024 // cache the combined master volume and stream type volume for fast mixer; this
3025 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3026 track->mCachedVolume = track->isMuted() ?
3027 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3028 ++fastTracks;
3029 } else {
3030 // was it previously active?
3031 if (state->mTrackMask & (1 << j)) {
3032 fastTrack->mBufferProvider = NULL;
3033 fastTrack->mGeneration++;
3034 state->mTrackMask &= ~(1 << j);
3035 didModify = true;
3036 // If any fast tracks were removed, we must wait for acknowledgement
3037 // because we're about to decrement the last sp<> on those tracks.
3038 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003039 } else {
3040 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003041 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003042 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003043 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003044 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003045 }
3046 continue;
3047 }
3048
3049 { // local variable scope to avoid goto warning
3050
Mathias Agopian65ab4712010-07-14 17:59:35 -07003051 audio_track_cblk_t* cblk = track->cblk();
3052
3053 // The first time a track is added we wait
3054 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003055 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003056 // make sure that we have enough frames to mix one full buffer.
3057 // enforce this condition only once to enable draining the buffer in case the client
3058 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003059 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003060 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003061 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003062 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003063 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003064 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003065 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003066 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003067 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003068 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003069 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003070 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003071 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3072 // the minimum track buffer size is normally twice the number of frames necessary
3073 // to fill one buffer and the resampler should not leave more than one buffer worth
3074 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003075 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003076 }
3077 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003078 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003079 !track->isPaused() && !track->isTerminated())
3080 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003081 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003082
3083 mixedTracks++;
3084
3085 // track->mainBuffer() != mMixBuffer means there is an effect chain
3086 // connected to the track
3087 chain.clear();
3088 if (track->mainBuffer() != mMixBuffer) {
3089 chain = getEffectChain_l(track->sessionId());
3090 // Delegate volume control to effect in track effect chain if needed
3091 if (chain != 0) {
3092 tracksWithEffect++;
3093 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003094 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003095 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003096 }
3097 }
3098
3099
3100 int param = AudioMixer::VOLUME;
3101 if (track->mFillingUpStatus == Track::FS_FILLED) {
3102 // no ramp for the first volume setting
3103 track->mFillingUpStatus = Track::FS_ACTIVE;
3104 if (track->mState == TrackBase::RESUMING) {
3105 track->mState = TrackBase::ACTIVE;
3106 param = AudioMixer::RAMP_VOLUME;
3107 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003108 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003109 } else if (cblk->server != 0) {
3110 // If the track is stopped before the first frame was mixed,
3111 // do not apply ramp
3112 param = AudioMixer::RAMP_VOLUME;
3113 }
3114
3115 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003116 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003117 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003118 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003119 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003120 if (track->isPausing()) {
3121 track->setPaused();
3122 }
3123 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003124
Mathias Agopian65ab4712010-07-14 17:59:35 -07003125 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003126 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003127 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003128 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003129 vl = vlr & 0xFFFF;
3130 vr = vlr >> 16;
3131 // track volumes come from shared memory, so can't be trusted and must be clamped
3132 if (vl > MAX_GAIN_INT) {
3133 ALOGV("Track left volume out of range: %04X", vl);
3134 vl = MAX_GAIN_INT;
3135 }
3136 if (vr > MAX_GAIN_INT) {
3137 ALOGV("Track right volume out of range: %04X", vr);
3138 vr = MAX_GAIN_INT;
3139 }
3140 // now apply the master volume and stream type volume
3141 vl = (uint32_t)(v * vl) << 12;
3142 vr = (uint32_t)(v * vr) << 12;
3143 // assuming master volume and stream type volume each go up to 1.0,
3144 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003145
Glenn Kasten05632a52012-01-03 14:22:33 -08003146 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3147 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003148 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003149 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003150 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003151 }
3152 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003154 // Delegate volume control to effect in track effect chain if needed
3155 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3156 // Do not ramp volume if volume is controlled by effect
3157 param = AudioMixer::VOLUME;
3158 track->mHasVolumeController = true;
3159 } else {
3160 // force no volume ramp when volume controller was just disabled or removed
3161 // from effect chain to avoid volume spike
3162 if (track->mHasVolumeController) {
3163 param = AudioMixer::VOLUME;
3164 }
3165 track->mHasVolumeController = false;
3166 }
3167
3168 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003169 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003170 vl = (vl + (1 << 11)) >> 12;
3171 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3172 vr = (vr + (1 << 11)) >> 12;
3173 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003174
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003175 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 -07003176
Mathias Agopian65ab4712010-07-14 17:59:35 -07003177 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003178 mAudioMixer->setBufferProvider(name, track);
3179 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003180
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003181 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3182 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3183 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003185 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003186 AudioMixer::TRACK,
3187 AudioMixer::FORMAT, (void *)track->format());
3188 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003189 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003190 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003191 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003192 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003193 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003194 AudioMixer::RESAMPLE,
3195 AudioMixer::SAMPLE_RATE,
3196 (void *)(cblk->sampleRate));
3197 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003198 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003199 AudioMixer::TRACK,
3200 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3201 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003202 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003203 AudioMixer::TRACK,
3204 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3205
3206 // reset retry count
3207 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003208
Eric Laurent27741442012-01-17 19:20:12 -08003209 // If one track is ready, set the mixer ready if:
3210 // - the mixer was not ready during previous round OR
3211 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003212 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003213 mixerStatus != MIXER_TRACKS_ENABLED) {
3214 mixerStatus = MIXER_TRACKS_READY;
3215 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003216 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003217 // clear effect chain input buffer if an active track underruns to avoid sending
3218 // previous audio buffer again to effects
3219 chain = getEffectChain_l(track->sessionId());
3220 if (chain != 0) {
3221 chain->clearInputBuffer();
3222 }
3223
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003224 //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 -07003225 if ((track->sharedBuffer() != 0) ||
Eric Laurent83faee02012-04-27 18:24:29 -07003226 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003227 // We have consumed all the buffers of this track.
3228 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003229 // TODO: use actual buffer filling status instead of latency when available from
3230 // audio HAL
3231 size_t audioHALFrames =
3232 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3233 size_t framesWritten =
3234 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3235 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003236 if (track->isStopped()) {
3237 track->reset();
3238 }
Eric Laurenta011e352012-03-29 15:51:43 -07003239 tracksToRemove->add(track);
3240 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003241 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003242 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003243 // No buffers for this track. Give it a few chances to
3244 // fill a buffer, then remove it from active list.
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003245 if (--(track->mRetryCount) <= 0 || track->isTerminated()) {
3246 ALOGV_IF(track->mRetryCount <= 0, "BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003247 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003248 // indicate to client process that the track was disabled because of underrun;
3249 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003250 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003251 // If one track is not ready, mark the mixer also not ready if:
3252 // - the mixer was ready during previous round OR
3253 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003254 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003255 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003256 mixerStatus = MIXER_TRACKS_ENABLED;
3257 }
3258 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003259 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003260 }
Glenn Kasten58912562012-04-03 10:45:00 -07003261
3262 } // local variable scope to avoid goto warning
3263track_is_ready: ;
3264
Mathias Agopian65ab4712010-07-14 17:59:35 -07003265 }
3266
Glenn Kasten288ed212012-04-25 17:52:27 -07003267 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003268 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003269 if (didModify) {
3270 state->mFastTracksGen++;
3271 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3272 if (kUseFastMixer == FastMixer_Dynamic &&
3273 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3274 state->mCommand = FastMixerState::COLD_IDLE;
3275 state->mColdFutexAddr = &mFastMixerFutex;
3276 state->mColdGen++;
3277 mFastMixerFutex = 0;
3278 if (kUseFastMixer == FastMixer_Dynamic) {
3279 mNormalSink = mOutputSink;
3280 }
3281 // If we go into cold idle, need to wait for acknowledgement
3282 // so that fast mixer stops doing I/O.
3283 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003284 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003285 }
3286 sq->end();
3287 }
3288 if (sq != NULL) {
3289 sq->end(didModify);
3290 sq->push(block);
3291 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07003292 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3293 mAudioWatchdog->pause();
3294 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003295
3296 // Now perform the deferred reset on fast tracks that have stopped
3297 while (resetMask != 0) {
3298 size_t i = __builtin_ctz(resetMask);
3299 ALOG_ASSERT(i < count);
3300 resetMask &= ~(1 << i);
3301 sp<Track> t = mActiveTracks[i].promote();
3302 if (t == 0) continue;
3303 Track* track = t.get();
3304 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3305 track->reset();
3306 }
Glenn Kasten58912562012-04-03 10:45:00 -07003307
Mathias Agopian65ab4712010-07-14 17:59:35 -07003308 // remove all the tracks that need to be...
3309 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003310 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003311 for (size_t i=0 ; i<count ; i++) {
3312 const sp<Track>& track = tracksToRemove->itemAt(i);
3313 mActiveTracks.remove(track);
3314 if (track->mainBuffer() != mMixBuffer) {
3315 chain = getEffectChain_l(track->sessionId());
3316 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003317 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003318 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003319 }
3320 }
3321 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003322 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003323 }
3324 }
3325 }
3326
3327 // mix buffer must be cleared if all tracks are connected to an
3328 // effect chain as in this case the mixer will not write to
3329 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003330 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3331 // FIXME as a performance optimization, should remember previous zero status
3332 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003333 }
3334
Glenn Kasten58912562012-04-03 10:45:00 -07003335 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003336 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003337 if (fastTracks > 0) {
3338 mixerStatus = MIXER_TRACKS_READY;
3339 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003340 return mixerStatus;
3341}
3342
Glenn Kasten66fcab92012-02-24 14:59:21 -08003343/*
3344The derived values that are cached:
3345 - mixBufferSize from frame count * frame size
3346 - activeSleepTime from activeSleepTimeUs()
3347 - idleSleepTime from idleSleepTimeUs()
3348 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3349 - maxPeriod from frame count and sample rate (MIXER only)
3350
3351The parameters that affect these derived values are:
3352 - frame count
3353 - frame size
3354 - sample rate
3355 - device type: A2DP or not
3356 - device latency
3357 - format: PCM or not
3358 - active sleep time
3359 - idle sleep time
3360*/
3361
3362void AudioFlinger::PlaybackThread::cacheParameters_l()
3363{
Glenn Kasten58912562012-04-03 10:45:00 -07003364 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003365 activeSleepTime = activeSleepTimeUs();
3366 idleSleepTime = idleSleepTimeUs();
3367}
3368
Eric Laurent22167852012-06-20 12:26:32 -07003369void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003370{
Steve Block3856b092011-10-20 11:56:00 +01003371 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003372 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003373 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003374
Mathias Agopian65ab4712010-07-14 17:59:35 -07003375 size_t size = mTracks.size();
3376 for (size_t i = 0; i < size; i++) {
3377 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003378 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003379 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003380 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003381 }
3382 }
3383}
3384
Mathias Agopian65ab4712010-07-14 17:59:35 -07003385// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003386int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003387{
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003388 return mAudioMixer->getTrackName(channelMask, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003389}
3390
3391// deleteTrackName_l() must be called with ThreadBase::mLock held
3392void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3393{
Steve Block3856b092011-10-20 11:56:00 +01003394 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003395 mAudioMixer->deleteTrackName(name);
3396}
3397
3398// checkForNewParameters_l() must be called with ThreadBase::mLock held
3399bool AudioFlinger::MixerThread::checkForNewParameters_l()
3400{
Glenn Kasten58912562012-04-03 10:45:00 -07003401 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3402 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003403 bool reconfig = false;
3404
3405 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003406
3407 if (mFastMixer != NULL) {
3408 FastMixerStateQueue *sq = mFastMixer->sq();
3409 FastMixerState *state = sq->begin();
3410 if (!(state->mCommand & FastMixerState::IDLE)) {
3411 previousCommand = state->mCommand;
3412 state->mCommand = FastMixerState::HOT_IDLE;
3413 sq->end();
3414 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3415 } else {
3416 sq->end(false /*didModify*/);
3417 }
3418 }
3419
Mathias Agopian65ab4712010-07-14 17:59:35 -07003420 status_t status = NO_ERROR;
3421 String8 keyValuePair = mNewParameters[0];
3422 AudioParameter param = AudioParameter(keyValuePair);
3423 int value;
3424
3425 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3426 reconfig = true;
3427 }
3428 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003429 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003430 status = BAD_VALUE;
3431 } else {
3432 reconfig = true;
3433 }
3434 }
3435 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003436 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003437 status = BAD_VALUE;
3438 } else {
3439 reconfig = true;
3440 }
3441 }
3442 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3443 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003444 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003445 // if frame count is changed after track creation
3446 if (!mTracks.isEmpty()) {
3447 status = INVALID_OPERATION;
3448 } else {
3449 reconfig = true;
3450 }
3451 }
3452 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003453#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003454 // when changing the audio output device, call addBatteryData to notify
3455 // the change
Eric Laurentf1c04f92012-08-28 14:26:53 -07003456 if (mOutDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003457 uint32_t params = 0;
3458 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003459 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003460 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3461 }
3462
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003463 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003464 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003465 // check if any other device (except speaker) is on
3466 if (value & deviceWithoutSpeaker ) {
3467 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3468 }
3469
3470 if (params != 0) {
3471 addBatteryData(params);
3472 }
3473 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003474#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003475
Mathias Agopian65ab4712010-07-14 17:59:35 -07003476 // forward device change to effects that have requested to be
3477 // aware of attached audio device.
Eric Laurentf1c04f92012-08-28 14:26:53 -07003478 mOutDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003479 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07003480 mEffectChains[i]->setDevice_l(mOutDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003481 }
3482 }
3483
3484 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003485 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003486 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003487 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003488 mOutput->stream->common.standby(&mOutput->stream->common);
3489 mStandby = true;
3490 mBytesWritten = 0;
3491 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003492 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493 }
3494 if (status == NO_ERROR && reconfig) {
3495 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003496 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3497 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003498 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003499 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003500 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003501 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003502 if (name < 0) break;
3503 mTracks[i]->mName = name;
3504 // limit track sample rate to 2 x new output sample rate
3505 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3506 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3507 }
3508 }
3509 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3510 }
3511 }
3512
3513 mNewParameters.removeAt(0);
3514
3515 mParamStatus = status;
3516 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003517 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3518 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003519 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003520 }
Glenn Kasten58912562012-04-03 10:45:00 -07003521
3522 if (!(previousCommand & FastMixerState::IDLE)) {
3523 ALOG_ASSERT(mFastMixer != NULL);
3524 FastMixerStateQueue *sq = mFastMixer->sq();
3525 FastMixerState *state = sq->begin();
3526 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3527 state->mCommand = previousCommand;
3528 sq->end();
3529 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3530 }
3531
Mathias Agopian65ab4712010-07-14 17:59:35 -07003532 return reconfig;
3533}
3534
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07003535void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003536{
3537 const size_t SIZE = 256;
3538 char buffer[SIZE];
3539 String8 result;
3540
3541 PlaybackThread::dumpInternals(fd, args);
3542
3543 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3544 result.append(buffer);
3545 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003546
3547 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3548 FastMixerDumpState copy = mFastMixerDumpState;
3549 copy.dump(fd);
3550
Glenn Kasten39993082012-05-31 13:40:27 -07003551#ifdef STATE_QUEUE_DUMP
3552 // Similar for state queue
3553 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3554 observerCopy.dump(fd);
3555 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3556 mutatorCopy.dump(fd);
3557#endif
3558
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003559 // Write the tee output to a .wav file
3560 NBAIO_Source *teeSource = mTeeSource.get();
3561 if (teeSource != NULL) {
3562 char teePath[64];
3563 struct timeval tv;
3564 gettimeofday(&tv, NULL);
3565 struct tm tm;
3566 localtime_r(&tv.tv_sec, &tm);
3567 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3568 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3569 if (teeFd >= 0) {
3570 char wavHeader[44];
3571 memcpy(wavHeader,
3572 "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",
3573 sizeof(wavHeader));
3574 NBAIO_Format format = teeSource->format();
3575 unsigned channelCount = Format_channelCount(format);
3576 ALOG_ASSERT(channelCount <= FCC_2);
3577 unsigned sampleRate = Format_sampleRate(format);
3578 wavHeader[22] = channelCount; // number of channels
3579 wavHeader[24] = sampleRate; // sample rate
3580 wavHeader[25] = sampleRate >> 8;
3581 wavHeader[32] = channelCount * 2; // block alignment
3582 write(teeFd, wavHeader, sizeof(wavHeader));
3583 size_t total = 0;
3584 bool firstRead = true;
3585 for (;;) {
3586#define TEE_SINK_READ 1024
3587 short buffer[TEE_SINK_READ * FCC_2];
3588 size_t count = TEE_SINK_READ;
John Grossman2c3b2da2012-08-02 17:08:54 -07003589 ssize_t actual = teeSource->read(buffer, count,
3590 AudioBufferProvider::kInvalidPTS);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003591 bool wasFirstRead = firstRead;
3592 firstRead = false;
3593 if (actual <= 0) {
3594 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3595 continue;
3596 }
3597 break;
3598 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003599 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003600 write(teeFd, buffer, actual * channelCount * sizeof(short));
3601 total += actual;
3602 }
3603 lseek(teeFd, (off_t) 4, SEEK_SET);
3604 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3605 write(teeFd, &temp, sizeof(temp));
3606 lseek(teeFd, (off_t) 40, SEEK_SET);
3607 temp = total * channelCount * sizeof(short);
3608 write(teeFd, &temp, sizeof(temp));
3609 close(teeFd);
3610 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3611 } else {
3612 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3613 }
3614 }
3615
Glenn Kastenc15d6652012-05-30 14:52:57 -07003616 if (mAudioWatchdog != 0) {
3617 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3618 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3619 wdCopy.dump(fd);
3620 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003621}
3622
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003623uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003624{
Glenn Kasten58912562012-04-03 10:45:00 -07003625 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003626}
3627
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003628uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003629{
Glenn Kasten58912562012-04-03 10:45:00 -07003630 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003631}
3632
Glenn Kasten66fcab92012-02-24 14:59:21 -08003633void AudioFlinger::MixerThread::cacheParameters_l()
3634{
3635 PlaybackThread::cacheParameters_l();
3636
3637 // FIXME: Relaxed timing because of a certain device that can't meet latency
3638 // Should be reduced to 2x after the vendor fixes the driver issue
3639 // increase threshold again due to low power audio mode. The way this warning
3640 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003641 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003642}
3643
Mathias Agopian65ab4712010-07-14 17:59:35 -07003644// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003645AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003646 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003647 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003648 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003649{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003650}
3651
3652AudioFlinger::DirectOutputThread::~DirectOutputThread()
3653{
3654}
3655
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003656AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3657 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003658)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003659{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003660 sp<Track> trackToRemove;
3661
Glenn Kastenfec279f2012-03-08 07:47:15 -08003662 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003663
Glenn Kasten952eeb22012-03-06 11:30:57 -08003664 // find out which tracks need to be processed
3665 if (mActiveTracks.size() != 0) {
3666 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003667 // The track died recently
3668 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003669
Glenn Kasten952eeb22012-03-06 11:30:57 -08003670 Track* const track = t.get();
3671 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003672
Glenn Kasten952eeb22012-03-06 11:30:57 -08003673 // The first time a track is added we wait
3674 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003675 uint32_t minFrames;
3676 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3677 minFrames = mNormalFrameCount;
3678 } else {
3679 minFrames = 1;
3680 }
3681 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003682 !track->isPaused() && !track->isTerminated())
3683 {
3684 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003685
Glenn Kasten952eeb22012-03-06 11:30:57 -08003686 if (track->mFillingUpStatus == Track::FS_FILLED) {
3687 track->mFillingUpStatus = Track::FS_ACTIVE;
3688 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003689 if (track->mState == TrackBase::RESUMING) {
3690 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003691 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003692 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003693
Glenn Kasten952eeb22012-03-06 11:30:57 -08003694 // compute volume for this track
3695 float left, right;
3696 if (track->isMuted() || mMasterMute || track->isPausing() ||
3697 mStreamTypes[track->streamType()].mute) {
3698 left = right = 0;
3699 if (track->isPausing()) {
3700 track->setPaused();
3701 }
3702 } else {
3703 float typeVolume = mStreamTypes[track->streamType()].volume;
3704 float v = mMasterVolume * typeVolume;
3705 uint32_t vlr = cblk->getVolumeLR();
3706 float v_clamped = v * (vlr & 0xFFFF);
3707 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3708 left = v_clamped/MAX_GAIN;
3709 v_clamped = v * (vlr >> 16);
3710 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3711 right = v_clamped/MAX_GAIN;
3712 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003713
Glenn Kasten952eeb22012-03-06 11:30:57 -08003714 if (left != mLeftVolFloat || right != mRightVolFloat) {
3715 mLeftVolFloat = left;
3716 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003717
Glenn Kasten952eeb22012-03-06 11:30:57 -08003718 // Convert volumes from float to 8.24
3719 uint32_t vl = (uint32_t)(left * (1 << 24));
3720 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003721
Glenn Kasten952eeb22012-03-06 11:30:57 -08003722 // Delegate volume control to effect in track effect chain if needed
3723 // only one effect chain can be present on DirectOutputThread, so if
3724 // there is one, the track is connected to it
3725 if (!mEffectChains.isEmpty()) {
3726 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003727 mEffectChains[0]->setVolume_l(&vl, &vr);
3728 left = (float)vl / (1 << 24);
3729 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003730 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003731 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003732 }
3733
3734 // reset retry count
3735 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003736 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003737 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003738 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003739 // clear effect chain input buffer if an active track underruns to avoid sending
3740 // previous audio buffer again to effects
3741 if (!mEffectChains.isEmpty()) {
3742 mEffectChains[0]->clearInputBuffer();
3743 }
3744
Glenn Kasten952eeb22012-03-06 11:30:57 -08003745 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003746 if ((track->sharedBuffer() != 0) ||
Eric Laurent67c0a582012-05-01 19:31:12 -07003747 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003748 // We have consumed all the buffers of this track.
3749 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003750 // TODO: implement behavior for compressed audio
3751 size_t audioHALFrames =
3752 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3753 size_t framesWritten =
3754 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3755 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003756 if (track->isStopped()) {
3757 track->reset();
3758 }
Eric Laurenta011e352012-03-29 15:51:43 -07003759 trackToRemove = track;
3760 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003761 } else {
3762 // No buffers for this track. Give it a few chances to
3763 // fill a buffer, then remove it from active list.
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003764 if (--(track->mRetryCount) <= 0 || track->isTerminated()) {
3765 ALOGV_IF(track->mRetryCount <= 0, "BUFFER TIMEOUT: remove(%d) from active list", track->name());
Glenn Kasten952eeb22012-03-06 11:30:57 -08003766 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003767 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003768 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003769 }
3770 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003771 }
3772 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003773
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003774 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003775 // remove all the tracks that need to be...
3776 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003777 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003778 mActiveTracks.remove(trackToRemove);
3779 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003780 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003781 trackToRemove->sessionId());
3782 mEffectChains[0]->decActiveTrackCnt();
3783 }
3784 if (trackToRemove->isTerminated()) {
3785 removeTrack_l(trackToRemove);
3786 }
3787 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003788
Glenn Kastenfec279f2012-03-08 07:47:15 -08003789 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003790}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003791
Glenn Kasten000f0e32012-03-01 17:10:56 -08003792void AudioFlinger::DirectOutputThread::threadLoop_mix()
3793{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003794 AudioBufferProvider::Buffer buffer;
3795 size_t frameCount = mFrameCount;
3796 int8_t *curBuf = (int8_t *)mMixBuffer;
3797 // output audio to hardware
3798 while (frameCount) {
3799 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003800 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003801 if (CC_UNLIKELY(buffer.raw == NULL)) {
3802 memset(curBuf, 0, frameCount * mFrameSize);
3803 break;
3804 }
3805 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3806 frameCount -= buffer.frameCount;
3807 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003808 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003809 }
3810 sleepTime = 0;
3811 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003812 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003813
Glenn Kasten000f0e32012-03-01 17:10:56 -08003814}
3815
3816void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3817{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003818 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003819 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003820 sleepTime = activeSleepTime;
3821 } else {
3822 sleepTime = idleSleepTime;
3823 }
3824 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003825 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003826 sleepTime = 0;
3827 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003828}
3829
3830// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003831int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3832 int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003833{
3834 return 0;
3835}
3836
3837// deleteTrackName_l() must be called with ThreadBase::mLock held
3838void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3839{
3840}
3841
3842// checkForNewParameters_l() must be called with ThreadBase::mLock held
3843bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3844{
3845 bool reconfig = false;
3846
3847 while (!mNewParameters.isEmpty()) {
3848 status_t status = NO_ERROR;
3849 String8 keyValuePair = mNewParameters[0];
3850 AudioParameter param = AudioParameter(keyValuePair);
3851 int value;
3852
3853 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3854 // do not accept frame count changes if tracks are open as the track buffer
3855 // size depends on frame count and correct behavior would not be garantied
3856 // if frame count is changed after track creation
3857 if (!mTracks.isEmpty()) {
3858 status = INVALID_OPERATION;
3859 } else {
3860 reconfig = true;
3861 }
3862 }
3863 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003864 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003865 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003866 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003867 mOutput->stream->common.standby(&mOutput->stream->common);
3868 mStandby = true;
3869 mBytesWritten = 0;
3870 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003871 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003872 }
3873 if (status == NO_ERROR && reconfig) {
3874 readOutputParameters();
3875 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3876 }
3877 }
3878
3879 mNewParameters.removeAt(0);
3880
3881 mParamStatus = status;
3882 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003883 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3884 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003885 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003886 }
3887 return reconfig;
3888}
3889
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003890uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003891{
3892 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003893 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003894 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003895 } else {
3896 time = 10000;
3897 }
3898 return time;
3899}
3900
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003901uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003902{
3903 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003904 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003905 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003906 } else {
3907 time = 10000;
3908 }
3909 return time;
3910}
3911
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003912uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003913{
3914 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003915 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003916 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3917 } else {
3918 time = 10000;
3919 }
3920 return time;
3921}
3922
Glenn Kasten66fcab92012-02-24 14:59:21 -08003923void AudioFlinger::DirectOutputThread::cacheParameters_l()
3924{
3925 PlaybackThread::cacheParameters_l();
3926
3927 // use shorter standby delay as on normal output to release
3928 // hardware resources as soon as possible
3929 standbyDelay = microseconds(activeSleepTime*2);
3930}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003931
Mathias Agopian65ab4712010-07-14 17:59:35 -07003932// ----------------------------------------------------------------------------
3933
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003934AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003935 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Eric Laurentf1c04f92012-08-28 14:26:53 -07003936 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), DUPLICATING),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003937 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003938{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003939 addOutputTrack(mainThread);
3940}
3941
3942AudioFlinger::DuplicatingThread::~DuplicatingThread()
3943{
3944 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3945 mOutputTracks[i]->destroy();
3946 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003947}
3948
Glenn Kasten000f0e32012-03-01 17:10:56 -08003949void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003950{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003951 // mix buffers...
3952 if (outputsReady(outputTracks)) {
3953 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3954 } else {
3955 memset(mMixBuffer, 0, mixBufferSize);
3956 }
3957 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003958 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003959 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003960}
3961
3962void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3963{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003964 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003965 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003966 sleepTime = activeSleepTime;
3967 } else {
3968 sleepTime = idleSleepTime;
3969 }
3970 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003971 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3972 writeFrames = mNormalFrameCount;
3973 memset(mMixBuffer, 0, mixBufferSize);
3974 } else {
3975 // flush remaining overflow buffers in output tracks
3976 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003977 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003978 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003979 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003980}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003981
Glenn Kasten000f0e32012-03-01 17:10:56 -08003982void AudioFlinger::DuplicatingThread::threadLoop_write()
3983{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003984 for (size_t i = 0; i < outputTracks.size(); i++) {
3985 outputTracks[i]->write(mMixBuffer, writeFrames);
3986 }
3987 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003988}
Glenn Kasten688a6402012-02-29 07:57:06 -08003989
Glenn Kasten000f0e32012-03-01 17:10:56 -08003990void AudioFlinger::DuplicatingThread::threadLoop_standby()
3991{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003992 // DuplicatingThread implements standby by stopping all tracks
3993 for (size_t i = 0; i < outputTracks.size(); i++) {
3994 outputTracks[i]->stop();
3995 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003996}
3997
Glenn Kastenfa26a852012-03-06 11:28:04 -08003998void AudioFlinger::DuplicatingThread::saveOutputTracks()
3999{
4000 outputTracks = mOutputTracks;
4001}
4002
4003void AudioFlinger::DuplicatingThread::clearOutputTracks()
4004{
4005 outputTracks.clear();
4006}
4007
Mathias Agopian65ab4712010-07-14 17:59:35 -07004008void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4009{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004010 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004011 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004012 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004013 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004014 this,
4015 mSampleRate,
4016 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004017 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004018 frameCount);
4019 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004020 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004021 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004022 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004023 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004024 }
4025}
4026
4027void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4028{
4029 Mutex::Autolock _l(mLock);
4030 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004031 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004032 mOutputTracks[i]->destroy();
4033 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004034 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004035 return;
4036 }
4037 }
Steve Block3856b092011-10-20 11:56:00 +01004038 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004039}
4040
Glenn Kasten438b0362012-03-06 11:24:48 -08004041// caller must hold mLock
4042void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004043{
4044 mWaitTimeMs = UINT_MAX;
4045 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4046 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004047 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004048 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4049 if (waitTimeMs < mWaitTimeMs) {
4050 mWaitTimeMs = waitTimeMs;
4051 }
4052 }
4053 }
4054}
4055
4056
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004057bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004058{
4059 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004060 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004061 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004062 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004063 return false;
4064 }
4065 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004066 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004067 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004068 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004069 return false;
4070 }
4071 }
4072 return true;
4073}
4074
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004075uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004076{
4077 return (mWaitTimeMs * 1000) / 2;
4078}
4079
Glenn Kasten66fcab92012-02-24 14:59:21 -08004080void AudioFlinger::DuplicatingThread::cacheParameters_l()
4081{
4082 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4083 updateWaitTime_l();
4084
4085 MixerThread::cacheParameters_l();
4086}
4087
Mathias Agopian65ab4712010-07-14 17:59:35 -07004088// ----------------------------------------------------------------------------
4089
4090// TrackBase constructor must be called with AudioFlinger::mLock held
4091AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004092 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004093 const sp<Client>& client,
4094 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004095 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004096 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004097 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004098 const sp<IMemory>& sharedBuffer,
4099 int sessionId)
4100 : RefBase(),
4101 mThread(thread),
4102 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004103 mCblk(NULL),
4104 // mBuffer
4105 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004106 mFrameCount(0),
4107 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004108 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004109 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004110 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004111 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004112 // mChannelCount
4113 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004114{
Steve Block3856b092011-10-20 11:56:00 +01004115 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004116
Steve Blockb8a80522011-12-20 16:23:08 +00004117 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004118 size_t size = sizeof(audio_track_cblk_t);
4119 uint8_t channelCount = popcount(channelMask);
4120 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4121 if (sharedBuffer == 0) {
4122 size += bufferSize;
4123 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004124
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004125 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004126 mCblkMemory = client->heap()->allocate(size);
4127 if (mCblkMemory != 0) {
4128 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004129 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004130 new(mCblk) audio_track_cblk_t();
4131 // clear all buffers
4132 mCblk->frameCount = frameCount;
4133 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004134// uncomment the following lines to quickly test 32-bit wraparound
4135// mCblk->user = 0xffff0000;
4136// mCblk->server = 0xffff0000;
4137// mCblk->userBase = 0xffff0000;
4138// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004139 mChannelCount = channelCount;
4140 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004141 if (sharedBuffer == 0) {
4142 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4143 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4144 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004145 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004146 mCblk->flags = CBLK_UNDERRUN_ON;
4147 } else {
4148 mBuffer = sharedBuffer->pointer();
4149 }
4150 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4151 }
4152 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004153 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004154 client->heap()->dump("AudioTrack");
4155 return;
4156 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004157 } else {
4158 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004159 // construct the shared structure in-place.
4160 new(mCblk) audio_track_cblk_t();
4161 // clear all buffers
4162 mCblk->frameCount = frameCount;
4163 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004164// uncomment the following lines to quickly test 32-bit wraparound
4165// mCblk->user = 0xffff0000;
4166// mCblk->server = 0xffff0000;
4167// mCblk->userBase = 0xffff0000;
4168// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004169 mChannelCount = channelCount;
4170 mChannelMask = channelMask;
4171 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4172 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4173 // Force underrun condition to avoid false underrun callback until first data is
4174 // written to buffer (other flags are cleared)
4175 mCblk->flags = CBLK_UNDERRUN_ON;
4176 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004177 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004178}
4179
4180AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4181{
Glenn Kastena0d68332012-01-27 16:47:15 -08004182 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004183 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004184 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004185 } else {
4186 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004187 }
4188 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004189 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004190 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004191 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004192 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004193 // If the client's reference count drops to zero, the associated destructor
4194 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4195 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004196 mClient.clear();
4197 }
4198}
4199
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004200// AudioBufferProvider interface
4201// getNextBuffer() = 0;
4202// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4204{
Glenn Kastene0feee32011-12-13 11:53:26 -08004205 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004206 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004207 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004208 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004209 buffer->frameCount = 0;
4210}
4211
4212bool AudioFlinger::ThreadBase::TrackBase::step() {
4213 bool result;
4214 audio_track_cblk_t* cblk = this->cblk();
4215
4216 result = cblk->stepServer(mFrameCount);
4217 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004218 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004219 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004220 }
4221 return result;
4222}
4223
4224void AudioFlinger::ThreadBase::TrackBase::reset() {
4225 audio_track_cblk_t* cblk = this->cblk();
4226
4227 cblk->user = 0;
4228 cblk->server = 0;
4229 cblk->userBase = 0;
4230 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004231 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004232 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004233}
4234
Mathias Agopian65ab4712010-07-14 17:59:35 -07004235int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4236 return (int)mCblk->sampleRate;
4237}
4238
Mathias Agopian65ab4712010-07-14 17:59:35 -07004239void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4240 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004241 size_t frameSize = cblk->frameSize;
4242 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4243 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004244
4245 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004246 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4247 "TrackBase::getBuffer buffer out of range:\n"
4248 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4249 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004250 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004251 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004252
4253 return bufferStart;
4254}
4255
Eric Laurenta011e352012-03-29 15:51:43 -07004256status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4257{
4258 mSyncEvents.add(event);
4259 return NO_ERROR;
4260}
4261
Mathias Agopian65ab4712010-07-14 17:59:35 -07004262// ----------------------------------------------------------------------------
4263
4264// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4265AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004266 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004267 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004268 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004269 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004270 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004271 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004272 int frameCount,
4273 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004274 int sessionId,
4275 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004276 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004277 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004278 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004279 // mRetryCount initialized later when needed
4280 mSharedBuffer(sharedBuffer),
4281 mStreamType(streamType),
4282 mName(-1), // see note below
4283 mMainBuffer(thread->mixBuffer()),
4284 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004285 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004286 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004287 mFlags(flags),
4288 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004289 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004290 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004291{
4292 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004293 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4294 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004295 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004296 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07004297 mName = thread->getTrackName_l(channelMask, sessionId);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004298 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004299 if (mName < 0) {
4300 ALOGE("no more track names available");
4301 return;
4302 }
4303 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004304 if (flags & IAudioFlinger::TRACK_FAST) {
4305 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4306 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4307 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004308 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004309 // FIXME This is too eager. We allocate a fast track index before the
4310 // fast track becomes active. Since fast tracks are a scarce resource,
4311 // this means we are potentially denying other more important fast tracks from
4312 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004313 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004314 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004315 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004316 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004317 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004318 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004319 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004320 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004321}
4322
4323AudioFlinger::PlaybackThread::Track::~Track()
4324{
Steve Block3856b092011-10-20 11:56:00 +01004325 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004326}
4327
4328void AudioFlinger::PlaybackThread::Track::destroy()
4329{
4330 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4331 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004332 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004333 // we must acquire a strong reference on this Track before locking mLock
4334 // here so that the destructor is called only when exiting this function.
4335 // On the other hand, as long as Track::destroy() is only called by
4336 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4337 // this Track with its member mTrack.
4338 sp<Track> keep(this);
4339 { // scope for mLock
4340 sp<ThreadBase> thread = mThread.promote();
4341 if (thread != 0) {
4342 if (!isOutputTrack()) {
4343 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004344 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004345
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004346#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004347 // to track the speaker usage
4348 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004349#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004350 }
4351 AudioSystem::releaseOutput(thread->id());
4352 }
4353 Mutex::Autolock _l(thread->mLock);
4354 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4355 playbackThread->destroyTrack_l(this);
4356 }
4357 }
4358}
4359
Glenn Kasten288ed212012-04-25 17:52:27 -07004360/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4361{
Glenn Kastene213c862012-04-25 13:46:15 -07004362 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 -07004363 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004364}
4365
Mathias Agopian65ab4712010-07-14 17:59:35 -07004366void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4367{
Glenn Kasten83d86532012-01-17 14:39:34 -08004368 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004369 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004370 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004371 } else {
4372 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4373 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004374 track_state state = mState;
4375 char stateChar;
4376 switch (state) {
4377 case IDLE:
4378 stateChar = 'I';
4379 break;
4380 case TERMINATED:
4381 stateChar = 'T';
4382 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004383 case STOPPING_1:
4384 stateChar = 's';
4385 break;
4386 case STOPPING_2:
4387 stateChar = '5';
4388 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004389 case STOPPED:
4390 stateChar = 'S';
4391 break;
4392 case RESUMING:
4393 stateChar = 'R';
4394 break;
4395 case ACTIVE:
4396 stateChar = 'A';
4397 break;
4398 case PAUSING:
4399 stateChar = 'p';
4400 break;
4401 case PAUSED:
4402 stateChar = 'P';
4403 break;
Eric Laurent29864602012-05-08 18:57:51 -07004404 case FLUSHED:
4405 stateChar = 'F';
4406 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004407 default:
4408 stateChar = '?';
4409 break;
4410 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004411 char nowInUnderrun;
4412 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4413 case UNDERRUN_FULL:
4414 nowInUnderrun = ' ';
4415 break;
4416 case UNDERRUN_PARTIAL:
4417 nowInUnderrun = '<';
4418 break;
4419 case UNDERRUN_EMPTY:
4420 nowInUnderrun = '*';
4421 break;
4422 default:
4423 nowInUnderrun = '?';
4424 break;
4425 }
Glenn Kastene213c862012-04-25 13:46:15 -07004426 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4427 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004428 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004429 mStreamType,
4430 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004431 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004432 mSessionId,
4433 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004434 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004435 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004436 mMute,
4437 mFillingUpStatus,
4438 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004439 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4440 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004441 mCblk->server,
4442 mCblk->user,
4443 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004444 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004445 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004446 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004447 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004448}
4449
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004450// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004451status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004452 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004453{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004454 audio_track_cblk_t* cblk = this->cblk();
4455 uint32_t framesReady;
4456 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004457
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004458 // Check if last stepServer failed, try to step now
4459 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004460 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4461 // Since the fast mixer is higher priority than client callback thread,
4462 // it does not result in priority inversion for client.
4463 // But a non-blocking solution would be preferable to avoid
4464 // fast mixer being unable to tryLock(), and
4465 // to avoid the extra context switches if the client wakes up,
4466 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004467 if (!step()) goto getNextBuffer_exit;
4468 ALOGV("stepServer recovered");
4469 mStepServerFailed = false;
4470 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004471
Glenn Kasten288ed212012-04-25 17:52:27 -07004472 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004473 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004474
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004475 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004476 uint32_t s = cblk->server;
4477 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4478
4479 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4480 if (framesReq > framesReady) {
4481 framesReq = framesReady;
4482 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004483 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004484 framesReq = bufferEnd - s;
4485 }
4486
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004487 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004488 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004489 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004490 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004491
4492getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004493 buffer->raw = NULL;
4494 buffer->frameCount = 0;
4495 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4496 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004497}
4498
Glenn Kasten288ed212012-04-25 17:52:27 -07004499// Note that framesReady() takes a mutex on the control block using tryLock().
4500// This could result in priority inversion if framesReady() is called by the normal mixer,
4501// as the normal mixer thread runs at lower
4502// priority than the client's callback thread: there is a short window within framesReady()
4503// during which the normal mixer could be preempted, and the client callback would block.
4504// Another problem can occur if framesReady() is called by the fast mixer:
4505// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4506// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4507size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004508 return mCblk->framesReady();
4509}
4510
Glenn Kasten288ed212012-04-25 17:52:27 -07004511// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004512bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004513 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004514
John Grossman4ff14ba2012-02-08 16:37:41 -08004515 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004516 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4517 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004518 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004519 return true;
4520 }
4521 return false;
4522}
4523
Glenn Kasten3acbd052012-02-28 10:39:56 -08004524status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004525 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004526{
4527 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004528 ALOGV("start(%d), calling pid %d session %d",
4529 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004530
Mathias Agopian65ab4712010-07-14 17:59:35 -07004531 sp<ThreadBase> thread = mThread.promote();
4532 if (thread != 0) {
4533 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004534 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004535 // here the track could be either new, or restarted
4536 // in both cases "unstop" the track
4537 if (mState == PAUSED) {
4538 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004539 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004540 } else {
4541 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004542 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004543 }
4544
4545 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4546 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004547 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004548 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004549
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004550#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004551 // to track the speaker usage
4552 if (status == NO_ERROR) {
4553 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4554 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004555#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004556 }
4557 if (status == NO_ERROR) {
4558 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4559 playbackThread->addTrack_l(this);
4560 } else {
4561 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004562 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004563 }
4564 } else {
4565 status = BAD_VALUE;
4566 }
4567 return status;
4568}
4569
4570void AudioFlinger::PlaybackThread::Track::stop()
4571{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004572 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004573 sp<ThreadBase> thread = mThread.promote();
4574 if (thread != 0) {
4575 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004576 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004577 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004578 // If the track is not active (PAUSED and buffers full), flush buffers
4579 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4580 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4581 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004582 mState = STOPPED;
4583 } else if (!isFastTrack()) {
4584 mState = STOPPED;
4585 } else {
4586 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4587 // and then to STOPPED and reset() when presentation is complete
4588 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004589 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004590 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004591 }
4592 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4593 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004594 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004595 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004596
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004597#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004598 // to track the speaker usage
4599 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004600#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004601 }
4602 }
4603}
4604
4605void AudioFlinger::PlaybackThread::Track::pause()
4606{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004607 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004608 sp<ThreadBase> thread = mThread.promote();
4609 if (thread != 0) {
4610 Mutex::Autolock _l(thread->mLock);
4611 if (mState == ACTIVE || mState == RESUMING) {
4612 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004613 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004614 if (!isOutputTrack()) {
4615 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004616 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004617 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004618
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004619#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004620 // to track the speaker usage
4621 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004622#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004623 }
4624 }
4625 }
4626}
4627
4628void AudioFlinger::PlaybackThread::Track::flush()
4629{
Steve Block3856b092011-10-20 11:56:00 +01004630 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004631 sp<ThreadBase> thread = mThread.promote();
4632 if (thread != 0) {
4633 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004634 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4635 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004636 return;
4637 }
4638 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004639 // FLUSHED state
4640 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004641 // do not reset the track if it is still in the process of being stopped or paused.
4642 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004643 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004644 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004645 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4646 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4647 reset();
4648 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004649 }
4650}
4651
4652void AudioFlinger::PlaybackThread::Track::reset()
4653{
4654 // Do not reset twice to avoid discarding data written just after a flush and before
4655 // the audioflinger thread detects the track is stopped.
4656 if (!mResetDone) {
4657 TrackBase::reset();
4658 // Force underrun condition to avoid false underrun callback until first data is
4659 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004660 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4661 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004662 mFillingUpStatus = FS_FILLING;
4663 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004664 if (mState == FLUSHED) {
4665 mState = IDLE;
4666 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004667 }
4668}
4669
4670void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4671{
4672 mMute = muted;
4673}
4674
Mathias Agopian65ab4712010-07-14 17:59:35 -07004675status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4676{
4677 status_t status = DEAD_OBJECT;
4678 sp<ThreadBase> thread = mThread.promote();
4679 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004680 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004681 sp<AudioFlinger> af = mClient->audioFlinger();
4682
4683 Mutex::Autolock _l(af->mLock);
4684
4685 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004686
Eric Laurent109347d2012-07-02 12:31:03 -07004687 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004688 Mutex::Autolock _dl(playbackThread->mLock);
4689 Mutex::Autolock _sl(srcThread->mLock);
4690 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4691 if (chain == 0) {
4692 return INVALID_OPERATION;
4693 }
4694
4695 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4696 if (effect == 0) {
4697 return INVALID_OPERATION;
4698 }
4699 srcThread->removeEffect_l(effect);
4700 playbackThread->addEffect_l(effect);
4701 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4702 if (effect->state() == EffectModule::ACTIVE ||
4703 effect->state() == EffectModule::STOPPING) {
4704 effect->start();
4705 }
4706
4707 sp<EffectChain> dstChain = effect->chain().promote();
4708 if (dstChain == 0) {
4709 srcThread->addEffect_l(effect);
4710 return INVALID_OPERATION;
4711 }
4712 AudioSystem::unregisterEffect(effect->id());
4713 AudioSystem::registerEffect(&effect->desc(),
4714 srcThread->id(),
4715 dstChain->strategy(),
4716 AUDIO_SESSION_OUTPUT_MIX,
4717 effect->id());
4718 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004719 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004720 }
4721 return status;
4722}
4723
4724void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4725{
4726 mAuxEffectId = EffectId;
4727 mAuxBuffer = buffer;
4728}
4729
Eric Laurenta011e352012-03-29 15:51:43 -07004730bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4731 size_t audioHalFrames)
4732{
4733 // a track is considered presented when the total number of frames written to audio HAL
4734 // corresponds to the number of frames written when presentationComplete() is called for the
4735 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4736 if (mPresentationCompleteFrames == 0) {
4737 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4738 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4739 mPresentationCompleteFrames, audioHalFrames);
4740 }
4741 if (framesWritten >= mPresentationCompleteFrames) {
4742 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4743 mSessionId, framesWritten);
4744 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004745 return true;
4746 }
4747 return false;
4748}
4749
4750void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4751{
4752 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4753 if (mSyncEvents[i]->type() == type) {
4754 mSyncEvents[i]->trigger();
4755 mSyncEvents.removeAt(i);
4756 i--;
4757 }
4758 }
4759}
4760
Glenn Kasten58912562012-04-03 10:45:00 -07004761// implement VolumeBufferProvider interface
4762
4763uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4764{
4765 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4766 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4767 uint32_t vlr = mCblk->getVolumeLR();
4768 uint32_t vl = vlr & 0xFFFF;
4769 uint32_t vr = vlr >> 16;
4770 // track volumes come from shared memory, so can't be trusted and must be clamped
4771 if (vl > MAX_GAIN_INT) {
4772 vl = MAX_GAIN_INT;
4773 }
4774 if (vr > MAX_GAIN_INT) {
4775 vr = MAX_GAIN_INT;
4776 }
4777 // now apply the cached master volume and stream type volume;
4778 // this is trusted but lacks any synchronization or barrier so may be stale
4779 float v = mCachedVolume;
4780 vl *= v;
4781 vr *= v;
4782 // re-combine into U4.16
4783 vlr = (vr << 16) | (vl & 0xFFFF);
4784 // FIXME look at mute, pause, and stop flags
4785 return vlr;
4786}
Eric Laurenta011e352012-03-29 15:51:43 -07004787
Eric Laurent29864602012-05-08 18:57:51 -07004788status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4789{
4790 if (mState == TERMINATED || mState == PAUSED ||
4791 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4792 (mState == STOPPED)))) {
4793 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4794 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4795 event->cancel();
4796 return INVALID_OPERATION;
4797 }
Glenn Kastend23eedc2012-08-02 13:35:47 -07004798 (void) TrackBase::setSyncEvent(event);
Eric Laurent29864602012-05-08 18:57:51 -07004799 return NO_ERROR;
4800}
4801
John Grossman4ff14ba2012-02-08 16:37:41 -08004802// timed audio tracks
4803
4804sp<AudioFlinger::PlaybackThread::TimedTrack>
4805AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004806 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004807 const sp<Client>& client,
4808 audio_stream_type_t streamType,
4809 uint32_t sampleRate,
4810 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004811 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004812 int frameCount,
4813 const sp<IMemory>& sharedBuffer,
4814 int sessionId) {
4815 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004816 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004817
Glenn Kastena0356762012-03-19 10:38:51 -07004818 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004819 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4820 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004821}
4822
4823AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004824 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004825 const sp<Client>& client,
4826 audio_stream_type_t streamType,
4827 uint32_t sampleRate,
4828 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004829 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004830 int frameCount,
4831 const sp<IMemory>& sharedBuffer,
4832 int sessionId)
4833 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004834 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004835 mQueueHeadInFlight(false),
4836 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004837 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004838 mTimedSilenceBuffer(NULL),
4839 mTimedSilenceBufferSize(0),
4840 mTimedAudioOutputOnTime(false),
4841 mMediaTimeTransformValid(false)
4842{
4843 LocalClock lc;
4844 mLocalTimeFreq = lc.getLocalFreq();
4845
4846 mLocalTimeToSampleTransform.a_zero = 0;
4847 mLocalTimeToSampleTransform.b_zero = 0;
4848 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4849 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4850 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4851 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004852
4853 mMediaTimeToSampleTransform.a_zero = 0;
4854 mMediaTimeToSampleTransform.b_zero = 0;
4855 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4856 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4857 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4858 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004859}
4860
4861AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4862 mClient->releaseTimedTrack();
4863 delete [] mTimedSilenceBuffer;
4864}
4865
4866status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4867 size_t size, sp<IMemory>* buffer) {
4868
4869 Mutex::Autolock _l(mTimedBufferQueueLock);
4870
4871 trimTimedBufferQueue_l();
4872
4873 // lazily initialize the shared memory heap for timed buffers
4874 if (mTimedMemoryDealer == NULL) {
4875 const int kTimedBufferHeapSize = 512 << 10;
4876
4877 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4878 "AudioFlingerTimed");
4879 if (mTimedMemoryDealer == NULL)
4880 return NO_MEMORY;
4881 }
4882
4883 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4884 if (newBuffer == NULL) {
4885 newBuffer = mTimedMemoryDealer->allocate(size);
4886 if (newBuffer == NULL)
4887 return NO_MEMORY;
4888 }
4889
4890 *buffer = newBuffer;
4891 return NO_ERROR;
4892}
4893
4894// caller must hold mTimedBufferQueueLock
4895void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4896 int64_t mediaTimeNow;
4897 {
4898 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4899 if (!mMediaTimeTransformValid)
4900 return;
4901
4902 int64_t targetTimeNow;
4903 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4904 ? mCCHelper.getCommonTime(&targetTimeNow)
4905 : mCCHelper.getLocalTime(&targetTimeNow);
4906
4907 if (OK != res)
4908 return;
4909
4910 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4911 &mediaTimeNow)) {
4912 return;
4913 }
4914 }
4915
John Grossman1c345192012-03-27 14:00:17 -07004916 size_t trimEnd;
4917 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004918 int64_t bufEnd;
4919
John Grossmanc95cfbb2012-04-12 11:53:11 -07004920 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4921 // We have a next buffer. Just use its PTS as the PTS of the frame
4922 // following the last frame in this buffer. If the stream is sparse
4923 // (ie, there are deliberate gaps left in the stream which should be
4924 // filled with silence by the TimedAudioTrack), then this can result
4925 // in one extra buffer being left un-trimmed when it could have
4926 // been. In general, this is not typical, and we would rather
4927 // optimized away the TS calculation below for the more common case
4928 // where PTSes are contiguous.
4929 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4930 } else {
4931 // We have no next buffer. Compute the PTS of the frame following
4932 // the last frame in this buffer by computing the duration of of
4933 // this frame in media time units and adding it to the PTS of the
4934 // buffer.
4935 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4936 / mCblk->frameSize;
4937
4938 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4939 &bufEnd)) {
4940 ALOGE("Failed to convert frame count of %lld to media time"
4941 " duration" " (scale factor %d/%u) in %s",
4942 frameCount,
4943 mMediaTimeToSampleTransform.a_to_b_numer,
4944 mMediaTimeToSampleTransform.a_to_b_denom,
4945 __PRETTY_FUNCTION__);
4946 break;
4947 }
4948 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004949 }
John Grossman9fbdee12012-03-26 17:51:46 -07004950
4951 if (bufEnd > mediaTimeNow)
4952 break;
4953
4954 // Is the buffer we want to use in the middle of a mix operation right
4955 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4956 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004957 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004958 mTrimQueueHeadOnRelease = true;
4959 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004960 }
4961
John Grossman9fbdee12012-03-26 17:51:46 -07004962 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004963 if (trimStart < trimEnd) {
4964 // Update the bookkeeping for framesReady()
4965 for (size_t i = trimStart; i < trimEnd; ++i) {
4966 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4967 }
4968
4969 // Now actually remove the buffers from the queue.
4970 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004971 }
4972}
4973
John Grossman1c345192012-03-27 14:00:17 -07004974void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4975 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004976 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4977 "%s called (reason \"%s\"), but timed buffer queue has no"
4978 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004979
4980 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4981 mTimedBufferQueue.removeAt(0);
4982}
4983
4984void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4985 const TimedBuffer& buf,
4986 const char* logTag) {
4987 uint32_t bufBytes = buf.buffer()->size();
4988 uint32_t consumedAlready = buf.position();
4989
Eric Laurentb388e532012-04-14 13:32:48 -07004990 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004991 "Bad bookkeeping while updating frames pending. Timed buffer is"
4992 " only %u bytes long, but claims to have consumed %u"
4993 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004994 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004995
4996 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004997 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4998 "Bad bookkeeping while updating frames pending. Should have at"
4999 " least %u queued frames, but we think we have only %u. (update"
5000 " reason: \"%s\")",
5001 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005002
5003 mFramesPendingInQueue -= bufFrames;
5004}
5005
John Grossman4ff14ba2012-02-08 16:37:41 -08005006status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5007 const sp<IMemory>& buffer, int64_t pts) {
5008
5009 {
5010 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5011 if (!mMediaTimeTransformValid)
5012 return INVALID_OPERATION;
5013 }
5014
5015 Mutex::Autolock _l(mTimedBufferQueueLock);
5016
John Grossman1c345192012-03-27 14:00:17 -07005017 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5018 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005019 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5020
5021 return NO_ERROR;
5022}
5023
5024status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5025 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5026
John Grossman1c345192012-03-27 14:00:17 -07005027 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5028 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5029 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005030
5031 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5032 target == TimedAudioTrack::COMMON_TIME)) {
5033 return BAD_VALUE;
5034 }
5035
5036 Mutex::Autolock lock(mMediaTimeTransformLock);
5037 mMediaTimeTransform = xform;
5038 mMediaTimeTransformTarget = target;
5039 mMediaTimeTransformValid = true;
5040
5041 return NO_ERROR;
5042}
5043
5044#define min(a, b) ((a) < (b) ? (a) : (b))
5045
5046// implementation of getNextBuffer for tracks whose buffers have timestamps
5047status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5048 AudioBufferProvider::Buffer* buffer, int64_t pts)
5049{
5050 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005051 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005052 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005053 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005054 return INVALID_OPERATION;
5055 }
5056
John Grossman4ff14ba2012-02-08 16:37:41 -08005057 Mutex::Autolock _l(mTimedBufferQueueLock);
5058
John Grossman9fbdee12012-03-26 17:51:46 -07005059 ALOG_ASSERT(!mQueueHeadInFlight,
5060 "getNextBuffer called without releaseBuffer!");
5061
John Grossman4ff14ba2012-02-08 16:37:41 -08005062 while (true) {
5063
5064 // if we have no timed buffers, then fail
5065 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005066 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005067 buffer->frameCount = 0;
5068 return NOT_ENOUGH_DATA;
5069 }
5070
5071 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5072
5073 // calculate the PTS of the head of the timed buffer queue expressed in
5074 // local time
5075 int64_t headLocalPTS;
5076 {
5077 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5078
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005079 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005080
5081 if (mMediaTimeTransform.a_to_b_denom == 0) {
5082 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005083 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005084 return NO_ERROR;
5085 }
5086
5087 int64_t transformedPTS;
5088 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5089 &transformedPTS)) {
5090 // the transform failed. this shouldn't happen, but if it does
5091 // then just drop this buffer
5092 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005093 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005094 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005095 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005096 return NO_ERROR;
5097 }
5098
5099 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5100 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5101 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005102 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005103 buffer->frameCount = 0;
5104 return INVALID_OPERATION;
5105 }
5106 } else {
5107 headLocalPTS = transformedPTS;
5108 }
5109 }
5110
5111 // adjust the head buffer's PTS to reflect the portion of the head buffer
5112 // that has already been consumed
5113 int64_t effectivePTS = headLocalPTS +
5114 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5115
5116 // Calculate the delta in samples between the head of the input buffer
5117 // queue and the start of the next output buffer that will be written.
5118 // If the transformation fails because of over or underflow, it means
5119 // that the sample's position in the output stream is so far out of
5120 // whack that it should just be dropped.
5121 int64_t sampleDelta;
5122 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5123 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005124 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5125 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005126 continue;
5127 }
5128 if (!mLocalTimeToSampleTransform.doForwardTransform(
5129 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005130 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005131 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005132 continue;
5133 }
5134
John Grossman1c345192012-03-27 14:00:17 -07005135 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5136 " sampleDelta=[%d.%08x]",
5137 head.pts(), head.position(), pts,
5138 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5139 + (sampleDelta >> 32)),
5140 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005141
5142 // if the delta between the ideal placement for the next input sample and
5143 // the current output position is within this threshold, then we will
5144 // concatenate the next input samples to the previous output
5145 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005146 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005147
5148 // if this is the first buffer of audio that we're emitting from this track
5149 // then it should be almost exactly on time.
5150 const int64_t kSampleStartupThreshold = 1LL << 32;
5151
5152 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005153 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005154 // the next input is close enough to being on time, so concatenate it
5155 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005156 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005157
John Grossman1c345192012-03-27 14:00:17 -07005158 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5159 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005160 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005161 }
5162
5163 // Looks like our output is not on time. Reset our on timed status.
5164 // Next time we mix samples from our input queue, then should be within
5165 // the StartupThreshold.
5166 mTimedAudioOutputOnTime = false;
5167 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005168 // the gap between the current output position and the proper start of
5169 // the next input sample is too big, so fill it with silence
5170 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5171
John Grossman9fbdee12012-03-26 17:51:46 -07005172 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005173 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5174 return NO_ERROR;
5175 } else {
5176 // the next input sample is late
5177 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5178 size_t onTimeSamplePosition =
5179 head.position() + lateFrames * mCblk->frameSize;
5180
5181 if (onTimeSamplePosition > head.buffer()->size()) {
5182 // all the remaining samples in the head are too late, so
5183 // drop it and move on
5184 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005185 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005186 continue;
5187 } else {
5188 // skip over the late samples
5189 head.setPosition(onTimeSamplePosition);
5190
5191 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005192 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005193
5194 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5195 return NO_ERROR;
5196 }
5197 }
5198 }
5199}
5200
5201// Yield samples from the timed buffer queue head up to the given output
5202// buffer's capacity.
5203//
5204// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005205void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005206 AudioBufferProvider::Buffer* buffer) {
5207
5208 const TimedBuffer& head = mTimedBufferQueue[0];
5209
5210 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5211 head.position());
5212
5213 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5214 mCblk->frameSize);
5215 size_t framesRequested = buffer->frameCount;
5216 buffer->frameCount = min(framesLeftInHead, framesRequested);
5217
John Grossman9fbdee12012-03-26 17:51:46 -07005218 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005219 mTimedAudioOutputOnTime = true;
5220}
5221
5222// Yield samples of silence up to the given output buffer's capacity
5223//
5224// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005225void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005226 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5227
5228 // lazily allocate a buffer filled with silence
5229 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5230 delete [] mTimedSilenceBuffer;
5231 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5232 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5233 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5234 }
5235
5236 buffer->raw = mTimedSilenceBuffer;
5237 size_t framesRequested = buffer->frameCount;
5238 buffer->frameCount = min(numFrames, framesRequested);
5239
5240 mTimedAudioOutputOnTime = false;
5241}
5242
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005243// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005244void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5245 AudioBufferProvider::Buffer* buffer) {
5246
5247 Mutex::Autolock _l(mTimedBufferQueueLock);
5248
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005249 // If the buffer which was just released is part of the buffer at the head
5250 // of the queue, be sure to update the amt of the buffer which has been
5251 // consumed. If the buffer being returned is not part of the head of the
5252 // queue, its either because the buffer is part of the silence buffer, or
5253 // because the head of the timed queue was trimmed after the mixer called
5254 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005255 if (buffer->raw == mTimedSilenceBuffer) {
5256 ALOG_ASSERT(!mQueueHeadInFlight,
5257 "Queue head in flight during release of silence buffer!");
5258 goto done;
5259 }
5260
5261 ALOG_ASSERT(mQueueHeadInFlight,
5262 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5263 " head in flight.");
5264
5265 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005266 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005267
5268 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005269 void* end = reinterpret_cast<void*>(
5270 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5271 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005272
John Grossman9fbdee12012-03-26 17:51:46 -07005273 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5274 "released buffer not within the head of the timed buffer"
5275 " queue; qHead = [%p, %p], released buffer = %p",
5276 start, end, buffer->raw);
5277
5278 head.setPosition(head.position() +
5279 (buffer->frameCount * mCblk->frameSize));
5280 mQueueHeadInFlight = false;
5281
John Grossman1c345192012-03-27 14:00:17 -07005282 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5283 "Bad bookkeeping during releaseBuffer! Should have at"
5284 " least %u queued frames, but we think we have only %u",
5285 buffer->frameCount, mFramesPendingInQueue);
5286
5287 mFramesPendingInQueue -= buffer->frameCount;
5288
John Grossman9fbdee12012-03-26 17:51:46 -07005289 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5290 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005291 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005292 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005293 }
John Grossman9fbdee12012-03-26 17:51:46 -07005294 } else {
5295 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5296 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005297 }
5298
John Grossman9fbdee12012-03-26 17:51:46 -07005299done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005300 buffer->raw = 0;
5301 buffer->frameCount = 0;
5302}
5303
Glenn Kasten288ed212012-04-25 17:52:27 -07005304size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005305 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005306 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005307}
5308
5309AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5310 : mPTS(0), mPosition(0) {}
5311
5312AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5313 const sp<IMemory>& buffer, int64_t pts)
5314 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5315
Mathias Agopian65ab4712010-07-14 17:59:35 -07005316// ----------------------------------------------------------------------------
5317
5318// RecordTrack constructor must be called with AudioFlinger::mLock held
5319AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005320 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005321 const sp<Client>& client,
5322 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005323 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005324 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005325 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005326 int sessionId)
5327 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005328 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005329 mOverflow(false)
5330{
5331 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005332 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5333 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5334 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5335 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5336 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5337 } else {
5338 mCblk->frameSize = sizeof(int8_t);
5339 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005340 }
5341}
5342
5343AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5344{
Glenn Kasten510a3d62012-07-16 14:24:34 -07005345 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005346}
5347
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005348// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005349status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005350{
5351 audio_track_cblk_t* cblk = this->cblk();
5352 uint32_t framesAvail;
5353 uint32_t framesReq = buffer->frameCount;
5354
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005355 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005356 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005357 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005358 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005359 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005360 }
5361
5362 framesAvail = cblk->framesAvailable_l();
5363
Glenn Kastenf6b16782011-12-15 09:51:17 -08005364 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005365 uint32_t s = cblk->server;
5366 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5367
5368 if (framesReq > framesAvail) {
5369 framesReq = framesAvail;
5370 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005371 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372 framesReq = bufferEnd - s;
5373 }
5374
5375 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005376 buffer->frameCount = framesReq;
5377 return NO_ERROR;
5378 }
5379
5380getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005381 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005382 buffer->frameCount = 0;
5383 return NOT_ENOUGH_DATA;
5384}
5385
Glenn Kasten3acbd052012-02-28 10:39:56 -08005386status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005387 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005388{
5389 sp<ThreadBase> thread = mThread.promote();
5390 if (thread != 0) {
5391 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005392 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005393 } else {
5394 return BAD_VALUE;
5395 }
5396}
5397
5398void AudioFlinger::RecordThread::RecordTrack::stop()
5399{
5400 sp<ThreadBase> thread = mThread.promote();
5401 if (thread != 0) {
5402 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005403 recordThread->mLock.lock();
5404 bool doStop = recordThread->stop_l(this);
5405 if (doStop) {
5406 TrackBase::reset();
5407 // Force overrun condition to avoid false overrun callback until first data is
5408 // read from buffer
5409 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5410 }
5411 recordThread->mLock.unlock();
5412 if (doStop) {
5413 AudioSystem::stopInput(recordThread->id());
5414 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005415 }
5416}
5417
Glenn Kasten510a3d62012-07-16 14:24:34 -07005418/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
5419{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005420 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User FrameCount\n");
Glenn Kasten510a3d62012-07-16 14:24:34 -07005421}
5422
Mathias Agopian65ab4712010-07-14 17:59:35 -07005423void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5424{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005425 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x %05d\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005426 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005427 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005428 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005429 mSessionId,
5430 mFrameCount,
5431 mState,
5432 mCblk->sampleRate,
5433 mCblk->server,
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005434 mCblk->user,
5435 mCblk->frameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005436}
5437
5438
5439// ----------------------------------------------------------------------------
5440
5441AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005442 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005443 DuplicatingThread *sourceThread,
5444 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005445 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005446 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005447 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005448 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5449 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005450 mActive(false), mSourceThread(sourceThread)
5451{
5452
Mathias Agopian65ab4712010-07-14 17:59:35 -07005453 if (mCblk != NULL) {
5454 mCblk->flags |= CBLK_DIRECTION_OUT;
5455 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005456 mOutBuffer.frameCount = 0;
5457 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005458 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005459 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5460 mCblk, mBuffer, mCblk->buffers,
5461 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005462 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005463 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005464 }
5465}
5466
5467AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5468{
5469 clearBufferQueue();
5470}
5471
Glenn Kasten3acbd052012-02-28 10:39:56 -08005472status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005473 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005474{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005475 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005476 if (status != NO_ERROR) {
5477 return status;
5478 }
5479
5480 mActive = true;
5481 mRetryCount = 127;
5482 return status;
5483}
5484
5485void AudioFlinger::PlaybackThread::OutputTrack::stop()
5486{
5487 Track::stop();
5488 clearBufferQueue();
5489 mOutBuffer.frameCount = 0;
5490 mActive = false;
5491}
5492
5493bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5494{
5495 Buffer *pInBuffer;
5496 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005497 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005498 bool outputBufferFull = false;
5499 inBuffer.frameCount = frames;
5500 inBuffer.i16 = data;
5501
5502 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5503
5504 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005505 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005506 sp<ThreadBase> thread = mThread.promote();
5507 if (thread != 0) {
5508 MixerThread *mixerThread = (MixerThread *)thread.get();
5509 if (mCblk->frameCount > frames){
5510 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5511 uint32_t startFrames = (mCblk->frameCount - frames);
5512 pInBuffer = new Buffer;
5513 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5514 pInBuffer->frameCount = startFrames;
5515 pInBuffer->i16 = pInBuffer->mBuffer;
5516 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5517 mBufferQueue.add(pInBuffer);
5518 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005519 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005520 }
5521 }
5522 }
5523 }
5524
5525 while (waitTimeLeftMs) {
5526 // First write pending buffers, then new data
5527 if (mBufferQueue.size()) {
5528 pInBuffer = mBufferQueue.itemAt(0);
5529 } else {
5530 pInBuffer = &inBuffer;
5531 }
5532
5533 if (pInBuffer->frameCount == 0) {
5534 break;
5535 }
5536
5537 if (mOutBuffer.frameCount == 0) {
5538 mOutBuffer.frameCount = pInBuffer->frameCount;
5539 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005540 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005541 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005542 outputBufferFull = true;
5543 break;
5544 }
5545 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5546 if (waitTimeLeftMs >= waitTimeMs) {
5547 waitTimeLeftMs -= waitTimeMs;
5548 } else {
5549 waitTimeLeftMs = 0;
5550 }
5551 }
5552
5553 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5554 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5555 mCblk->stepUser(outFrames);
5556 pInBuffer->frameCount -= outFrames;
5557 pInBuffer->i16 += outFrames * channelCount;
5558 mOutBuffer.frameCount -= outFrames;
5559 mOutBuffer.i16 += outFrames * channelCount;
5560
5561 if (pInBuffer->frameCount == 0) {
5562 if (mBufferQueue.size()) {
5563 mBufferQueue.removeAt(0);
5564 delete [] pInBuffer->mBuffer;
5565 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005566 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005567 } else {
5568 break;
5569 }
5570 }
5571 }
5572
5573 // If we could not write all frames, allocate a buffer and queue it for next time.
5574 if (inBuffer.frameCount) {
5575 sp<ThreadBase> thread = mThread.promote();
5576 if (thread != 0 && !thread->standby()) {
5577 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5578 pInBuffer = new Buffer;
5579 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5580 pInBuffer->frameCount = inBuffer.frameCount;
5581 pInBuffer->i16 = pInBuffer->mBuffer;
5582 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5583 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005584 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005585 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005586 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005587 }
5588 }
5589 }
5590
5591 // Calling write() with a 0 length buffer, means that no more data will be written:
5592 // If no more buffers are pending, fill output track buffer to make sure it is started
5593 // by output mixer.
5594 if (frames == 0 && mBufferQueue.size() == 0) {
5595 if (mCblk->user < mCblk->frameCount) {
5596 frames = mCblk->frameCount - mCblk->user;
5597 pInBuffer = new Buffer;
5598 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5599 pInBuffer->frameCount = frames;
5600 pInBuffer->i16 = pInBuffer->mBuffer;
5601 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5602 mBufferQueue.add(pInBuffer);
5603 } else if (mActive) {
5604 stop();
5605 }
5606 }
5607
5608 return outputBufferFull;
5609}
5610
5611status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5612{
5613 int active;
5614 status_t result;
5615 audio_track_cblk_t* cblk = mCblk;
5616 uint32_t framesReq = buffer->frameCount;
5617
Steve Block3856b092011-10-20 11:56:00 +01005618// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005619 buffer->frameCount = 0;
5620
5621 uint32_t framesAvail = cblk->framesAvailable();
5622
5623
5624 if (framesAvail == 0) {
5625 Mutex::Autolock _l(cblk->lock);
5626 goto start_loop_here;
5627 while (framesAvail == 0) {
5628 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005629 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005630 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005631 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005632 }
5633 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5634 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005635 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005636 }
5637 // read the server count again
5638 start_loop_here:
5639 framesAvail = cblk->framesAvailable_l();
5640 }
5641 }
5642
5643// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005644// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005645// }
5646
5647 if (framesReq > framesAvail) {
5648 framesReq = framesAvail;
5649 }
5650
5651 uint32_t u = cblk->user;
5652 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5653
Marco Nelissena1472d92012-03-30 14:36:54 -07005654 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005655 framesReq = bufferEnd - u;
5656 }
5657
5658 buffer->frameCount = framesReq;
5659 buffer->raw = (void *)cblk->buffer(u);
5660 return NO_ERROR;
5661}
5662
5663
5664void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5665{
5666 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005667
5668 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005669 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005670 delete [] pBuffer->mBuffer;
5671 delete pBuffer;
5672 }
5673 mBufferQueue.clear();
5674}
5675
5676// ----------------------------------------------------------------------------
5677
5678AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5679 : RefBase(),
5680 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005681 // 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 -07005682 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005683 mPid(pid),
5684 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005685{
5686 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5687}
5688
5689// Client destructor must be called with AudioFlinger::mLock held
5690AudioFlinger::Client::~Client()
5691{
5692 mAudioFlinger->removeClient_l(mPid);
5693}
5694
Glenn Kasten435dbe62012-01-30 10:15:48 -08005695sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005696{
5697 return mMemoryDealer;
5698}
5699
John Grossman4ff14ba2012-02-08 16:37:41 -08005700// Reserve one of the limited slots for a timed audio track associated
5701// with this client
5702bool AudioFlinger::Client::reserveTimedTrack()
5703{
5704 const int kMaxTimedTracksPerClient = 4;
5705
5706 Mutex::Autolock _l(mTimedTrackLock);
5707
5708 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5709 ALOGW("can not create timed track - pid %d has exceeded the limit",
5710 mPid);
5711 return false;
5712 }
5713
5714 mTimedTrackCount++;
5715 return true;
5716}
5717
5718// Release a slot for a timed audio track
5719void AudioFlinger::Client::releaseTimedTrack()
5720{
5721 Mutex::Autolock _l(mTimedTrackLock);
5722 mTimedTrackCount--;
5723}
5724
Mathias Agopian65ab4712010-07-14 17:59:35 -07005725// ----------------------------------------------------------------------------
5726
5727AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5728 const sp<IAudioFlingerClient>& client,
5729 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005730 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005731{
5732}
5733
5734AudioFlinger::NotificationClient::~NotificationClient()
5735{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005736}
5737
5738void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5739{
5740 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005741 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005742}
5743
5744// ----------------------------------------------------------------------------
5745
5746AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5747 : BnAudioTrack(),
5748 mTrack(track)
5749{
5750}
5751
5752AudioFlinger::TrackHandle::~TrackHandle() {
5753 // just stop the track on deletion, associated resources
5754 // will be freed from the main thread once all pending buffers have
5755 // been played. Unless it's not in the active track list, in which
5756 // case we free everything now...
5757 mTrack->destroy();
5758}
5759
Glenn Kasten90716c52012-01-26 13:40:12 -08005760sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5761 return mTrack->getCblk();
5762}
5763
Glenn Kasten3acbd052012-02-28 10:39:56 -08005764status_t AudioFlinger::TrackHandle::start() {
5765 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005766}
5767
5768void AudioFlinger::TrackHandle::stop() {
5769 mTrack->stop();
5770}
5771
5772void AudioFlinger::TrackHandle::flush() {
5773 mTrack->flush();
5774}
5775
5776void AudioFlinger::TrackHandle::mute(bool e) {
5777 mTrack->mute(e);
5778}
5779
5780void AudioFlinger::TrackHandle::pause() {
5781 mTrack->pause();
5782}
5783
Mathias Agopian65ab4712010-07-14 17:59:35 -07005784status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5785{
5786 return mTrack->attachAuxEffect(EffectId);
5787}
5788
John Grossman4ff14ba2012-02-08 16:37:41 -08005789status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5790 sp<IMemory>* buffer) {
5791 if (!mTrack->isTimedTrack())
5792 return INVALID_OPERATION;
5793
5794 PlaybackThread::TimedTrack* tt =
5795 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5796 return tt->allocateTimedBuffer(size, buffer);
5797}
5798
5799status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5800 int64_t pts) {
5801 if (!mTrack->isTimedTrack())
5802 return INVALID_OPERATION;
5803
5804 PlaybackThread::TimedTrack* tt =
5805 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5806 return tt->queueTimedBuffer(buffer, pts);
5807}
5808
5809status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5810 const LinearTransform& xform, int target) {
5811
5812 if (!mTrack->isTimedTrack())
5813 return INVALID_OPERATION;
5814
5815 PlaybackThread::TimedTrack* tt =
5816 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5817 return tt->setMediaTimeTransform(
5818 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5819}
5820
Mathias Agopian65ab4712010-07-14 17:59:35 -07005821status_t AudioFlinger::TrackHandle::onTransact(
5822 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5823{
5824 return BnAudioTrack::onTransact(code, data, reply, flags);
5825}
5826
5827// ----------------------------------------------------------------------------
5828
5829sp<IAudioRecord> AudioFlinger::openRecord(
5830 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005831 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005832 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005833 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005834 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005835 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005836 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07005837 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005838 int *sessionId,
5839 status_t *status)
5840{
5841 sp<RecordThread::RecordTrack> recordTrack;
5842 sp<RecordHandle> recordHandle;
5843 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005844 status_t lStatus;
5845 RecordThread *thread;
5846 size_t inFrameCount;
5847 int lSessionId;
5848
5849 // check calling permissions
5850 if (!recordingAllowed()) {
5851 lStatus = PERMISSION_DENIED;
5852 goto Exit;
5853 }
5854
5855 // add client to list
5856 { // scope for mLock
5857 Mutex::Autolock _l(mLock);
5858 thread = checkRecordThread_l(input);
5859 if (thread == NULL) {
5860 lStatus = BAD_VALUE;
5861 goto Exit;
5862 }
5863
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005864 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005865
5866 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005867 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005868 lSessionId = *sessionId;
5869 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005870 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005871 if (sessionId != NULL) {
5872 *sessionId = lSessionId;
5873 }
5874 }
5875 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07005876 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5877 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005878 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005879 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005880 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5881 // destructor is called by the TrackBase destructor with mLock held
5882 client.clear();
5883 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005884 goto Exit;
5885 }
5886
5887 // return to handle to client
5888 recordHandle = new RecordHandle(recordTrack);
5889 lStatus = NO_ERROR;
5890
5891Exit:
5892 if (status) {
5893 *status = lStatus;
5894 }
5895 return recordHandle;
5896}
5897
5898// ----------------------------------------------------------------------------
5899
5900AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5901 : BnAudioRecord(),
5902 mRecordTrack(recordTrack)
5903{
5904}
5905
5906AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005907 stop_nonvirtual();
Glenn Kasten510a3d62012-07-16 14:24:34 -07005908 mRecordTrack->destroy();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005909}
5910
Glenn Kasten90716c52012-01-26 13:40:12 -08005911sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5912 return mRecordTrack->getCblk();
5913}
5914
Glenn Kasten0ec23ce2012-07-10 12:56:08 -07005915status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005916 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005917 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005918}
5919
5920void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005921 stop_nonvirtual();
5922}
5923
5924void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01005925 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005926 mRecordTrack->stop();
5927}
5928
Mathias Agopian65ab4712010-07-14 17:59:35 -07005929status_t AudioFlinger::RecordHandle::onTransact(
5930 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5931{
5932 return BnAudioRecord::onTransact(code, data, reply, flags);
5933}
5934
5935// ----------------------------------------------------------------------------
5936
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005937AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5938 AudioStreamIn *input,
5939 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07005940 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005941 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07005942 audio_devices_t device) :
Eric Laurentf1c04f92012-08-28 14:26:53 -07005943 ThreadBase(audioFlinger, id, AUDIO_DEVICE_NONE, device, RECORD),
Glenn Kasten510a3d62012-07-16 14:24:34 -07005944 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005945 // mRsmpInIndex and mInputBytes set by readInputParameters()
Glenn Kasten254af182012-07-03 14:59:05 -07005946 mReqChannelCount(popcount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005947 mReqSampleRate(sampleRate)
5948 // mBytesRead is only meaningful while active, and so is cleared in start()
5949 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005950{
Glenn Kasten480b4682012-02-28 12:30:08 -08005951 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005952
Mathias Agopian65ab4712010-07-14 17:59:35 -07005953 readInputParameters();
5954}
5955
5956
5957AudioFlinger::RecordThread::~RecordThread()
5958{
5959 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005960 delete mResampler;
5961 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005962}
5963
5964void AudioFlinger::RecordThread::onFirstRef()
5965{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005966 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005967}
5968
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005969status_t AudioFlinger::RecordThread::readyToRun()
5970{
5971 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005972 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005973 return status;
5974}
5975
Mathias Agopian65ab4712010-07-14 17:59:35 -07005976bool AudioFlinger::RecordThread::threadLoop()
5977{
5978 AudioBufferProvider::Buffer buffer;
5979 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005980 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005981
Eric Laurent44d98482010-09-30 16:12:31 -07005982 nsecs_t lastWarning = 0;
5983
Glenn Kastene4e2a372012-07-23 12:55:09 -07005984 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07005985 acquireWakeLock();
5986
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005987 // used to verify we've read at least one before evaluating how many bytes were read
5988 bool readOnce = false;
5989
Mathias Agopian65ab4712010-07-14 17:59:35 -07005990 // start recording
5991 while (!exitPending()) {
5992
5993 processConfigEvents();
5994
5995 { // scope for mLock
5996 Mutex::Autolock _l(mLock);
5997 checkForNewParameters_l();
5998 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07005999 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006000
6001 if (exitPending()) break;
6002
Eric Laurentfeb0db62011-07-22 09:04:31 -07006003 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01006004 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006005 // go to sleep
6006 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006007 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006008 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006009 continue;
6010 }
6011 if (mActiveTrack != 0) {
6012 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006013 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006014 mActiveTrack.clear();
6015 mStartStopCond.broadcast();
6016 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6017 if (mReqChannelCount != mActiveTrack->channelCount()) {
6018 mActiveTrack.clear();
6019 mStartStopCond.broadcast();
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006020 } else if (readOnce) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006021 // record start succeeds only if first read from audio input
6022 // succeeds
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006023 if (mBytesRead >= 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006024 mActiveTrack->mState = TrackBase::ACTIVE;
6025 } else {
6026 mActiveTrack.clear();
6027 }
6028 mStartStopCond.broadcast();
6029 }
6030 mStandby = false;
Glenn Kasten510a3d62012-07-16 14:24:34 -07006031 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
6032 removeTrack_l(mActiveTrack);
6033 mActiveTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006034 }
6035 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006036 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006037 }
6038
6039 if (mActiveTrack != 0) {
6040 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6041 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006042 unlockEffectChains(effectChains);
6043 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006044 continue;
6045 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006046 for (size_t i = 0; i < effectChains.size(); i ++) {
6047 effectChains[i]->process_l();
6048 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006049
Mathias Agopian65ab4712010-07-14 17:59:35 -07006050 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006051 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006052 readOnce = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006053 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006054 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006055 // no resampling
6056 while (framesOut) {
6057 size_t framesIn = mFrameCount - mRsmpInIndex;
6058 if (framesIn) {
6059 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6060 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6061 if (framesIn > framesOut)
6062 framesIn = framesOut;
6063 mRsmpInIndex += framesIn;
6064 framesOut -= framesIn;
6065 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006066 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006067 memcpy(dst, src, framesIn * mFrameSize);
6068 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006069 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006070 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6071 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006072 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006073 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6074 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006075 }
6076 }
6077 }
6078 if (framesOut && mFrameCount == mRsmpInIndex) {
6079 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006080 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006081 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006082 framesOut = 0;
6083 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006084 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006085 mRsmpInIndex = 0;
6086 }
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006087 if (mBytesRead <= 0) {
6088 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
6089 {
6090 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006091 // Force input into standby so that it tries to
6092 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006093 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006094 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006095 }
6096 mRsmpInIndex = mFrameCount;
6097 framesOut = 0;
6098 buffer.frameCount = 0;
6099 }
6100 }
6101 }
6102 } else {
6103 // resampling
6104
6105 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6106 // alter output frame count as if we were expecting stereo samples
6107 if (mChannelCount == 1 && mReqChannelCount == 1) {
6108 framesOut >>= 1;
6109 }
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07006110 mResampler->resample(mRsmpOutBuffer, framesOut, this /* AudioBufferProvider* */);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006111 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6112 // are 32 bit aligned which should be always true.
6113 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006114 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006115 // the resampler always outputs stereo samples: do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006116 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6117 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006118 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006119 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120 }
6121
6122 }
Eric Laurenta011e352012-03-29 15:51:43 -07006123 if (mFramestoDrop == 0) {
6124 mActiveTrack->releaseBuffer(&buffer);
6125 } else {
6126 if (mFramestoDrop > 0) {
6127 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006128 if (mFramestoDrop <= 0) {
6129 clearSyncStartEvent();
6130 }
6131 } else {
6132 mFramestoDrop += buffer.frameCount;
6133 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6134 mSyncStartEvent->isCancelled()) {
6135 ALOGW("Synced record %s, session %d, trigger session %d",
6136 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6137 mActiveTrack->sessionId(),
6138 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6139 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006140 }
6141 }
6142 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006143 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006144 }
6145 // client isn't retrieving buffers fast enough
6146 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006147 if (!mActiveTrack->setOverflow()) {
6148 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006149 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006150 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006151 lastWarning = now;
6152 }
6153 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006154 // Release the processor for a while before asking for a new buffer.
6155 // This will give the application more chance to read from the buffer and
6156 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006157 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006158 }
6159 }
Eric Laurentec437d82011-07-26 20:54:46 -07006160 // enable changes in effect chain
6161 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006162 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006163 }
6164
Glenn Kastene4e2a372012-07-23 12:55:09 -07006165 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006166
Glenn Kasten33e6e352012-07-16 15:56:57 -07006167 {
6168 Mutex::Autolock _l(mLock);
6169 mActiveTrack.clear();
6170 mStartStopCond.broadcast();
6171 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006172
Eric Laurentfeb0db62011-07-22 09:04:31 -07006173 releaseWakeLock();
6174
Steve Block3856b092011-10-20 11:56:00 +01006175 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006176 return false;
6177}
6178
Glenn Kastene4e2a372012-07-23 12:55:09 -07006179void AudioFlinger::RecordThread::standby()
6180{
6181 if (!mStandby) {
6182 inputStandBy();
6183 mStandby = true;
6184 }
6185}
6186
6187void AudioFlinger::RecordThread::inputStandBy()
6188{
6189 mInput->stream->common.standby(&mInput->stream->common);
6190}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006191
6192sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6193 const sp<AudioFlinger::Client>& client,
6194 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006195 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006196 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006197 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006198 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006199 IAudioFlinger::track_flags_t flags,
6200 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006201 status_t *status)
6202{
6203 sp<RecordTrack> track;
6204 status_t lStatus;
6205
6206 lStatus = initCheck();
6207 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006208 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006209 goto Exit;
6210 }
6211
Glenn Kasten1879fff2012-07-11 15:36:59 -07006212 // FIXME use flags and tid similar to createTrack_l()
6213
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006214 { // scope for mLock
6215 Mutex::Autolock _l(mLock);
6216
6217 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006218 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006219
Glenn Kasten7378ca52012-01-20 13:44:40 -08006220 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006221 lStatus = NO_MEMORY;
6222 goto Exit;
6223 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006224 mTracks.add(track);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006225
Eric Laurent59bd0da2011-08-01 09:52:20 -07006226 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1c04f92012-08-28 14:26:53 -07006227 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006228 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006229 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6230 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006231 }
6232 lStatus = NO_ERROR;
6233
6234Exit:
6235 if (status) {
6236 *status = lStatus;
6237 }
6238 return track;
6239}
6240
Eric Laurenta011e352012-03-29 15:51:43 -07006241status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006242 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006243 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006244{
Glenn Kasten58912562012-04-03 10:45:00 -07006245 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006246 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006247 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006248
6249 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006250 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006251 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6252 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6253 triggerSession,
6254 recordTrack->sessionId(),
6255 syncStartEventCallback,
6256 this);
Eric Laurent29864602012-05-08 18:57:51 -07006257 // Sync event can be cancelled by the trigger session if the track is not in a
6258 // compatible state in which case we start record immediately
6259 if (mSyncStartEvent->isCancelled()) {
6260 clearSyncStartEvent();
6261 } else {
6262 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6263 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6264 }
Eric Laurenta011e352012-03-29 15:51:43 -07006265 }
6266
Mathias Agopian65ab4712010-07-14 17:59:35 -07006267 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006268 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006269 if (mActiveTrack != 0) {
6270 if (recordTrack != mActiveTrack.get()) {
6271 status = -EBUSY;
6272 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6273 mActiveTrack->mState = TrackBase::ACTIVE;
6274 }
6275 return status;
6276 }
6277
6278 recordTrack->mState = TrackBase::IDLE;
6279 mActiveTrack = recordTrack;
6280 mLock.unlock();
6281 status_t status = AudioSystem::startInput(mId);
6282 mLock.lock();
6283 if (status != NO_ERROR) {
6284 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006285 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006286 return status;
6287 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006288 mRsmpInIndex = mFrameCount;
6289 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006290 if (mResampler != NULL) {
6291 mResampler->reset();
6292 }
6293 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006294 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006295 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006296 mWaitWorkCV.signal();
6297 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006298 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006299 mActiveTrack.clear();
6300 status = INVALID_OPERATION;
6301 goto startError;
6302 }
6303 mStartStopCond.wait(mLock);
6304 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006305 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006306 status = BAD_VALUE;
6307 goto startError;
6308 }
Steve Block3856b092011-10-20 11:56:00 +01006309 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006310 return status;
6311 }
6312startError:
6313 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006314 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006315 return status;
6316}
6317
Eric Laurenta011e352012-03-29 15:51:43 -07006318void AudioFlinger::RecordThread::clearSyncStartEvent()
6319{
6320 if (mSyncStartEvent != 0) {
6321 mSyncStartEvent->cancel();
6322 }
6323 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006324 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006325}
6326
6327void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6328{
6329 sp<SyncEvent> strongEvent = event.promote();
6330
6331 if (strongEvent != 0) {
6332 RecordThread *me = (RecordThread *)strongEvent->cookie();
6333 me->handleSyncStartEvent(strongEvent);
6334 }
6335}
6336
6337void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6338{
Eric Laurent29864602012-05-08 18:57:51 -07006339 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006340 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6341 // from audio HAL
6342 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006343 }
6344}
6345
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006346bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006347 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006348 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
6349 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006350 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006351 recordTrack->mState = TrackBase::PAUSING;
6352 // do not wait for mStartStopCond if exiting
6353 if (exitPending()) {
6354 return true;
6355 }
6356 mStartStopCond.wait(mLock);
6357 // if we have been restarted, recordTrack == mActiveTrack.get() here
6358 if (exitPending() || recordTrack != mActiveTrack.get()) {
6359 ALOGV("Record stopped OK");
6360 return true;
6361 }
6362 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006363}
6364
Glenn Kasten106e8a42012-08-02 13:37:12 -07006365bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07006366{
6367 return false;
6368}
6369
6370status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6371{
Glenn Kasten7aa25592012-08-02 16:37:07 -07006372#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
Eric Laurenta011e352012-03-29 15:51:43 -07006373 if (!isValidSyncEvent(event)) {
6374 return BAD_VALUE;
6375 }
6376
Glenn Kasten510a3d62012-07-16 14:24:34 -07006377 int eventSession = event->triggerSession();
6378 status_t ret = NAME_NOT_FOUND;
6379
Eric Laurenta011e352012-03-29 15:51:43 -07006380 Mutex::Autolock _l(mLock);
6381
Glenn Kasten510a3d62012-07-16 14:24:34 -07006382 for (size_t i = 0; i < mTracks.size(); i++) {
6383 sp<RecordTrack> track = mTracks[i];
6384 if (eventSession == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07006385 (void) track->setSyncEvent(event);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006386 ret = NO_ERROR;
6387 }
Eric Laurenta011e352012-03-29 15:51:43 -07006388 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006389 return ret;
Glenn Kasten7aa25592012-08-02 16:37:07 -07006390#else
6391 return BAD_VALUE;
6392#endif
Glenn Kasten510a3d62012-07-16 14:24:34 -07006393}
6394
6395void AudioFlinger::RecordThread::RecordTrack::destroy()
6396{
6397 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
6398 sp<RecordTrack> keep(this);
6399 {
6400 sp<ThreadBase> thread = mThread.promote();
6401 if (thread != 0) {
6402 if (mState == ACTIVE || mState == RESUMING) {
6403 AudioSystem::stopInput(thread->id());
6404 }
6405 AudioSystem::releaseInput(thread->id());
6406 Mutex::Autolock _l(thread->mLock);
6407 RecordThread *recordThread = (RecordThread *) thread.get();
6408 recordThread->destroyTrack_l(this);
6409 }
6410 }
6411}
6412
6413// destroyTrack_l() must be called with ThreadBase::mLock held
6414void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6415{
6416 track->mState = TrackBase::TERMINATED;
6417 // active tracks are removed by threadLoop()
6418 if (mActiveTrack != track) {
6419 removeTrack_l(track);
6420 }
6421}
6422
6423void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6424{
6425 mTracks.remove(track);
6426 // need anything related to effects here?
Eric Laurenta011e352012-03-29 15:51:43 -07006427}
6428
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07006429void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006430{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006431 dumpInternals(fd, args);
6432 dumpTracks(fd, args);
6433 dumpEffectChains(fd, args);
6434}
6435
6436void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6437{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006438 const size_t SIZE = 256;
6439 char buffer[SIZE];
6440 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006441
6442 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6443 result.append(buffer);
6444
6445 if (mActiveTrack != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006446 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6447 result.append(buffer);
6448 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6449 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006450 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006451 result.append(buffer);
6452 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6453 result.append(buffer);
6454 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6455 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006456 } else {
Glenn Kasten510a3d62012-07-16 14:24:34 -07006457 result.append("No active record client\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006458 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006459
Mathias Agopian65ab4712010-07-14 17:59:35 -07006460 write(fd, result.string(), result.size());
6461
6462 dumpBase(fd, args);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006463}
6464
6465void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
6466{
6467 const size_t SIZE = 256;
6468 char buffer[SIZE];
6469 String8 result;
6470
6471 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
6472 result.append(buffer);
6473 RecordTrack::appendDumpHeader(result);
6474 for (size_t i = 0; i < mTracks.size(); ++i) {
6475 sp<RecordTrack> track = mTracks[i];
6476 if (track != 0) {
6477 track->dump(buffer, SIZE);
6478 result.append(buffer);
6479 }
6480 }
6481
6482 if (mActiveTrack != 0) {
6483 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
6484 result.append(buffer);
6485 RecordTrack::appendDumpHeader(result);
6486 mActiveTrack->dump(buffer, SIZE);
6487 result.append(buffer);
6488
6489 }
6490 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006491}
6492
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006493// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006494status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006495{
6496 size_t framesReq = buffer->frameCount;
6497 size_t framesReady = mFrameCount - mRsmpInIndex;
6498 int channelCount;
6499
6500 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006501 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006502 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006503 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006504 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6505 // Force input into standby so that it tries to
6506 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006507 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006508 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006509 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006510 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006511 buffer->frameCount = 0;
6512 return NOT_ENOUGH_DATA;
6513 }
6514 mRsmpInIndex = 0;
6515 framesReady = mFrameCount;
6516 }
6517
6518 if (framesReq > framesReady) {
6519 framesReq = framesReady;
6520 }
6521
6522 if (mChannelCount == 1 && mReqChannelCount == 2) {
6523 channelCount = 1;
6524 } else {
6525 channelCount = 2;
6526 }
6527 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6528 buffer->frameCount = framesReq;
6529 return NO_ERROR;
6530}
6531
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006532// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006533void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6534{
6535 mRsmpInIndex += buffer->frameCount;
6536 buffer->frameCount = 0;
6537}
6538
6539bool AudioFlinger::RecordThread::checkForNewParameters_l()
6540{
6541 bool reconfig = false;
6542
6543 while (!mNewParameters.isEmpty()) {
6544 status_t status = NO_ERROR;
6545 String8 keyValuePair = mNewParameters[0];
6546 AudioParameter param = AudioParameter(keyValuePair);
6547 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006548 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006549 int reqSamplingRate = mReqSampleRate;
6550 int reqChannelCount = mReqChannelCount;
6551
6552 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6553 reqSamplingRate = value;
6554 reconfig = true;
6555 }
6556 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006557 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006558 reconfig = true;
6559 }
6560 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006561 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006562 reconfig = true;
6563 }
6564 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6565 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006566 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006567 // if frame count is changed after track creation
6568 if (mActiveTrack != 0) {
6569 status = INVALID_OPERATION;
6570 } else {
6571 reconfig = true;
6572 }
6573 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006574 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6575 // forward device change to effects that have requested to be
6576 // aware of attached audio device.
6577 for (size_t i = 0; i < mEffectChains.size(); i++) {
6578 mEffectChains[i]->setDevice_l(value);
6579 }
Eric Laurentf1c04f92012-08-28 14:26:53 -07006580
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006581 // store input device and output device but do not forward output device to audio HAL.
6582 // Note that status is ignored by the caller for output device
6583 // (see AudioFlinger::setParameters()
Eric Laurentf1c04f92012-08-28 14:26:53 -07006584 if (audio_is_output_devices(value)) {
6585 mOutDevice = value;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006586 status = BAD_VALUE;
6587 } else {
Eric Laurentf1c04f92012-08-28 14:26:53 -07006588 mInDevice = value;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006589 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kasten510a3d62012-07-16 14:24:34 -07006590 if (mTracks.size() > 0) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07006591 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6592 mAudioFlinger->btNrecIsOff();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006593 for (size_t i = 0; i < mTracks.size(); i++) {
6594 sp<RecordTrack> track = mTracks[i];
6595 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6596 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6597 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07006598 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006599 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006600 }
Eric Laurent57b2dd12012-08-31 17:44:06 -07006601 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6602 mAudioSource != (audio_source_t)value) {
6603 // forward device change to effects that have requested to be
6604 // aware of attached audio device.
6605 for (size_t i = 0; i < mEffectChains.size(); i++) {
6606 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
6607 }
6608 mAudioSource = (audio_source_t)value;
6609 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006610 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006611 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006612 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006613 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006614 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6615 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006616 }
6617 if (reconfig) {
6618 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006619 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006620 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006621 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006622 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6623 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006624 status = NO_ERROR;
6625 }
6626 if (status == NO_ERROR) {
6627 readInputParameters();
6628 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6629 }
6630 }
6631 }
6632
6633 mNewParameters.removeAt(0);
6634
6635 mParamStatus = status;
6636 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006637 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6638 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006639 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006640 }
6641 return reconfig;
6642}
6643
6644String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6645{
Dima Zavinfce7a472011-04-19 22:30:36 -07006646 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006647 String8 out_s8 = String8();
6648
6649 Mutex::Autolock _l(mLock);
6650 if (initCheck() != NO_ERROR) {
6651 return out_s8;
6652 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006653
Dima Zavin799a70e2011-04-18 16:57:27 -07006654 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006655 out_s8 = String8(s);
6656 free(s);
6657 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006658}
6659
6660void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6661 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006662 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006663
6664 switch (event) {
6665 case AudioSystem::INPUT_OPENED:
6666 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006667 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006668 desc.samplingRate = mSampleRate;
6669 desc.format = mFormat;
6670 desc.frameCount = mFrameCount;
6671 desc.latency = 0;
6672 param2 = &desc;
6673 break;
6674
6675 case AudioSystem::INPUT_CLOSED:
6676 default:
6677 break;
6678 }
6679 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6680}
6681
6682void AudioFlinger::RecordThread::readInputParameters()
6683{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006684 delete mRsmpInBuffer;
6685 // mRsmpInBuffer is always assigned a new[] below
6686 delete mRsmpOutBuffer;
6687 mRsmpOutBuffer = NULL;
6688 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006689 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006690
Dima Zavin799a70e2011-04-18 16:57:27 -07006691 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006692 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6693 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006694 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006695 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006696 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006697 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006698 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006699 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6700
Glenn Kasten53d76db2012-03-08 12:32:47 -08006701 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006702 {
6703 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006704 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6705 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006706 if (mChannelCount == 1 && mReqChannelCount == 2) {
6707 channelCount = 1;
6708 } else {
6709 channelCount = 2;
6710 }
6711 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6712 mResampler->setSampleRate(mSampleRate);
6713 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6714 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6715
6716 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6717 if (mChannelCount == 1 && mReqChannelCount == 1) {
6718 mFrameCount >>= 1;
6719 }
6720
6721 }
6722 mRsmpInIndex = mFrameCount;
6723}
6724
6725unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6726{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006727 Mutex::Autolock _l(mLock);
6728 if (initCheck() != NO_ERROR) {
6729 return 0;
6730 }
6731
Dima Zavin799a70e2011-04-18 16:57:27 -07006732 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006733}
6734
Glenn Kasten106e8a42012-08-02 13:37:12 -07006735uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006736{
6737 Mutex::Autolock _l(mLock);
6738 uint32_t result = 0;
6739 if (getEffectChain_l(sessionId) != 0) {
6740 result = EFFECT_SESSION;
6741 }
6742
Glenn Kasten510a3d62012-07-16 14:24:34 -07006743 for (size_t i = 0; i < mTracks.size(); ++i) {
6744 if (sessionId == mTracks[i]->sessionId()) {
6745 result |= TRACK_SESSION;
6746 break;
6747 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006748 }
6749
6750 return result;
6751}
6752
Glenn Kasten106e8a42012-08-02 13:37:12 -07006753KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent59bd0da2011-08-01 09:52:20 -07006754{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006755 KeyedVector<int, bool> ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006756 Mutex::Autolock _l(mLock);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006757 for (size_t j = 0; j < mTracks.size(); ++j) {
6758 sp<RecordThread::RecordTrack> track = mTracks[j];
6759 int sessionId = track->sessionId();
6760 if (ids.indexOfKey(sessionId) < 0) {
6761 ids.add(sessionId, true);
6762 }
6763 }
6764 return ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006765}
6766
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006767AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6768{
6769 Mutex::Autolock _l(mLock);
6770 AudioStreamIn *input = mInput;
6771 mInput = NULL;
6772 return input;
6773}
6774
6775// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006776audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006777{
6778 if (mInput == NULL) {
6779 return NULL;
6780 }
6781 return &mInput->stream->common;
6782}
6783
6784
Mathias Agopian65ab4712010-07-14 17:59:35 -07006785// ----------------------------------------------------------------------------
6786
Eric Laurenta4c5a552012-03-29 10:12:40 -07006787audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6788{
6789 if (!settingsAllowed()) {
6790 return 0;
6791 }
6792 Mutex::Autolock _l(mLock);
6793 return loadHwModule_l(name);
6794}
6795
6796// loadHwModule_l() must be called with AudioFlinger::mLock held
6797audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6798{
6799 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6800 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6801 ALOGW("loadHwModule() module %s already loaded", name);
6802 return mAudioHwDevs.keyAt(i);
6803 }
6804 }
6805
Eric Laurenta4c5a552012-03-29 10:12:40 -07006806 audio_hw_device_t *dev;
6807
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006808 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006809 if (rc) {
6810 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6811 return 0;
6812 }
6813
6814 mHardwareStatus = AUDIO_HW_INIT;
6815 rc = dev->init_check(dev);
6816 mHardwareStatus = AUDIO_HW_IDLE;
6817 if (rc) {
6818 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6819 return 0;
6820 }
6821
John Grossmanee578c02012-07-23 17:05:46 -07006822 // Check and cache this HAL's level of support for master mute and master
6823 // volume. If this is the first HAL opened, and it supports the get
6824 // methods, use the initial values provided by the HAL as the current
6825 // master mute and volume settings.
6826
6827 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
6828 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07006829 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07006830
6831 if (0 == mAudioHwDevs.size()) {
6832 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6833 if (NULL != dev->get_master_volume) {
6834 float mv;
6835 if (OK == dev->get_master_volume(dev, &mv)) {
6836 mMasterVolume = mv;
6837 }
6838 }
6839
6840 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
6841 if (NULL != dev->get_master_mute) {
6842 bool mm;
6843 if (OK == dev->get_master_mute(dev, &mm)) {
6844 mMasterMute = mm;
6845 }
6846 }
6847 }
6848
Eric Laurenta4c5a552012-03-29 10:12:40 -07006849 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07006850 if ((NULL != dev->set_master_volume) &&
6851 (OK == dev->set_master_volume(dev, mMasterVolume))) {
6852 flags = static_cast<AudioHwDevice::Flags>(flags |
6853 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
6854 }
6855
6856 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
6857 if ((NULL != dev->set_master_mute) &&
6858 (OK == dev->set_master_mute(dev, mMasterMute))) {
6859 flags = static_cast<AudioHwDevice::Flags>(flags |
6860 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
6861 }
6862
Eric Laurenta4c5a552012-03-29 10:12:40 -07006863 mHardwareStatus = AUDIO_HW_IDLE;
6864 }
6865
6866 audio_module_handle_t handle = nextUniqueId();
John Grossmanee578c02012-07-23 17:05:46 -07006867 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07006868
6869 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006870 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006871
6872 return handle;
6873
6874}
6875
6876audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6877 audio_devices_t *pDevices,
6878 uint32_t *pSamplingRate,
6879 audio_format_t *pFormat,
6880 audio_channel_mask_t *pChannelMask,
6881 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006882 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006883{
6884 status_t status;
6885 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006886 struct audio_config config = {
6887 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6888 channel_mask: pChannelMask ? *pChannelMask : 0,
6889 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6890 };
6891 audio_stream_out_t *outStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07006892 AudioHwDevice *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006893
Eric Laurenta4c5a552012-03-29 10:12:40 -07006894 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6895 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006896 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006897 config.sample_rate,
6898 config.format,
6899 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006900 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006901
6902 if (pDevices == NULL || *pDevices == 0) {
6903 return 0;
6904 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006905
Mathias Agopian65ab4712010-07-14 17:59:35 -07006906 Mutex::Autolock _l(mLock);
6907
Eric Laurenta4c5a552012-03-29 10:12:40 -07006908 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006909 if (outHwDev == NULL)
6910 return 0;
6911
John Grossmanee578c02012-07-23 17:05:46 -07006912 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006913 audio_io_handle_t id = nextUniqueId();
6914
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006915 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006916
John Grossmanee578c02012-07-23 17:05:46 -07006917 status = hwDevHal->open_output_stream(hwDevHal,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006918 id,
6919 *pDevices,
6920 (audio_output_flags_t)flags,
6921 &config,
6922 &outStream);
6923
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006924 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006925 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006926 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006927 config.sample_rate,
6928 config.format,
6929 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006930 status);
6931
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006932 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006933 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006934
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006935 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006936 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6937 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006938 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006939 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006940 } else {
6941 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006942 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006943 }
6944 mPlaybackThreads.add(id, thread);
6945
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006946 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6947 if (pFormat != NULL) *pFormat = config.format;
6948 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006949 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006950
6951 // notify client processes of the new output creation
6952 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006953
6954 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006955 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006956 ALOGI("Using module %d has the primary audio interface", module);
6957 mPrimaryHardwareDev = outHwDev;
6958
6959 AutoMutex lock(mHardwareLock);
6960 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -07006961 hwDevHal->set_mode(hwDevHal, mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006962 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006963 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006964 return id;
6965 }
6966
6967 return 0;
6968}
6969
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006970audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6971 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006972{
6973 Mutex::Autolock _l(mLock);
6974 MixerThread *thread1 = checkMixerThread_l(output1);
6975 MixerThread *thread2 = checkMixerThread_l(output2);
6976
6977 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006978 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006979 return 0;
6980 }
6981
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006982 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006983 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6984 thread->addOutputTrack(thread2);
6985 mPlaybackThreads.add(id, thread);
6986 // notify client processes of the new output creation
6987 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6988 return id;
6989}
6990
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006991status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006992{
Glenn Kastend96c5722012-04-25 13:44:49 -07006993 return closeOutput_nonvirtual(output);
6994}
6995
6996status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
6997{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006998 // keep strong reference on the playback thread so that
6999 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007000 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007001 {
7002 Mutex::Autolock _l(mLock);
7003 thread = checkPlaybackThread_l(output);
7004 if (thread == NULL) {
7005 return BAD_VALUE;
7006 }
7007
Steve Block3856b092011-10-20 11:56:00 +01007008 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007009
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007010 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007011 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007012 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007013 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
7014 dupThread->removeOutputTrack((MixerThread *)thread.get());
7015 }
7016 }
7017 }
Glenn Kastena1117922012-01-26 10:53:32 -08007018 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007019 mPlaybackThreads.removeItem(output);
7020 }
7021 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007022 // The thread entity (active unit of execution) is no longer running here,
7023 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007024
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007025 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007026 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007027 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007028 // from now on thread->mOutput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007029 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007030 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007031 }
7032 return NO_ERROR;
7033}
7034
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007035status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007036{
7037 Mutex::Autolock _l(mLock);
7038 PlaybackThread *thread = checkPlaybackThread_l(output);
7039
7040 if (thread == NULL) {
7041 return BAD_VALUE;
7042 }
7043
Steve Block3856b092011-10-20 11:56:00 +01007044 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007045 thread->suspend();
7046
7047 return NO_ERROR;
7048}
7049
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007050status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007051{
7052 Mutex::Autolock _l(mLock);
7053 PlaybackThread *thread = checkPlaybackThread_l(output);
7054
7055 if (thread == NULL) {
7056 return BAD_VALUE;
7057 }
7058
Steve Block3856b092011-10-20 11:56:00 +01007059 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007060
7061 thread->restore();
7062
7063 return NO_ERROR;
7064}
7065
Eric Laurenta4c5a552012-03-29 10:12:40 -07007066audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
7067 audio_devices_t *pDevices,
7068 uint32_t *pSamplingRate,
7069 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07007070 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007071{
7072 status_t status;
7073 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007074 struct audio_config config = {
7075 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7076 channel_mask: pChannelMask ? *pChannelMask : 0,
7077 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7078 };
7079 uint32_t reqSamplingRate = config.sample_rate;
7080 audio_format_t reqFormat = config.format;
7081 audio_channel_mask_t reqChannels = config.channel_mask;
7082 audio_stream_in_t *inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007083 AudioHwDevice *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007084
7085 if (pDevices == NULL || *pDevices == 0) {
7086 return 0;
7087 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007088
Mathias Agopian65ab4712010-07-14 17:59:35 -07007089 Mutex::Autolock _l(mLock);
7090
Eric Laurenta4c5a552012-03-29 10:12:40 -07007091 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007092 if (inHwDev == NULL)
7093 return 0;
7094
John Grossmanee578c02012-07-23 17:05:46 -07007095 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007096 audio_io_handle_t id = nextUniqueId();
7097
John Grossmanee578c02012-07-23 17:05:46 -07007098 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007099 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007100 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007101 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007102 config.sample_rate,
7103 config.format,
7104 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007105 status);
7106
7107 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7108 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7109 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007110 if (status == BAD_VALUE &&
7111 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7112 (config.sample_rate <= 2 * reqSamplingRate) &&
7113 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007114 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007115 inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007116 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007117 }
7118
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007119 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007120 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7121
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007122 // Start record thread
7123 // RecorThread require both input and output device indication to forward to audio
7124 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007125 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007126 thread = new RecordThread(this,
7127 input,
7128 reqSamplingRate,
7129 reqChannels,
7130 id,
7131 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007132 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007133 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007134 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007135 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007136 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007137
Mathias Agopian65ab4712010-07-14 17:59:35 -07007138 // notify client processes of the new input creation
7139 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7140 return id;
7141 }
7142
7143 return 0;
7144}
7145
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007146status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007147{
Glenn Kastend96c5722012-04-25 13:44:49 -07007148 return closeInput_nonvirtual(input);
7149}
7150
7151status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7152{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007153 // keep strong reference on the record thread so that
7154 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007155 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007156 {
7157 Mutex::Autolock _l(mLock);
7158 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007159 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007160 return BAD_VALUE;
7161 }
7162
Steve Block3856b092011-10-20 11:56:00 +01007163 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007164 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007165 mRecordThreads.removeItem(input);
7166 }
7167 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007168 // The thread entity (active unit of execution) is no longer running here,
7169 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007170
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007171 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007172 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007173 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007174 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007175 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007176
7177 return NO_ERROR;
7178}
7179
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007180status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007181{
7182 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007183 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007184
7185 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7186 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007187 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007188 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007189
7190 return NO_ERROR;
7191}
7192
7193
7194int AudioFlinger::newAudioSessionId()
7195{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007196 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007197}
7198
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007199void AudioFlinger::acquireAudioSessionId(int audioSession)
7200{
7201 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007202 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007203 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007204 size_t num = mAudioSessionRefs.size();
7205 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007206 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007207 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7208 ref->mCnt++;
7209 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007210 return;
7211 }
7212 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007213 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7214 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007215}
7216
7217void AudioFlinger::releaseAudioSessionId(int audioSession)
7218{
7219 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007220 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007221 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007222 size_t num = mAudioSessionRefs.size();
7223 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007224 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007225 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7226 ref->mCnt--;
7227 ALOGV(" decremented refcount to %d", ref->mCnt);
7228 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007229 mAudioSessionRefs.removeAt(i);
7230 delete ref;
7231 purgeStaleEffects_l();
7232 }
7233 return;
7234 }
7235 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007236 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007237}
7238
7239void AudioFlinger::purgeStaleEffects_l() {
7240
Steve Block3856b092011-10-20 11:56:00 +01007241 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007242
7243 Vector< sp<EffectChain> > chains;
7244
7245 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7246 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7247 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7248 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007249 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7250 chains.push(ec);
7251 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007252 }
7253 }
7254 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7255 sp<RecordThread> t = mRecordThreads.valueAt(i);
7256 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7257 sp<EffectChain> ec = t->mEffectChains[j];
7258 chains.push(ec);
7259 }
7260 }
7261
7262 for (size_t i = 0; i < chains.size(); i++) {
7263 sp<EffectChain> ec = chains[i];
7264 int sessionid = ec->sessionId();
7265 sp<ThreadBase> t = ec->mThread.promote();
7266 if (t == 0) {
7267 continue;
7268 }
7269 size_t numsessionrefs = mAudioSessionRefs.size();
7270 bool found = false;
7271 for (size_t k = 0; k < numsessionrefs; k++) {
7272 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007273 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007274 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007275 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007276 found = true;
7277 break;
7278 }
7279 }
7280 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007281 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007282 // remove all effects from the chain
7283 while (ec->mEffects.size()) {
7284 sp<EffectModule> effect = ec->mEffects[0];
7285 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007286 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007287 if (effect->purgeHandles()) {
7288 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007289 }
7290 AudioSystem::unregisterEffect(effect->id());
7291 }
7292 }
7293 }
7294 return;
7295}
7296
Mathias Agopian65ab4712010-07-14 17:59:35 -07007297// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007298AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007299{
Glenn Kastena1117922012-01-26 10:53:32 -08007300 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007301}
7302
7303// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007304AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007305{
7306 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007307 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007308}
7309
7310// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007311AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007312{
Glenn Kastena1117922012-01-26 10:53:32 -08007313 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007314}
7315
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007316uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007317{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007318 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007319}
7320
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007321AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007322{
7323 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7324 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007325 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07007326 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007327 return thread;
7328 }
7329 }
7330 return NULL;
7331}
7332
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007333audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007334{
7335 PlaybackThread *thread = primaryPlaybackThread_l();
7336
7337 if (thread == NULL) {
7338 return 0;
7339 }
7340
Eric Laurentf1c04f92012-08-28 14:26:53 -07007341 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007342}
7343
Eric Laurenta011e352012-03-29 15:51:43 -07007344sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7345 int triggerSession,
7346 int listenerSession,
7347 sync_event_callback_t callBack,
7348 void *cookie)
7349{
7350 Mutex::Autolock _l(mLock);
7351
7352 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7353 status_t playStatus = NAME_NOT_FOUND;
7354 status_t recStatus = NAME_NOT_FOUND;
7355 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7356 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7357 if (playStatus == NO_ERROR) {
7358 return event;
7359 }
7360 }
7361 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7362 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7363 if (recStatus == NO_ERROR) {
7364 return event;
7365 }
7366 }
7367 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7368 mPendingSyncEvents.add(event);
7369 } else {
7370 ALOGV("createSyncEvent() invalid event %d", event->type());
7371 event.clear();
7372 }
7373 return event;
7374}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007375
Mathias Agopian65ab4712010-07-14 17:59:35 -07007376// ----------------------------------------------------------------------------
7377// Effect management
7378// ----------------------------------------------------------------------------
7379
7380
Glenn Kastenf587ba52012-01-26 16:25:10 -08007381status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007382{
7383 Mutex::Autolock _l(mLock);
7384 return EffectQueryNumberEffects(numEffects);
7385}
7386
Glenn Kastenf587ba52012-01-26 16:25:10 -08007387status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007388{
7389 Mutex::Autolock _l(mLock);
7390 return EffectQueryEffect(index, descriptor);
7391}
7392
Glenn Kasten5e92a782012-01-30 07:40:52 -08007393status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007394 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007395{
7396 Mutex::Autolock _l(mLock);
7397 return EffectGetDescriptor(pUuid, descriptor);
7398}
7399
7400
Mathias Agopian65ab4712010-07-14 17:59:35 -07007401sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7402 effect_descriptor_t *pDesc,
7403 const sp<IEffectClient>& effectClient,
7404 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007405 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007406 int sessionId,
7407 status_t *status,
7408 int *id,
7409 int *enabled)
7410{
7411 status_t lStatus = NO_ERROR;
7412 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007413 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007414
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007415 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007416 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007417
7418 if (pDesc == NULL) {
7419 lStatus = BAD_VALUE;
7420 goto Exit;
7421 }
7422
Eric Laurent84e9a102010-09-23 16:10:16 -07007423 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007424 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007425 lStatus = PERMISSION_DENIED;
7426 goto Exit;
7427 }
7428
Dima Zavinfce7a472011-04-19 22:30:36 -07007429 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007430 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007431 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007432 lStatus = PERMISSION_DENIED;
7433 goto Exit;
7434 }
7435
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007436 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007437 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007438 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007439 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007440 lStatus = BAD_VALUE;
7441 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007442 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007443 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007444 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007445 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007446 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007447 }
7448 }
7449
Mathias Agopian65ab4712010-07-14 17:59:35 -07007450 {
7451 Mutex::Autolock _l(mLock);
7452
Mathias Agopian65ab4712010-07-14 17:59:35 -07007453
7454 if (!EffectIsNullUuid(&pDesc->uuid)) {
7455 // if uuid is specified, request effect descriptor
7456 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7457 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007458 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007459 goto Exit;
7460 }
7461 } else {
7462 // if uuid is not specified, look for an available implementation
7463 // of the required type in effect factory
7464 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007465 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007466 lStatus = BAD_VALUE;
7467 goto Exit;
7468 }
7469 uint32_t numEffects = 0;
7470 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007471 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007472 bool found = false;
7473
7474 lStatus = EffectQueryNumberEffects(&numEffects);
7475 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007476 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007477 goto Exit;
7478 }
7479 for (uint32_t i = 0; i < numEffects; i++) {
7480 lStatus = EffectQueryEffect(i, &desc);
7481 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007482 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007483 continue;
7484 }
7485 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7486 // If matching type found save effect descriptor. If the session is
7487 // 0 and the effect is not auxiliary, continue enumeration in case
7488 // an auxiliary version of this effect type is available
7489 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08007490 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07007491 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007492 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7493 break;
7494 }
7495 }
7496 }
7497 if (!found) {
7498 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007499 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007500 goto Exit;
7501 }
7502 // For same effect type, chose auxiliary version over insert version if
7503 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007504 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007505 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08007506 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007507 }
7508 }
7509
7510 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007511 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007512 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7513 lStatus = INVALID_OPERATION;
7514 goto Exit;
7515 }
7516
Eric Laurent59255e42011-07-27 19:49:51 -07007517 // check recording permission for visualizer
7518 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7519 !recordingAllowed()) {
7520 lStatus = PERMISSION_DENIED;
7521 goto Exit;
7522 }
7523
Mathias Agopian65ab4712010-07-14 17:59:35 -07007524 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08007525 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007526
7527 // If output is not specified try to find a matching audio session ID in one of the
7528 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007529 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7530 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007531 // Note: io is never 0 when creating an effect on an input
7532 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007533 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007534 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7535 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007536 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007537 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007538 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007539 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007540 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007541 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7542 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7543 io = mRecordThreads.keyAt(i);
7544 break;
7545 }
7546 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007547 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007548 // If no output thread contains the requested session ID, default to
7549 // first output. The effect chain will be moved to the correct output
7550 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007551 if (io == 0 && mPlaybackThreads.size()) {
7552 io = mPlaybackThreads.keyAt(0);
7553 }
Steve Block3856b092011-10-20 11:56:00 +01007554 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007555 }
7556 ThreadBase *thread = checkRecordThread_l(io);
7557 if (thread == NULL) {
7558 thread = checkPlaybackThread_l(io);
7559 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007560 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007561 lStatus = BAD_VALUE;
7562 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007563 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007564 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007565
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007566 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007567
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007568 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007569 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7570 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007571 if (handle != 0 && id != NULL) {
7572 *id = handle->id();
7573 }
7574 }
7575
7576Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007577 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007578 *status = lStatus;
7579 }
7580 return handle;
7581}
7582
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007583status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7584 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007585{
Steve Block3856b092011-10-20 11:56:00 +01007586 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007587 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007588 Mutex::Autolock _l(mLock);
7589 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007590 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007591 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007592 }
Eric Laurentde070132010-07-13 04:45:46 -07007593 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7594 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007595 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007596 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007597 }
Eric Laurentde070132010-07-13 04:45:46 -07007598 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7599 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007600 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007601 return BAD_VALUE;
7602 }
7603
7604 Mutex::Autolock _dl(dstThread->mLock);
7605 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007606 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007607
Mathias Agopian65ab4712010-07-14 17:59:35 -07007608 return NO_ERROR;
7609}
7610
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007611// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007612status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007613 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007614 AudioFlinger::PlaybackThread *dstThread,
7615 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007616{
Steve Block3856b092011-10-20 11:56:00 +01007617 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007618 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007619
Eric Laurent59255e42011-07-27 19:49:51 -07007620 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007621 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007622 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007623 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007624 return INVALID_OPERATION;
7625 }
7626
Eric Laurent39e94f82010-07-28 01:32:47 -07007627 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007628 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007629 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007630 // removed.
7631 srcThread->removeEffectChain_l(chain);
7632
7633 // transfer all effects one by one so that new effect chain is created on new thread with
7634 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007635 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007636 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007637 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007638 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7639 while (effect != 0) {
7640 srcThread->removeEffect_l(effect);
7641 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007642 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7643 if (effect->state() == EffectModule::ACTIVE ||
7644 effect->state() == EffectModule::STOPPING) {
7645 effect->start();
7646 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007647 // if the move request is not received from audio policy manager, the effect must be
7648 // re-registered with the new strategy and output
7649 if (dstChain == 0) {
7650 dstChain = effect->chain().promote();
7651 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007652 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007653 srcThread->addEffect_l(effect);
7654 return NO_INIT;
7655 }
7656 strategy = dstChain->strategy();
7657 }
7658 if (reRegister) {
7659 AudioSystem::unregisterEffect(effect->id());
7660 AudioSystem::registerEffect(&effect->desc(),
7661 dstOutput,
7662 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007663 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007664 effect->id());
7665 }
Eric Laurentde070132010-07-13 04:45:46 -07007666 effect = chain->getEffectFromId_l(0);
7667 }
7668
7669 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007670}
7671
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007672
Mathias Agopian65ab4712010-07-14 17:59:35 -07007673// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007674sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007675 const sp<AudioFlinger::Client>& client,
7676 const sp<IEffectClient>& effectClient,
7677 int32_t priority,
7678 int sessionId,
7679 effect_descriptor_t *desc,
7680 int *enabled,
7681 status_t *status
7682 )
7683{
7684 sp<EffectModule> effect;
7685 sp<EffectHandle> handle;
7686 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007687 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007688 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007689 bool effectCreated = false;
7690 bool effectRegistered = false;
7691
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007692 lStatus = initCheck();
7693 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007694 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007695 goto Exit;
7696 }
7697
7698 // Do not allow effects with session ID 0 on direct output or duplicating threads
7699 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007700 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007701 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007702 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007703 lStatus = BAD_VALUE;
7704 goto Exit;
7705 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007706 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007707 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007708 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007709 desc->name, desc->flags, mType);
7710 lStatus = BAD_VALUE;
7711 goto Exit;
7712 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007713
Steve Block3856b092011-10-20 11:56:00 +01007714 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007715
7716 { // scope for mLock
7717 Mutex::Autolock _l(mLock);
7718
7719 // check for existing effect chain with the requested audio session
7720 chain = getEffectChain_l(sessionId);
7721 if (chain == 0) {
7722 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007723 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007724 chain = new EffectChain(this, sessionId);
7725 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007726 chain->setStrategy(getStrategyForSession_l(sessionId));
7727 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007728 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007729 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007730 }
7731
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007732 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007733
7734 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007735 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007736 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007737 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007738 if (lStatus != NO_ERROR) {
7739 goto Exit;
7740 }
7741 effectRegistered = true;
7742 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007743 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007744 lStatus = effect->status();
7745 if (lStatus != NO_ERROR) {
7746 goto Exit;
7747 }
Eric Laurentcab11242010-07-15 12:50:15 -07007748 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007749 if (lStatus != NO_ERROR) {
7750 goto Exit;
7751 }
7752 effectCreated = true;
7753
Eric Laurentf1c04f92012-08-28 14:26:53 -07007754 effect->setDevice(mOutDevice);
7755 effect->setDevice(mInDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007756 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07007757 effect->setAudioSource(mAudioSource);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007758 }
7759 // create effect handle and connect it to effect module
7760 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007761 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007762 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007763 *enabled = (int)effect->isEnabled();
7764 }
7765 }
7766
7767Exit:
7768 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007769 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007770 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007771 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007772 }
7773 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007774 AudioSystem::unregisterEffect(effect->id());
7775 }
7776 if (chainCreated) {
7777 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007778 }
7779 handle.clear();
7780 }
7781
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007782 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007783 *status = lStatus;
7784 }
7785 return handle;
7786}
7787
Eric Laurent717e1282012-06-29 16:36:52 -07007788sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7789{
7790 Mutex::Autolock _l(mLock);
7791 return getEffect_l(sessionId, effectId);
7792}
7793
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007794sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7795{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007796 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007797 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007798}
7799
Eric Laurentde070132010-07-13 04:45:46 -07007800// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7801// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007802status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007803{
7804 // check for existing effect chain with the requested audio session
7805 int sessionId = effect->sessionId();
7806 sp<EffectChain> chain = getEffectChain_l(sessionId);
7807 bool chainCreated = false;
7808
7809 if (chain == 0) {
7810 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007811 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007812 chain = new EffectChain(this, sessionId);
7813 addEffectChain_l(chain);
7814 chain->setStrategy(getStrategyForSession_l(sessionId));
7815 chainCreated = true;
7816 }
Steve Block3856b092011-10-20 11:56:00 +01007817 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007818
7819 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007820 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007821 this, effect->desc().name, chain.get());
7822 return BAD_VALUE;
7823 }
7824
7825 status_t status = chain->addEffect_l(effect);
7826 if (status != NO_ERROR) {
7827 if (chainCreated) {
7828 removeEffectChain_l(chain);
7829 }
7830 return status;
7831 }
7832
Eric Laurentf1c04f92012-08-28 14:26:53 -07007833 effect->setDevice(mOutDevice);
7834 effect->setDevice(mInDevice);
Eric Laurentde070132010-07-13 04:45:46 -07007835 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07007836 effect->setAudioSource(mAudioSource);
Eric Laurentde070132010-07-13 04:45:46 -07007837 return NO_ERROR;
7838}
7839
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007840void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007841
Steve Block3856b092011-10-20 11:56:00 +01007842 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007843 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007844 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7845 detachAuxEffect_l(effect->id());
7846 }
7847
7848 sp<EffectChain> chain = effect->chain().promote();
7849 if (chain != 0) {
7850 // remove effect chain if removing last effect
7851 if (chain->removeEffect_l(effect) == 0) {
7852 removeEffectChain_l(chain);
7853 }
7854 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007855 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007856 }
7857}
7858
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007859void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007860 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007861{
7862 effectChains = mEffectChains;
7863 for (size_t i = 0; i < mEffectChains.size(); i++) {
7864 mEffectChains[i]->lock();
7865 }
7866}
7867
7868void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007869 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007870{
7871 for (size_t i = 0; i < effectChains.size(); i++) {
7872 effectChains[i]->unlock();
7873 }
7874}
7875
7876sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7877{
7878 Mutex::Autolock _l(mLock);
7879 return getEffectChain_l(sessionId);
7880}
7881
Glenn Kasten106e8a42012-08-02 13:37:12 -07007882sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007883{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007884 size_t size = mEffectChains.size();
7885 for (size_t i = 0; i < size; i++) {
7886 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007887 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007888 }
7889 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007890 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007891}
7892
Glenn Kastenf78aee72012-01-04 11:00:47 -08007893void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007894{
7895 Mutex::Autolock _l(mLock);
7896 size_t size = mEffectChains.size();
7897 for (size_t i = 0; i < size; i++) {
7898 mEffectChains[i]->setMode_l(mode);
7899 }
7900}
7901
7902void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007903 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007904 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007905
Mathias Agopian65ab4712010-07-14 17:59:35 -07007906 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007907 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007908 // delete the effect module if removing last handle on it
7909 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007910 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007911 removeEffect_l(effect);
7912 AudioSystem::unregisterEffect(effect->id());
7913 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007914 }
7915}
7916
7917status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7918{
7919 int session = chain->sessionId();
7920 int16_t *buffer = mMixBuffer;
7921 bool ownsBuffer = false;
7922
Steve Block3856b092011-10-20 11:56:00 +01007923 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007924 if (session > 0) {
7925 // Only one effect chain can be present in direct output thread and it uses
7926 // the mix buffer as input
7927 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007928 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007929 buffer = new int16_t[numSamples];
7930 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007931 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007932 ownsBuffer = true;
7933 }
7934
7935 // Attach all tracks with same session ID to this chain.
7936 for (size_t i = 0; i < mTracks.size(); ++i) {
7937 sp<Track> track = mTracks[i];
7938 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007939 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007940 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007941 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007942 }
7943 }
7944
7945 // indicate all active tracks in the chain
7946 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7947 sp<Track> track = mActiveTracks[i].promote();
7948 if (track == 0) continue;
7949 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007950 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007951 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007952 }
7953 }
7954 }
7955
7956 chain->setInBuffer(buffer, ownsBuffer);
7957 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007958 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007959 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007960 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7961 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007962 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007963 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7964 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007965 // Effect chain for other sessions are inserted at beginning of effect
7966 // chains list to be processed before output mix effects. Relative order between other
7967 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007968 size_t size = mEffectChains.size();
7969 size_t i = 0;
7970 for (i = 0; i < size; i++) {
7971 if (mEffectChains[i]->sessionId() < session) break;
7972 }
7973 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007974 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007975
7976 return NO_ERROR;
7977}
7978
7979size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7980{
7981 int session = chain->sessionId();
7982
Steve Block3856b092011-10-20 11:56:00 +01007983 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007984
7985 for (size_t i = 0; i < mEffectChains.size(); i++) {
7986 if (chain == mEffectChains[i]) {
7987 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007988 // detach all active tracks from the chain
7989 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7990 sp<Track> track = mActiveTracks[i].promote();
7991 if (track == 0) continue;
7992 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007993 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007994 chain.get(), session);
7995 chain->decActiveTrackCnt();
7996 }
7997 }
7998
Mathias Agopian65ab4712010-07-14 17:59:35 -07007999 // detach all tracks with same session ID from this chain
8000 for (size_t i = 0; i < mTracks.size(); ++i) {
8001 sp<Track> track = mTracks[i];
8002 if (session == track->sessionId()) {
8003 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008004 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008005 }
8006 }
Eric Laurentde070132010-07-13 04:45:46 -07008007 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008008 }
8009 }
8010 return mEffectChains.size();
8011}
8012
Eric Laurentde070132010-07-13 04:45:46 -07008013status_t AudioFlinger::PlaybackThread::attachAuxEffect(
8014 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008015{
8016 Mutex::Autolock _l(mLock);
8017 return attachAuxEffect_l(track, EffectId);
8018}
8019
Eric Laurentde070132010-07-13 04:45:46 -07008020status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
8021 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008022{
8023 status_t status = NO_ERROR;
8024
8025 if (EffectId == 0) {
8026 track->setAuxBuffer(0, NULL);
8027 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07008028 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
8029 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008030 if (effect != 0) {
8031 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8032 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
8033 } else {
8034 status = INVALID_OPERATION;
8035 }
8036 } else {
8037 status = BAD_VALUE;
8038 }
8039 }
8040 return status;
8041}
8042
8043void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
8044{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008045 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008046 sp<Track> track = mTracks[i];
8047 if (track->auxEffectId() == effectId) {
8048 attachAuxEffect_l(track, 0);
8049 }
8050 }
8051}
8052
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008053status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8054{
8055 // only one chain per input thread
8056 if (mEffectChains.size() != 0) {
8057 return INVALID_OPERATION;
8058 }
Steve Block3856b092011-10-20 11:56:00 +01008059 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008060
8061 chain->setInBuffer(NULL);
8062 chain->setOutBuffer(NULL);
8063
Eric Laurent59255e42011-07-27 19:49:51 -07008064 checkSuspendOnAddEffectChain_l(chain);
8065
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008066 mEffectChains.add(chain);
8067
8068 return NO_ERROR;
8069}
8070
8071size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8072{
Steve Block3856b092011-10-20 11:56:00 +01008073 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00008074 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008075 "removeEffectChain_l() %p invalid chain size %d on thread %p",
8076 chain.get(), mEffectChains.size(), this);
8077 if (mEffectChains.size() == 1) {
8078 mEffectChains.removeAt(0);
8079 }
8080 return 0;
8081}
8082
Mathias Agopian65ab4712010-07-14 17:59:35 -07008083// ----------------------------------------------------------------------------
8084// EffectModule implementation
8085// ----------------------------------------------------------------------------
8086
8087#undef LOG_TAG
8088#define LOG_TAG "AudioFlinger::EffectModule"
8089
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008090AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008091 const wp<AudioFlinger::EffectChain>& chain,
8092 effect_descriptor_t *desc,
8093 int id,
8094 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07008095 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
8096 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07008097 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07008098 // mConfig is set by configure() and not used before then
8099 mEffectInterface(NULL),
8100 mStatus(NO_INIT), mState(IDLE),
8101 // mMaxDisableWaitCnt is set by configure() and not used before then
8102 // mDisableWaitCnt is set by process() and updateState() and not used before then
8103 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008104{
Steve Block3856b092011-10-20 11:56:00 +01008105 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008106 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008107
8108 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008109 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008110
8111 if (mStatus != NO_ERROR) {
8112 return;
8113 }
8114 lStatus = init();
8115 if (lStatus < 0) {
8116 mStatus = lStatus;
8117 goto Error;
8118 }
8119
Steve Block3856b092011-10-20 11:56:00 +01008120 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008121 return;
8122Error:
8123 EffectRelease(mEffectInterface);
8124 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008125 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008126}
8127
8128AudioFlinger::EffectModule::~EffectModule()
8129{
Steve Block3856b092011-10-20 11:56:00 +01008130 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008131 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008132 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8133 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8134 sp<ThreadBase> thread = mThread.promote();
8135 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008136 audio_stream_t *stream = thread->stream();
8137 if (stream != NULL) {
8138 stream->remove_audio_effect(stream, mEffectInterface);
8139 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008140 }
8141 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008142 // release effect engine
8143 EffectRelease(mEffectInterface);
8144 }
8145}
8146
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008147status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008148{
8149 status_t status;
8150
8151 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008152 int priority = handle->priority();
8153 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008154 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008155 size_t i;
8156 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008157 EffectHandle *h = mHandles[i];
8158 if (h == NULL || h->destroyed_l()) continue;
8159 // first non destroyed handle is considered in control
8160 if (controlHandle == NULL)
8161 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008162 if (h->priority() <= priority) break;
8163 }
8164 // if inserted in first place, move effect control from previous owner to this handle
8165 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008166 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008167 if (controlHandle != NULL) {
8168 enabled = controlHandle->enabled();
8169 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008170 }
Eric Laurent59255e42011-07-27 19:49:51 -07008171 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008172 status = NO_ERROR;
8173 } else {
8174 status = ALREADY_EXISTS;
8175 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008176 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008177 mHandles.insertAt(handle, i);
8178 return status;
8179}
8180
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008181size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008182{
8183 Mutex::Autolock _l(mLock);
8184 size_t size = mHandles.size();
8185 size_t i;
8186 for (i = 0; i < size; i++) {
8187 if (mHandles[i] == handle) break;
8188 }
8189 if (i == size) {
8190 return size;
8191 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008192 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008193
Mathias Agopian65ab4712010-07-14 17:59:35 -07008194 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008195 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008196 if (i == 0) {
8197 EffectHandle *h = controlHandle_l();
8198 if (h != NULL) {
8199 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008200 }
8201 }
8202
Eric Laurentec437d82011-07-26 20:54:46 -07008203 // Prevent calls to process() and other functions on effect interface from now on.
8204 // The effect engine will be released by the destructor when the last strong reference on
8205 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008206 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008207 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008208 }
8209
Eric Laurente65c8912012-07-20 15:57:23 -07008210 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008211}
8212
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008213// must be called with EffectModule::mLock held
8214AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008215{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008216 // the first valid handle in the list has control over the module
8217 for (size_t i = 0; i < mHandles.size(); i++) {
8218 EffectHandle *h = mHandles[i];
8219 if (h != NULL && !h->destroyed_l()) {
8220 return h;
8221 }
8222 }
8223
8224 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008225}
8226
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008227size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008228{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008229 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008230 // keep a strong reference on this EffectModule to avoid calling the
8231 // destructor before we exit
8232 sp<EffectModule> keep(this);
8233 {
8234 sp<ThreadBase> thread = mThread.promote();
8235 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008236 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008237 }
8238 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008239 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008240}
8241
8242void AudioFlinger::EffectModule::updateState() {
8243 Mutex::Autolock _l(mLock);
8244
8245 switch (mState) {
8246 case RESTART:
8247 reset_l();
8248 // FALL THROUGH
8249
8250 case STARTING:
8251 // clear auxiliary effect input buffer for next accumulation
8252 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8253 memset(mConfig.inputCfg.buffer.raw,
8254 0,
8255 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8256 }
8257 start_l();
8258 mState = ACTIVE;
8259 break;
8260 case STOPPING:
8261 stop_l();
8262 mDisableWaitCnt = mMaxDisableWaitCnt;
8263 mState = STOPPED;
8264 break;
8265 case STOPPED:
8266 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8267 // turn off sequence.
8268 if (--mDisableWaitCnt == 0) {
8269 reset_l();
8270 mState = IDLE;
8271 }
8272 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008273 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008274 break;
8275 }
8276}
8277
8278void AudioFlinger::EffectModule::process()
8279{
8280 Mutex::Autolock _l(mLock);
8281
Eric Laurentec437d82011-07-26 20:54:46 -07008282 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008283 mConfig.inputCfg.buffer.raw == NULL ||
8284 mConfig.outputCfg.buffer.raw == NULL) {
8285 return;
8286 }
8287
Eric Laurent8f45bd72010-08-31 13:50:07 -07008288 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008289 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8290 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008291 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008292 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008293 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008294 }
8295
8296 // do the actual processing in the effect engine
8297 int ret = (*mEffectInterface)->process(mEffectInterface,
8298 &mConfig.inputCfg.buffer,
8299 &mConfig.outputCfg.buffer);
8300
8301 // force transition to IDLE state when engine is ready
8302 if (mState == STOPPED && ret == -ENODATA) {
8303 mDisableWaitCnt = 1;
8304 }
8305
8306 // clear auxiliary effect input buffer for next accumulation
8307 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008308 memset(mConfig.inputCfg.buffer.raw, 0,
8309 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008310 }
8311 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008312 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8313 // If an insert effect is idle and input buffer is different from output buffer,
8314 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008315 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008316 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008317 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8318 int16_t *in = mConfig.inputCfg.buffer.s16;
8319 int16_t *out = mConfig.outputCfg.buffer.s16;
8320 for (size_t i = 0; i < frameCnt; i++) {
8321 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008322 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008323 }
8324 }
8325}
8326
8327void AudioFlinger::EffectModule::reset_l()
8328{
8329 if (mEffectInterface == NULL) {
8330 return;
8331 }
8332 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8333}
8334
8335status_t AudioFlinger::EffectModule::configure()
8336{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008337 if (mEffectInterface == NULL) {
8338 return NO_INIT;
8339 }
8340
8341 sp<ThreadBase> thread = mThread.promote();
8342 if (thread == 0) {
8343 return DEAD_OBJECT;
8344 }
8345
8346 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07008347 audio_channel_mask_t channelMask = thread->channelMask();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008348
8349 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008350 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008351 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07008352 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008353 }
Glenn Kasten254af182012-07-03 14:59:05 -07008354 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07008355 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8356 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008357 mConfig.inputCfg.samplingRate = thread->sampleRate();
8358 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8359 mConfig.inputCfg.bufferProvider.cookie = NULL;
8360 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8361 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8362 mConfig.outputCfg.bufferProvider.cookie = NULL;
8363 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8364 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8365 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8366 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008367 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008368 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008369 // - in other sessions:
8370 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8371 // other effect: overwrites output buffer: input buffer == output buffer
8372 // Auxiliary effect:
8373 // accumulates in output buffer: input buffer != output buffer
8374 // Therefore: accumulate <=> input buffer != output buffer
8375 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8376 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8377 } else {
8378 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8379 }
8380 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8381 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8382 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8383 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8384
Steve Block3856b092011-10-20 11:56:00 +01008385 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008386 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8387
Mathias Agopian65ab4712010-07-14 17:59:35 -07008388 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008389 uint32_t size = sizeof(int);
8390 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008391 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008392 sizeof(effect_config_t),
8393 &mConfig,
8394 &size,
8395 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008396 if (status == 0) {
8397 status = cmdStatus;
8398 }
8399
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008400 if (status == 0 &&
8401 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8402 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8403 effect_param_t *p = (effect_param_t *)buf32;
8404
8405 p->psize = sizeof(uint32_t);
8406 p->vsize = sizeof(uint32_t);
8407 size = sizeof(int);
8408 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8409
8410 uint32_t latency = 0;
8411 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8412 if (pbt != NULL) {
8413 latency = pbt->latency_l();
8414 }
8415
8416 *((int32_t *)p->data + 1)= latency;
8417 (*mEffectInterface)->command(mEffectInterface,
8418 EFFECT_CMD_SET_PARAM,
8419 sizeof(effect_param_t) + 8,
8420 &buf32,
8421 &size,
8422 &cmdStatus);
8423 }
8424
Mathias Agopian65ab4712010-07-14 17:59:35 -07008425 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8426 (1000 * mConfig.outputCfg.buffer.frameCount);
8427
8428 return status;
8429}
8430
8431status_t AudioFlinger::EffectModule::init()
8432{
8433 Mutex::Autolock _l(mLock);
8434 if (mEffectInterface == NULL) {
8435 return NO_INIT;
8436 }
8437 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008438 uint32_t size = sizeof(status_t);
8439 status_t status = (*mEffectInterface)->command(mEffectInterface,
8440 EFFECT_CMD_INIT,
8441 0,
8442 NULL,
8443 &size,
8444 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008445 if (status == 0) {
8446 status = cmdStatus;
8447 }
8448 return status;
8449}
8450
Eric Laurentec35a142011-10-05 17:42:25 -07008451status_t AudioFlinger::EffectModule::start()
8452{
8453 Mutex::Autolock _l(mLock);
8454 return start_l();
8455}
8456
Mathias Agopian65ab4712010-07-14 17:59:35 -07008457status_t AudioFlinger::EffectModule::start_l()
8458{
8459 if (mEffectInterface == NULL) {
8460 return NO_INIT;
8461 }
8462 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008463 uint32_t size = sizeof(status_t);
8464 status_t status = (*mEffectInterface)->command(mEffectInterface,
8465 EFFECT_CMD_ENABLE,
8466 0,
8467 NULL,
8468 &size,
8469 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008470 if (status == 0) {
8471 status = cmdStatus;
8472 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008473 if (status == 0 &&
8474 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8475 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8476 sp<ThreadBase> thread = mThread.promote();
8477 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008478 audio_stream_t *stream = thread->stream();
8479 if (stream != NULL) {
8480 stream->add_audio_effect(stream, mEffectInterface);
8481 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008482 }
8483 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008484 return status;
8485}
8486
Eric Laurentec437d82011-07-26 20:54:46 -07008487status_t AudioFlinger::EffectModule::stop()
8488{
8489 Mutex::Autolock _l(mLock);
8490 return stop_l();
8491}
8492
Mathias Agopian65ab4712010-07-14 17:59:35 -07008493status_t AudioFlinger::EffectModule::stop_l()
8494{
8495 if (mEffectInterface == NULL) {
8496 return NO_INIT;
8497 }
8498 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008499 uint32_t size = sizeof(status_t);
8500 status_t status = (*mEffectInterface)->command(mEffectInterface,
8501 EFFECT_CMD_DISABLE,
8502 0,
8503 NULL,
8504 &size,
8505 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008506 if (status == 0) {
8507 status = cmdStatus;
8508 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008509 if (status == 0 &&
8510 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8511 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8512 sp<ThreadBase> thread = mThread.promote();
8513 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008514 audio_stream_t *stream = thread->stream();
8515 if (stream != NULL) {
8516 stream->remove_audio_effect(stream, mEffectInterface);
8517 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008518 }
8519 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008520 return status;
8521}
8522
Eric Laurent25f43952010-07-28 05:40:18 -07008523status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8524 uint32_t cmdSize,
8525 void *pCmdData,
8526 uint32_t *replySize,
8527 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008528{
8529 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008530// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008531
Eric Laurentec437d82011-07-26 20:54:46 -07008532 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008533 return NO_INIT;
8534 }
Eric Laurent25f43952010-07-28 05:40:18 -07008535 status_t status = (*mEffectInterface)->command(mEffectInterface,
8536 cmdCode,
8537 cmdSize,
8538 pCmdData,
8539 replySize,
8540 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008541 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008542 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008543 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008544 EffectHandle *h = mHandles[i];
8545 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008546 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8547 }
8548 }
8549 }
8550 return status;
8551}
8552
8553status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8554{
8555 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008556 return setEnabled_l(enabled);
8557}
8558
8559// must be called with EffectModule::mLock held
8560status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8561{
8562
Steve Block3856b092011-10-20 11:56:00 +01008563 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008564
8565 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008566 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8567 if (enabled && status != NO_ERROR) {
8568 return status;
8569 }
8570
Mathias Agopian65ab4712010-07-14 17:59:35 -07008571 switch (mState) {
8572 // going from disabled to enabled
8573 case IDLE:
8574 mState = STARTING;
8575 break;
8576 case STOPPED:
8577 mState = RESTART;
8578 break;
8579 case STOPPING:
8580 mState = ACTIVE;
8581 break;
8582
8583 // going from enabled to disabled
8584 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008585 mState = STOPPED;
8586 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008587 case STARTING:
8588 mState = IDLE;
8589 break;
8590 case ACTIVE:
8591 mState = STOPPING;
8592 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008593 case DESTROYED:
8594 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008595 }
8596 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008597 EffectHandle *h = mHandles[i];
8598 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008599 h->setEnabled(enabled);
8600 }
8601 }
8602 }
8603 return NO_ERROR;
8604}
8605
Glenn Kastenc59c0042012-02-02 14:06:11 -08008606bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008607{
8608 switch (mState) {
8609 case RESTART:
8610 case STARTING:
8611 case ACTIVE:
8612 return true;
8613 case IDLE:
8614 case STOPPING:
8615 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008616 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008617 default:
8618 return false;
8619 }
8620}
8621
Glenn Kastenc59c0042012-02-02 14:06:11 -08008622bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008623{
8624 switch (mState) {
8625 case RESTART:
8626 case ACTIVE:
8627 case STOPPING:
8628 case STOPPED:
8629 return true;
8630 case IDLE:
8631 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008632 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008633 default:
8634 return false;
8635 }
8636}
8637
Mathias Agopian65ab4712010-07-14 17:59:35 -07008638status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8639{
8640 Mutex::Autolock _l(mLock);
8641 status_t status = NO_ERROR;
8642
8643 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8644 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008645 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008646 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8647 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008648 status_t cmdStatus;
8649 uint32_t volume[2];
8650 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008651 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008652 volume[0] = *left;
8653 volume[1] = *right;
8654 if (controller) {
8655 pVolume = volume;
8656 }
Eric Laurent25f43952010-07-28 05:40:18 -07008657 status = (*mEffectInterface)->command(mEffectInterface,
8658 EFFECT_CMD_SET_VOLUME,
8659 size,
8660 volume,
8661 &size,
8662 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008663 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8664 *left = volume[0];
8665 *right = volume[1];
8666 }
8667 }
8668 return status;
8669}
8670
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008671status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008672{
Eric Laurentf1c04f92012-08-28 14:26:53 -07008673 if (device == AUDIO_DEVICE_NONE) {
8674 return NO_ERROR;
8675 }
8676
Mathias Agopian65ab4712010-07-14 17:59:35 -07008677 Mutex::Autolock _l(mLock);
8678 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008679 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07008680 status_t cmdStatus;
8681 uint32_t size = sizeof(status_t);
8682 uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE :
8683 EFFECT_CMD_SET_INPUT_DEVICE;
8684 status = (*mEffectInterface)->command(mEffectInterface,
8685 cmd,
8686 sizeof(uint32_t),
8687 &device,
8688 &size,
8689 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008690 }
8691 return status;
8692}
8693
Glenn Kastenf78aee72012-01-04 11:00:47 -08008694status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008695{
8696 Mutex::Autolock _l(mLock);
8697 status_t status = NO_ERROR;
8698 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008699 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008700 uint32_t size = sizeof(status_t);
8701 status = (*mEffectInterface)->command(mEffectInterface,
8702 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008703 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008704 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008705 &size,
8706 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008707 if (status == NO_ERROR) {
8708 status = cmdStatus;
8709 }
8710 }
8711 return status;
8712}
8713
Eric Laurent57b2dd12012-08-31 17:44:06 -07008714status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
8715{
8716 Mutex::Autolock _l(mLock);
8717 status_t status = NO_ERROR;
8718 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
8719 uint32_t size = 0;
8720 status = (*mEffectInterface)->command(mEffectInterface,
8721 EFFECT_CMD_SET_AUDIO_SOURCE,
8722 sizeof(audio_source_t),
8723 &source,
8724 &size,
8725 NULL);
8726 }
8727 return status;
8728}
8729
Eric Laurent59255e42011-07-27 19:49:51 -07008730void AudioFlinger::EffectModule::setSuspended(bool suspended)
8731{
8732 Mutex::Autolock _l(mLock);
8733 mSuspended = suspended;
8734}
Glenn Kastena3a85482012-01-04 11:01:11 -08008735
8736bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008737{
8738 Mutex::Autolock _l(mLock);
8739 return mSuspended;
8740}
8741
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008742bool AudioFlinger::EffectModule::purgeHandles()
8743{
8744 bool enabled = false;
8745 Mutex::Autolock _l(mLock);
8746 for (size_t i = 0; i < mHandles.size(); i++) {
8747 EffectHandle *handle = mHandles[i];
8748 if (handle != NULL && !handle->destroyed_l()) {
8749 handle->effect().clear();
8750 if (handle->hasControl()) {
8751 enabled = handle->enabled();
8752 }
8753 }
8754 }
8755 return enabled;
8756}
8757
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07008758void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008759{
8760 const size_t SIZE = 256;
8761 char buffer[SIZE];
8762 String8 result;
8763
8764 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8765 result.append(buffer);
8766
8767 bool locked = tryLock(mLock);
8768 // failed to lock - AudioFlinger is probably deadlocked
8769 if (!locked) {
8770 result.append("\t\tCould not lock Fx mutex:\n");
8771 }
8772
8773 result.append("\t\tSession Status State Engine:\n");
8774 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8775 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8776 result.append(buffer);
8777
8778 result.append("\t\tDescriptor:\n");
8779 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8780 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8781 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8782 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8783 result.append(buffer);
8784 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8785 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8786 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8787 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8788 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008789 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008790 mDescriptor.apiVersion,
8791 mDescriptor.flags);
8792 result.append(buffer);
8793 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8794 mDescriptor.name);
8795 result.append(buffer);
8796 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8797 mDescriptor.implementor);
8798 result.append(buffer);
8799
8800 result.append("\t\t- Input configuration:\n");
8801 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8802 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8803 (uint32_t)mConfig.inputCfg.buffer.raw,
8804 mConfig.inputCfg.buffer.frameCount,
8805 mConfig.inputCfg.samplingRate,
8806 mConfig.inputCfg.channels,
8807 mConfig.inputCfg.format);
8808 result.append(buffer);
8809
8810 result.append("\t\t- Output configuration:\n");
8811 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8812 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8813 (uint32_t)mConfig.outputCfg.buffer.raw,
8814 mConfig.outputCfg.buffer.frameCount,
8815 mConfig.outputCfg.samplingRate,
8816 mConfig.outputCfg.channels,
8817 mConfig.outputCfg.format);
8818 result.append(buffer);
8819
8820 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8821 result.append(buffer);
8822 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8823 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008824 EffectHandle *handle = mHandles[i];
8825 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008826 handle->dump(buffer, SIZE);
8827 result.append(buffer);
8828 }
8829 }
8830
8831 result.append("\n");
8832
8833 write(fd, result.string(), result.length());
8834
8835 if (locked) {
8836 mLock.unlock();
8837 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008838}
8839
8840// ----------------------------------------------------------------------------
8841// EffectHandle implementation
8842// ----------------------------------------------------------------------------
8843
8844#undef LOG_TAG
8845#define LOG_TAG "AudioFlinger::EffectHandle"
8846
8847AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8848 const sp<AudioFlinger::Client>& client,
8849 const sp<IEffectClient>& effectClient,
8850 int32_t priority)
8851 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008852 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008853 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008854{
Steve Block3856b092011-10-20 11:56:00 +01008855 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008856
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008857 if (client == 0) {
8858 return;
8859 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008860 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8861 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8862 if (mCblkMemory != 0) {
8863 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8864
Glenn Kastena0d68332012-01-27 16:47:15 -08008865 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008866 new(mCblk) effect_param_cblk_t();
8867 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008868 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008869 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008870 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008871 return;
8872 }
8873}
8874
8875AudioFlinger::EffectHandle::~EffectHandle()
8876{
Steve Block3856b092011-10-20 11:56:00 +01008877 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008878
8879 if (mEffect == 0) {
8880 mDestroyed = true;
8881 return;
8882 }
8883 mEffect->lock();
8884 mDestroyed = true;
8885 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008886 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008887}
8888
8889status_t AudioFlinger::EffectHandle::enable()
8890{
Steve Block3856b092011-10-20 11:56:00 +01008891 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008892 if (!mHasControl) return INVALID_OPERATION;
8893 if (mEffect == 0) return DEAD_OBJECT;
8894
Eric Laurentdb7c0792011-08-10 10:37:50 -07008895 if (mEnabled) {
8896 return NO_ERROR;
8897 }
8898
Eric Laurent59255e42011-07-27 19:49:51 -07008899 mEnabled = true;
8900
8901 sp<ThreadBase> thread = mEffect->thread().promote();
8902 if (thread != 0) {
8903 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8904 }
8905
8906 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8907 if (mEffect->suspended()) {
8908 return NO_ERROR;
8909 }
8910
Eric Laurentdb7c0792011-08-10 10:37:50 -07008911 status_t status = mEffect->setEnabled(true);
8912 if (status != NO_ERROR) {
8913 if (thread != 0) {
8914 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8915 }
8916 mEnabled = false;
8917 }
8918 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008919}
8920
8921status_t AudioFlinger::EffectHandle::disable()
8922{
Steve Block3856b092011-10-20 11:56:00 +01008923 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008924 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008925 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008926
Eric Laurentdb7c0792011-08-10 10:37:50 -07008927 if (!mEnabled) {
8928 return NO_ERROR;
8929 }
Eric Laurent59255e42011-07-27 19:49:51 -07008930 mEnabled = false;
8931
8932 if (mEffect->suspended()) {
8933 return NO_ERROR;
8934 }
8935
8936 status_t status = mEffect->setEnabled(false);
8937
8938 sp<ThreadBase> thread = mEffect->thread().promote();
8939 if (thread != 0) {
8940 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8941 }
8942
8943 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008944}
8945
8946void AudioFlinger::EffectHandle::disconnect()
8947{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008948 disconnect(true);
8949}
8950
Glenn Kasten58123c32012-02-03 10:32:24 -08008951void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008952{
Glenn Kasten58123c32012-02-03 10:32:24 -08008953 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008954 if (mEffect == 0) {
8955 return;
8956 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008957 // restore suspended effects if the disconnected handle was enabled and the last one.
8958 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008959 sp<ThreadBase> thread = mEffect->thread().promote();
8960 if (thread != 0) {
8961 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8962 }
Eric Laurent59255e42011-07-27 19:49:51 -07008963 }
8964
Mathias Agopian65ab4712010-07-14 17:59:35 -07008965 // release sp on module => module destructor can be called now
8966 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008967 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008968 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008969 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008970 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8971 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008972 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008973 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008974 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8975 mClient.clear();
8976 }
8977}
8978
Eric Laurent25f43952010-07-28 05:40:18 -07008979status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8980 uint32_t cmdSize,
8981 void *pCmdData,
8982 uint32_t *replySize,
8983 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008984{
Steve Block3856b092011-10-20 11:56:00 +01008985// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008986// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008987
8988 // only get parameter command is permitted for applications not controlling the effect
8989 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8990 return INVALID_OPERATION;
8991 }
8992 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008993 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008994
8995 // handle commands that are not forwarded transparently to effect engine
8996 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8997 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8998 // no risk to block the whole media server process or mixer threads is we are stuck here
8999 Mutex::Autolock _l(mCblk->lock);
9000 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
9001 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
9002 mCblk->serverIndex = 0;
9003 mCblk->clientIndex = 0;
9004 return BAD_VALUE;
9005 }
9006 status_t status = NO_ERROR;
9007 while (mCblk->serverIndex < mCblk->clientIndex) {
9008 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07009009 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009010 int *p = (int *)(mBuffer + mCblk->serverIndex);
9011 int size = *p++;
9012 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009013 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009014 break;
9015 }
9016 effect_param_t *param = (effect_param_t *)p;
9017 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009018 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009019 mCblk->serverIndex += size;
9020 continue;
9021 }
Eric Laurent25f43952010-07-28 05:40:18 -07009022 uint32_t psize = sizeof(effect_param_t) +
9023 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
9024 param->vsize;
9025 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
9026 psize,
9027 p,
9028 &rsize,
9029 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07009030 // stop at first error encountered
9031 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009032 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07009033 *(int *)pReplyData = reply;
9034 break;
9035 } else if (reply != NO_ERROR) {
9036 *(int *)pReplyData = reply;
9037 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009038 }
9039 mCblk->serverIndex += size;
9040 }
9041 mCblk->serverIndex = 0;
9042 mCblk->clientIndex = 0;
9043 return status;
9044 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009045 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009046 return enable();
9047 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009048 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009049 return disable();
9050 }
9051
9052 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9053}
9054
Eric Laurent59255e42011-07-27 19:49:51 -07009055void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009056{
Steve Block3856b092011-10-20 11:56:00 +01009057 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009058
9059 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07009060 mEnabled = enabled;
9061
Mathias Agopian65ab4712010-07-14 17:59:35 -07009062 if (signal && mEffectClient != 0) {
9063 mEffectClient->controlStatusChanged(hasControl);
9064 }
9065}
9066
Eric Laurent25f43952010-07-28 05:40:18 -07009067void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
9068 uint32_t cmdSize,
9069 void *pCmdData,
9070 uint32_t replySize,
9071 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009072{
9073 if (mEffectClient != 0) {
9074 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9075 }
9076}
9077
9078
9079
9080void AudioFlinger::EffectHandle::setEnabled(bool enabled)
9081{
9082 if (mEffectClient != 0) {
9083 mEffectClient->enableStatusChanged(enabled);
9084 }
9085}
9086
9087status_t AudioFlinger::EffectHandle::onTransact(
9088 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9089{
9090 return BnEffect::onTransact(code, data, reply, flags);
9091}
9092
9093
9094void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
9095{
Glenn Kastena0d68332012-01-27 16:47:15 -08009096 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009097
9098 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08009099 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07009100 mPriority,
9101 mHasControl,
9102 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009103 mCblk ? mCblk->clientIndex : 0,
9104 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07009105 );
9106
9107 if (locked) {
9108 mCblk->lock.unlock();
9109 }
9110}
9111
9112#undef LOG_TAG
9113#define LOG_TAG "AudioFlinger::EffectChain"
9114
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009115AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009116 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009117 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07009118 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9119 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009120{
Dima Zavinfce7a472011-04-19 22:30:36 -07009121 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009122 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009123 return;
9124 }
9125 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9126 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009127}
9128
9129AudioFlinger::EffectChain::~EffectChain()
9130{
9131 if (mOwnInBuffer) {
9132 delete mInBuffer;
9133 }
9134
9135}
9136
Eric Laurent59255e42011-07-27 19:49:51 -07009137// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009138sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009139{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009140 size_t size = mEffects.size();
9141
9142 for (size_t i = 0; i < size; i++) {
9143 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009144 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009145 }
9146 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009147 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009148}
9149
Eric Laurent59255e42011-07-27 19:49:51 -07009150// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009151sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009152{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009153 size_t size = mEffects.size();
9154
9155 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009156 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9157 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009158 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009159 }
9160 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009161 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009162}
9163
Eric Laurent59255e42011-07-27 19:49:51 -07009164// getEffectFromType_l() must be called with ThreadBase::mLock held
9165sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9166 const effect_uuid_t *type)
9167{
Eric Laurent59255e42011-07-27 19:49:51 -07009168 size_t size = mEffects.size();
9169
9170 for (size_t i = 0; i < size; i++) {
9171 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009172 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009173 }
9174 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009175 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009176}
9177
Eric Laurent91b14c42012-05-30 12:30:29 -07009178void AudioFlinger::EffectChain::clearInputBuffer()
9179{
9180 Mutex::Autolock _l(mLock);
9181 sp<ThreadBase> thread = mThread.promote();
9182 if (thread == 0) {
9183 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9184 return;
9185 }
9186 clearInputBuffer_l(thread);
9187}
9188
9189// Must be called with EffectChain::mLock locked
9190void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9191{
9192 size_t numSamples = thread->frameCount() * thread->channelCount();
9193 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9194
9195}
9196
Mathias Agopian65ab4712010-07-14 17:59:35 -07009197// Must be called with EffectChain::mLock locked
9198void AudioFlinger::EffectChain::process_l()
9199{
Eric Laurentdac69112010-09-28 14:09:57 -07009200 sp<ThreadBase> thread = mThread.promote();
9201 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009202 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009203 return;
9204 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009205 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9206 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009207 // always process effects unless no more tracks are on the session and the effect tail
9208 // has been rendered
9209 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009210 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009211 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009212
Eric Laurent544fe9b2011-11-11 15:42:52 -08009213 if (!tracksOnSession && mTailBufferCount == 0) {
9214 doProcess = false;
9215 }
9216
9217 if (activeTrackCnt() == 0) {
9218 // if no track is active and the effect tail has not been rendered,
9219 // the input buffer must be cleared here as the mixer process will not do it
9220 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009221 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009222 if (mTailBufferCount > 0) {
9223 mTailBufferCount--;
9224 }
9225 }
9226 }
Eric Laurentdac69112010-09-28 14:09:57 -07009227 }
9228
Mathias Agopian65ab4712010-07-14 17:59:35 -07009229 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009230 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009231 for (size_t i = 0; i < size; i++) {
9232 mEffects[i]->process();
9233 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009234 }
9235 for (size_t i = 0; i < size; i++) {
9236 mEffects[i]->updateState();
9237 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009238}
9239
Eric Laurentcab11242010-07-15 12:50:15 -07009240// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009241status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009242{
9243 effect_descriptor_t desc = effect->desc();
9244 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9245
9246 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009247 effect->setChain(this);
9248 sp<ThreadBase> thread = mThread.promote();
9249 if (thread == 0) {
9250 return NO_INIT;
9251 }
9252 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009253
9254 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9255 // Auxiliary effects are inserted at the beginning of mEffects vector as
9256 // they are processed first and accumulated in chain input buffer
9257 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009258
Mathias Agopian65ab4712010-07-14 17:59:35 -07009259 // the input buffer for auxiliary effect contains mono samples in
9260 // 32 bit format. This is to avoid saturation in AudoMixer
9261 // accumulation stage. Saturation is done in EffectModule::process() before
9262 // calling the process in effect engine
9263 size_t numSamples = thread->frameCount();
9264 int32_t *buffer = new int32_t[numSamples];
9265 memset(buffer, 0, numSamples * sizeof(int32_t));
9266 effect->setInBuffer((int16_t *)buffer);
9267 // auxiliary effects output samples to chain input buffer for further processing
9268 // by insert effects
9269 effect->setOutBuffer(mInBuffer);
9270 } else {
9271 // Insert effects are inserted at the end of mEffects vector as they are processed
9272 // after track and auxiliary effects.
9273 // Insert effect order as a function of indicated preference:
9274 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9275 // another effect is present
9276 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9277 // last effect claiming first position
9278 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9279 // first effect claiming last position
9280 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9281 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9282 // already present
9283
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009284 size_t size = mEffects.size();
9285 size_t idx_insert = size;
9286 ssize_t idx_insert_first = -1;
9287 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009288
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009289 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009290 effect_descriptor_t d = mEffects[i]->desc();
9291 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9292 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9293 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9294 // check invalid effect chaining combinations
9295 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9296 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009297 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009298 return INVALID_OPERATION;
9299 }
9300 // remember position of first insert effect and by default
9301 // select this as insert position for new effect
9302 if (idx_insert == size) {
9303 idx_insert = i;
9304 }
9305 // remember position of last insert effect claiming
9306 // first position
9307 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9308 idx_insert_first = i;
9309 }
9310 // remember position of first insert effect claiming
9311 // last position
9312 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9313 idx_insert_last == -1) {
9314 idx_insert_last = i;
9315 }
9316 }
9317 }
9318
9319 // modify idx_insert from first position if needed
9320 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9321 if (idx_insert_last != -1) {
9322 idx_insert = idx_insert_last;
9323 } else {
9324 idx_insert = size;
9325 }
9326 } else {
9327 if (idx_insert_first != -1) {
9328 idx_insert = idx_insert_first + 1;
9329 }
9330 }
9331
9332 // always read samples from chain input buffer
9333 effect->setInBuffer(mInBuffer);
9334
9335 // if last effect in the chain, output samples to chain
9336 // output buffer, otherwise to chain input buffer
9337 if (idx_insert == size) {
9338 if (idx_insert != 0) {
9339 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9340 mEffects[idx_insert-1]->configure();
9341 }
9342 effect->setOutBuffer(mOutBuffer);
9343 } else {
9344 effect->setOutBuffer(mInBuffer);
9345 }
9346 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009347
Steve Block3856b092011-10-20 11:56:00 +01009348 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009349 }
9350 effect->configure();
9351 return NO_ERROR;
9352}
9353
Eric Laurentcab11242010-07-15 12:50:15 -07009354// removeEffect_l() must be called with PlaybackThread::mLock held
9355size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009356{
9357 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009358 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009359 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9360
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009361 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009362 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009363 // calling stop here will remove pre-processing effect from the audio HAL.
9364 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9365 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009366 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9367 mEffects[i]->state() == EffectModule::STOPPING) {
9368 mEffects[i]->stop();
9369 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009370 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9371 delete[] effect->inBuffer();
9372 } else {
9373 if (i == size - 1 && i != 0) {
9374 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9375 mEffects[i - 1]->configure();
9376 }
9377 }
9378 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009379 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009380 break;
9381 }
9382 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009383
9384 return mEffects.size();
9385}
9386
Eric Laurentcab11242010-07-15 12:50:15 -07009387// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009388void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009389{
9390 size_t size = mEffects.size();
9391 for (size_t i = 0; i < size; i++) {
9392 mEffects[i]->setDevice(device);
9393 }
9394}
9395
Eric Laurentcab11242010-07-15 12:50:15 -07009396// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009397void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009398{
9399 size_t size = mEffects.size();
9400 for (size_t i = 0; i < size; i++) {
9401 mEffects[i]->setMode(mode);
9402 }
9403}
9404
Eric Laurent57b2dd12012-08-31 17:44:06 -07009405// setAudioSource_l() must be called with PlaybackThread::mLock held
9406void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
9407{
9408 size_t size = mEffects.size();
9409 for (size_t i = 0; i < size; i++) {
9410 mEffects[i]->setAudioSource(source);
9411 }
9412}
9413
Eric Laurentcab11242010-07-15 12:50:15 -07009414// setVolume_l() must be called with PlaybackThread::mLock held
9415bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009416{
9417 uint32_t newLeft = *left;
9418 uint32_t newRight = *right;
9419 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009420 int ctrlIdx = -1;
9421 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009422
Eric Laurentcab11242010-07-15 12:50:15 -07009423 // first update volume controller
9424 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009425 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009426 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9427 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009428 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009429 break;
9430 }
9431 }
9432
9433 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009434 if (hasControl) {
9435 *left = mNewLeftVolume;
9436 *right = mNewRightVolume;
9437 }
9438 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009439 }
9440
9441 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009442 mLeftVolume = newLeft;
9443 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009444
9445 // second get volume update from volume controller
9446 if (ctrlIdx >= 0) {
9447 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009448 mNewLeftVolume = newLeft;
9449 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009450 }
9451 // then indicate volume to all other effects in chain.
9452 // Pass altered volume to effects before volume controller
9453 // and requested volume to effects after controller
9454 uint32_t lVol = newLeft;
9455 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009456
Mathias Agopian65ab4712010-07-14 17:59:35 -07009457 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009458 if ((int)i == ctrlIdx) continue;
9459 // this also works for ctrlIdx == -1 when there is no volume controller
9460 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009461 lVol = *left;
9462 rVol = *right;
9463 }
9464 mEffects[i]->setVolume(&lVol, &rVol, false);
9465 }
9466 *left = newLeft;
9467 *right = newRight;
9468
9469 return hasControl;
9470}
9471
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009472void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009473{
9474 const size_t SIZE = 256;
9475 char buffer[SIZE];
9476 String8 result;
9477
9478 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9479 result.append(buffer);
9480
9481 bool locked = tryLock(mLock);
9482 // failed to lock - AudioFlinger is probably deadlocked
9483 if (!locked) {
9484 result.append("\tCould not lock mutex:\n");
9485 }
9486
Eric Laurentcab11242010-07-15 12:50:15 -07009487 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9488 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009489 mEffects.size(),
9490 (uint32_t)mInBuffer,
9491 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009492 mActiveTrackCnt);
9493 result.append(buffer);
9494 write(fd, result.string(), result.size());
9495
9496 for (size_t i = 0; i < mEffects.size(); ++i) {
9497 sp<EffectModule> effect = mEffects[i];
9498 if (effect != 0) {
9499 effect->dump(fd, args);
9500 }
9501 }
9502
9503 if (locked) {
9504 mLock.unlock();
9505 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009506}
9507
Eric Laurent59255e42011-07-27 19:49:51 -07009508// must be called with ThreadBase::mLock held
9509void AudioFlinger::EffectChain::setEffectSuspended_l(
9510 const effect_uuid_t *type, bool suspend)
9511{
9512 sp<SuspendedEffectDesc> desc;
9513 // use effect type UUID timelow as key as there is no real risk of identical
9514 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009515 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009516 if (suspend) {
9517 if (index >= 0) {
9518 desc = mSuspendedEffects.valueAt(index);
9519 } else {
9520 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -08009521 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07009522 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009523 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009524 }
9525 if (desc->mRefCount++ == 0) {
9526 sp<EffectModule> effect = getEffectIfEnabled(type);
9527 if (effect != 0) {
9528 desc->mEffect = effect;
9529 effect->setSuspended(true);
9530 effect->setEnabled(false);
9531 }
9532 }
9533 } else {
9534 if (index < 0) {
9535 return;
9536 }
9537 desc = mSuspendedEffects.valueAt(index);
9538 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009539 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009540 desc->mRefCount = 1;
9541 }
9542 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009543 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009544 if (desc->mEffect != 0) {
9545 sp<EffectModule> effect = desc->mEffect.promote();
9546 if (effect != 0) {
9547 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009548 effect->lock();
9549 EffectHandle *handle = effect->controlHandle_l();
9550 if (handle != NULL && !handle->destroyed_l()) {
9551 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009552 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009553 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009554 }
9555 desc->mEffect.clear();
9556 }
9557 mSuspendedEffects.removeItemsAt(index);
9558 }
9559 }
9560}
9561
9562// must be called with ThreadBase::mLock held
9563void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9564{
9565 sp<SuspendedEffectDesc> desc;
9566
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009567 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009568 if (suspend) {
9569 if (index >= 0) {
9570 desc = mSuspendedEffects.valueAt(index);
9571 } else {
9572 desc = new SuspendedEffectDesc();
9573 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009574 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009575 }
9576 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009577 Vector< sp<EffectModule> > effects;
9578 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009579 for (size_t i = 0; i < effects.size(); i++) {
9580 setEffectSuspended_l(&effects[i]->desc().type, true);
9581 }
9582 }
9583 } else {
9584 if (index < 0) {
9585 return;
9586 }
9587 desc = mSuspendedEffects.valueAt(index);
9588 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009589 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009590 desc->mRefCount = 1;
9591 }
9592 if (--desc->mRefCount == 0) {
9593 Vector<const effect_uuid_t *> types;
9594 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9595 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9596 continue;
9597 }
9598 types.add(&mSuspendedEffects.valueAt(i)->mType);
9599 }
9600 for (size_t i = 0; i < types.size(); i++) {
9601 setEffectSuspended_l(types[i], false);
9602 }
Steve Block3856b092011-10-20 11:56:00 +01009603 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009604 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9605 }
9606 }
9607}
9608
Eric Laurent6bffdb82011-09-23 08:40:41 -07009609
9610// The volume effect is used for automated tests only
9611#ifndef OPENSL_ES_H_
9612static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9613 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9614const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9615#endif //OPENSL_ES_H_
9616
Eric Laurentdb7c0792011-08-10 10:37:50 -07009617bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9618{
9619 // auxiliary effects and visualizer are never suspended on output mix
9620 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9621 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009622 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9623 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009624 return false;
9625 }
9626 return true;
9627}
9628
Glenn Kastend0539712012-01-30 12:56:03 -08009629void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009630{
Glenn Kastend0539712012-01-30 12:56:03 -08009631 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009632 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009633 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9634 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009635 }
Eric Laurent59255e42011-07-27 19:49:51 -07009636 }
Eric Laurent59255e42011-07-27 19:49:51 -07009637}
9638
9639sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9640 const effect_uuid_t *type)
9641{
Glenn Kasten090f0192012-01-30 13:00:02 -08009642 sp<EffectModule> effect = getEffectFromType_l(type);
9643 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009644}
9645
9646void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9647 bool enabled)
9648{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009649 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009650 if (enabled) {
9651 if (index < 0) {
9652 // if the effect is not suspend check if all effects are suspended
9653 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9654 if (index < 0) {
9655 return;
9656 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009657 if (!isEffectEligibleForSuspend(effect->desc())) {
9658 return;
9659 }
Eric Laurent59255e42011-07-27 19:49:51 -07009660 setEffectSuspended_l(&effect->desc().type, enabled);
9661 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009662 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009663 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009664 return;
9665 }
Eric Laurent59255e42011-07-27 19:49:51 -07009666 }
Steve Block3856b092011-10-20 11:56:00 +01009667 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009668 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009669 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9670 // if effect is requested to suspended but was not yet enabled, supend it now.
9671 if (desc->mEffect == 0) {
9672 desc->mEffect = effect;
9673 effect->setEnabled(false);
9674 effect->setSuspended(true);
9675 }
9676 } else {
9677 if (index < 0) {
9678 return;
9679 }
Steve Block3856b092011-10-20 11:56:00 +01009680 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009681 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009682 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9683 desc->mEffect.clear();
9684 effect->setSuspended(false);
9685 }
9686}
9687
Mathias Agopian65ab4712010-07-14 17:59:35 -07009688#undef LOG_TAG
9689#define LOG_TAG "AudioFlinger"
9690
9691// ----------------------------------------------------------------------------
9692
9693status_t AudioFlinger::onTransact(
9694 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9695{
9696 return BnAudioFlinger::onTransact(code, data, reply, flags);
9697}
9698
Mathias Agopian65ab4712010-07-14 17:59:35 -07009699}; // namespace android