blob: 76d64476e76ae87b7a5a544ead999c49cfa63fb3 [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++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001066 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001067 }
1068
1069 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001070 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001071 }
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");
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07001166 // do any cleanup required for exit to succeed
1167 preExit();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001168 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001169 // This lock prevents the following race in thread (uniprocessor for illustration):
1170 // if (!exitPending()) {
1171 // // context switch from here to exit()
1172 // // exit() calls requestExit(), what exitPending() observes
1173 // // exit() calls signal(), which is dropped since no waiters
1174 // // context switch back from exit() to here
1175 // mWaitWorkCV.wait(...);
1176 // // now thread is hung
1177 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001178 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001179 requestExit();
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07001180 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001181 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001182 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1183 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001184 requestExitAndWait();
1185}
1186
Mathias Agopian65ab4712010-07-14 17:59:35 -07001187status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1188{
1189 status_t status;
1190
Steve Block3856b092011-10-20 11:56:00 +01001191 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001192 Mutex::Autolock _l(mLock);
1193
1194 mNewParameters.add(keyValuePairs);
1195 mWaitWorkCV.signal();
1196 // wait condition with timeout in case the thread loop has exited
1197 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001198 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001199 status = mParamStatus;
1200 mWaitWorkCV.signal();
1201 } else {
1202 status = TIMED_OUT;
1203 }
1204 return status;
1205}
1206
Eric Laurent896adcd2012-09-13 11:18:23 -07001207void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001208{
1209 Mutex::Autolock _l(mLock);
Eric Laurent896adcd2012-09-13 11:18:23 -07001210 sendIoConfigEvent_l(event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001211}
1212
Eric Laurent896adcd2012-09-13 11:18:23 -07001213// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
1214void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001215{
Eric Laurent896adcd2012-09-13 11:18:23 -07001216 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
1217 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
1218 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1219 mWaitWorkCV.signal();
1220}
1221
1222// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
1223void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
1224{
1225 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
1226 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
1227 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
1228 mConfigEvents.size(), pid, tid, prio);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001229 mWaitWorkCV.signal();
1230}
1231
1232void AudioFlinger::ThreadBase::processConfigEvents()
1233{
1234 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001235 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001236 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Eric Laurent896adcd2012-09-13 11:18:23 -07001237 ConfigEvent *event = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001238 mConfigEvents.removeAt(0);
1239 // release mLock before locking AudioFlinger mLock: lock order is always
1240 // AudioFlinger then ThreadBase to avoid cross deadlock
1241 mLock.unlock();
Eric Laurent896adcd2012-09-13 11:18:23 -07001242 switch(event->type()) {
1243 case CFG_EVENT_PRIO: {
1244 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
1245 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio());
1246 if (err != 0) {
1247 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1248 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
1249 }
1250 } break;
1251 case CFG_EVENT_IO: {
1252 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
1253 mAudioFlinger->mLock.lock();
1254 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
1255 mAudioFlinger->mLock.unlock();
1256 } break;
1257 default:
1258 ALOGE("processConfigEvents() unknown event type %d", event->type());
1259 break;
1260 }
1261 delete event;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001262 mLock.lock();
1263 }
1264 mLock.unlock();
1265}
1266
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001267void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001268{
1269 const size_t SIZE = 256;
1270 char buffer[SIZE];
1271 String8 result;
1272
1273 bool locked = tryLock(mLock);
1274 if (!locked) {
1275 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1276 write(fd, buffer, strlen(buffer));
1277 }
1278
Eric Laurent612bbb52012-03-14 15:03:26 -07001279 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1280 result.append(buffer);
1281 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1282 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001283 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1284 result.append(buffer);
1285 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1286 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001287 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1288 result.append(buffer);
1289 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001290 result.append(buffer);
1291 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1292 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001293 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1294 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001295 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1296 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001297 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001298 result.append(buffer);
1299
1300 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1301 result.append(buffer);
1302 result.append(" Index Command");
1303 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1304 snprintf(buffer, SIZE, "\n %02d ", i);
1305 result.append(buffer);
1306 result.append(mNewParameters[i]);
1307 }
1308
1309 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1310 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001311 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001312 mConfigEvents[i]->dump(buffer, SIZE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001313 result.append(buffer);
1314 }
1315 result.append("\n");
1316
1317 write(fd, result.string(), result.size());
1318
1319 if (locked) {
1320 mLock.unlock();
1321 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001322}
1323
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001324void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001325{
1326 const size_t SIZE = 256;
1327 char buffer[SIZE];
1328 String8 result;
1329
1330 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1331 write(fd, buffer, strlen(buffer));
1332
1333 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1334 sp<EffectChain> chain = mEffectChains[i];
1335 if (chain != 0) {
1336 chain->dump(fd, args);
1337 }
1338 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001339}
1340
Eric Laurentfeb0db62011-07-22 09:04:31 -07001341void AudioFlinger::ThreadBase::acquireWakeLock()
1342{
1343 Mutex::Autolock _l(mLock);
1344 acquireWakeLock_l();
1345}
1346
1347void AudioFlinger::ThreadBase::acquireWakeLock_l()
1348{
1349 if (mPowerManager == 0) {
1350 // use checkService() to avoid blocking if power service is not up yet
1351 sp<IBinder> binder =
1352 defaultServiceManager()->checkService(String16("power"));
1353 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001354 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001355 } else {
1356 mPowerManager = interface_cast<IPowerManager>(binder);
1357 binder->linkToDeath(mDeathRecipient);
1358 }
1359 }
1360 if (mPowerManager != 0) {
1361 sp<IBinder> binder = new BBinder();
1362 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1363 binder,
1364 String16(mName));
1365 if (status == NO_ERROR) {
1366 mWakeLockToken = binder;
1367 }
Steve Block3856b092011-10-20 11:56:00 +01001368 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001369 }
1370}
1371
1372void AudioFlinger::ThreadBase::releaseWakeLock()
1373{
1374 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001375 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001376}
1377
1378void AudioFlinger::ThreadBase::releaseWakeLock_l()
1379{
1380 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001381 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001382 if (mPowerManager != 0) {
1383 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1384 }
1385 mWakeLockToken.clear();
1386 }
1387}
1388
1389void AudioFlinger::ThreadBase::clearPowerManager()
1390{
1391 Mutex::Autolock _l(mLock);
1392 releaseWakeLock_l();
1393 mPowerManager.clear();
1394}
1395
1396void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1397{
1398 sp<ThreadBase> thread = mThread.promote();
1399 if (thread != 0) {
1400 thread->clearPowerManager();
1401 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001402 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001403}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001404
Eric Laurent59255e42011-07-27 19:49:51 -07001405void AudioFlinger::ThreadBase::setEffectSuspended(
1406 const effect_uuid_t *type, bool suspend, int sessionId)
1407{
1408 Mutex::Autolock _l(mLock);
1409 setEffectSuspended_l(type, suspend, sessionId);
1410}
1411
1412void AudioFlinger::ThreadBase::setEffectSuspended_l(
1413 const effect_uuid_t *type, bool suspend, int sessionId)
1414{
Glenn Kasten090f0192012-01-30 13:00:02 -08001415 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001416 if (chain != 0) {
1417 if (type != NULL) {
1418 chain->setEffectSuspended_l(type, suspend);
1419 } else {
1420 chain->setEffectSuspendedAll_l(suspend);
1421 }
1422 }
1423
1424 updateSuspendedSessions_l(type, suspend, sessionId);
1425}
1426
1427void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1428{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001429 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001430 if (index < 0) {
1431 return;
1432 }
1433
Glenn Kasten0a7af182012-07-09 16:09:19 -07001434 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1435 mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001436
1437 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001438 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001439 for (int j = 0; j < desc->mRefCount; j++) {
1440 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1441 chain->setEffectSuspendedAll_l(true);
1442 } else {
Steve Block3856b092011-10-20 11:56:00 +01001443 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001444 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001445 chain->setEffectSuspended_l(&desc->mType, true);
1446 }
1447 }
1448 }
1449}
1450
Eric Laurent59255e42011-07-27 19:49:51 -07001451void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1452 bool suspend,
1453 int sessionId)
1454{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001455 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001456
1457 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1458
1459 if (suspend) {
1460 if (index >= 0) {
Glenn Kasten0a7af182012-07-09 16:09:19 -07001461 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001462 } else {
1463 mSuspendedSessions.add(sessionId, sessionEffects);
1464 }
1465 } else {
1466 if (index < 0) {
1467 return;
1468 }
Glenn Kasten0a7af182012-07-09 16:09:19 -07001469 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001470 }
1471
1472
1473 int key = EffectChain::kKeyForSuspendAll;
1474 if (type != NULL) {
1475 key = type->timeLow;
1476 }
1477 index = sessionEffects.indexOfKey(key);
1478
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001479 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001480 if (suspend) {
1481 if (index >= 0) {
1482 desc = sessionEffects.valueAt(index);
1483 } else {
1484 desc = new SuspendedSessionDesc();
1485 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001486 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001487 }
1488 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001489 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001490 }
1491 desc->mRefCount++;
1492 } else {
1493 if (index < 0) {
1494 return;
1495 }
1496 desc = sessionEffects.valueAt(index);
1497 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001498 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001499 sessionEffects.removeItemsAt(index);
1500 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001501 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001502 sessionId);
1503 mSuspendedSessions.removeItem(sessionId);
1504 }
1505 }
1506 }
1507 if (!sessionEffects.isEmpty()) {
1508 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1509 }
1510}
1511
1512void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1513 bool enabled,
1514 int sessionId)
1515{
1516 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001517 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1518}
Eric Laurent59255e42011-07-27 19:49:51 -07001519
Eric Laurenta85a74a2011-10-19 11:44:54 -07001520void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1521 bool enabled,
1522 int sessionId)
1523{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001524 if (mType != RECORD) {
1525 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1526 // another session. This gives the priority to well behaved effect control panels
1527 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001528 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1529 // global effects
1530 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001531 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1532 }
1533 }
Eric Laurent59255e42011-07-27 19:49:51 -07001534
1535 sp<EffectChain> chain = getEffectChain_l(sessionId);
1536 if (chain != 0) {
1537 chain->checkSuspendOnEffectEnabled(effect, enabled);
1538 }
1539}
1540
Mathias Agopian65ab4712010-07-14 17:59:35 -07001541// ----------------------------------------------------------------------------
1542
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001543AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1544 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001545 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001546 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001547 type_t type)
Eric Laurentf1c04f92012-08-28 14:26:53 -07001548 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001549 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001550 // mStreamTypes[] initialized in constructor body
1551 mOutput(output),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001552 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001553 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001554 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001555 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001556 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001557 // index 0 is reserved for normal mixer's submix
1558 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001559{
Glenn Kasten480b4682012-02-28 12:30:08 -08001560 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001561
John Grossmanee578c02012-07-23 17:05:46 -07001562 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1563 // it would be safer to explicitly pass initial masterVolume/masterMute as
1564 // parameter.
1565 //
1566 // If the HAL we are using has support for master volume or master mute,
1567 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1568 // and the mute set to false).
1569 mMasterVolume = audioFlinger->masterVolume_l();
1570 mMasterMute = audioFlinger->masterMute_l();
1571 if (mOutput && mOutput->audioHwDev) {
1572 if (mOutput->audioHwDev->canSetMasterVolume()) {
1573 mMasterVolume = 1.0;
1574 }
1575
1576 if (mOutput->audioHwDev->canSetMasterMute()) {
1577 mMasterMute = false;
1578 }
1579 }
1580
Mathias Agopian65ab4712010-07-14 17:59:35 -07001581 readOutputParameters();
1582
Glenn Kasten263709e2012-01-06 08:40:01 -08001583 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001584 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1585 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1586 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001587 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1588 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001590 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1591 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592}
1593
1594AudioFlinger::PlaybackThread::~PlaybackThread()
1595{
1596 delete [] mMixBuffer;
1597}
1598
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001599void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600{
1601 dumpInternals(fd, args);
1602 dumpTracks(fd, args);
1603 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001604}
1605
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001606void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001607{
1608 const size_t SIZE = 256;
1609 char buffer[SIZE];
1610 String8 result;
1611
Glenn Kasten58912562012-04-03 10:45:00 -07001612 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1613 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1614 const stream_type_t *st = &mStreamTypes[i];
1615 if (i > 0) {
1616 result.appendFormat(", ");
1617 }
1618 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1619 if (st->mute) {
1620 result.append("M");
1621 }
1622 }
1623 result.append("\n");
1624 write(fd, result.string(), result.length());
1625 result.clear();
1626
Mathias Agopian65ab4712010-07-14 17:59:35 -07001627 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1628 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001629 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001630 for (size_t i = 0; i < mTracks.size(); ++i) {
1631 sp<Track> track = mTracks[i];
1632 if (track != 0) {
1633 track->dump(buffer, SIZE);
1634 result.append(buffer);
1635 }
1636 }
1637
1638 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1639 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001640 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001641 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001642 sp<Track> track = mActiveTracks[i].promote();
1643 if (track != 0) {
1644 track->dump(buffer, SIZE);
1645 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001646 }
1647 }
1648 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001649
1650 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1651 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1652 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1653 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001654}
1655
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001656void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001657{
1658 const size_t SIZE = 256;
1659 char buffer[SIZE];
1660 String8 result;
1661
1662 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1663 result.append(buffer);
1664 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1665 result.append(buffer);
1666 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1667 result.append(buffer);
1668 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1669 result.append(buffer);
1670 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1671 result.append(buffer);
1672 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1673 result.append(buffer);
1674 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1675 result.append(buffer);
1676 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001677 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001678
1679 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001680}
1681
1682// Thread virtuals
1683status_t AudioFlinger::PlaybackThread::readyToRun()
1684{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001685 status_t status = initCheck();
1686 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001687 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001688 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001689 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001690 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001691 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001692}
1693
1694void AudioFlinger::PlaybackThread::onFirstRef()
1695{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001696 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001697}
1698
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07001699// ThreadBase virtuals
1700void AudioFlinger::PlaybackThread::preExit()
1701{
1702 ALOGV(" preExit()");
1703 // FIXME this is using hard-coded strings but in the future, this functionality will be
1704 // converted to use audio HAL extensions required to support tunneling
1705 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1706}
1707
Mathias Agopian65ab4712010-07-14 17:59:35 -07001708// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001709sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001710 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001711 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001712 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001713 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001714 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715 int frameCount,
1716 const sp<IMemory>& sharedBuffer,
1717 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001718 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001719 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001720 status_t *status)
1721{
1722 sp<Track> track;
1723 status_t lStatus;
1724
Glenn Kasten73d22752012-03-19 13:38:30 -07001725 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1726
1727 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001728 if (flags & IAudioFlinger::TRACK_FAST) {
1729 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001730 // not timed
1731 (!isTimed) &&
1732 // either of these use cases:
1733 (
1734 // use case 1: shared buffer with any frame count
1735 (
1736 (sharedBuffer != 0)
1737 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001738 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001739 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001740 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001741 ((frameCount == 0) ||
Glenn Kasten3ed29202012-08-07 15:24:44 -07001742 (frameCount >= (int) (mFrameCount * kFastTrackMultiplier)))
Glenn Kasten73d22752012-03-19 13:38:30 -07001743 )
1744 ) &&
1745 // PCM data
1746 audio_is_linear_pcm(format) &&
1747 // mono or stereo
1748 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1749 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001750#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001751 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001752 (sampleRate == mSampleRate) &&
1753#endif
1754 // normal mixer has an associated fast mixer
1755 hasFastMixer() &&
1756 // there are sufficient fast track slots available
1757 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001758 // FIXME test that MixerThread for this fast track has a capable output HAL
1759 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001760 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001761 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1762 if (frameCount == 0) {
Glenn Kasten3ed29202012-08-07 15:24:44 -07001763 frameCount = mFrameCount * kFastTrackMultiplier;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001764 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001765 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001766 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001767 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001768 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07001769 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001770 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1771 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1772 audio_is_linear_pcm(format),
1773 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001774 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001775 // For compatibility with AudioTrack calculation, buffer depth is forced
1776 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1777 // This is probably too conservative, but legacy application code may depend on it.
1778 // If you change this calculation, also review the start threshold which is related.
1779 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1780 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1781 if (minBufCount < 2) {
1782 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001783 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001784 int minFrameCount = mNormalFrameCount * minBufCount;
1785 if (frameCount < minFrameCount) {
1786 frameCount = minFrameCount;
1787 }
1788 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001789 }
1790
Mathias Agopian65ab4712010-07-14 17:59:35 -07001791 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001792 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1793 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001794 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001795 "for output %p with format %d",
1796 sampleRate, format, channelMask, mOutput, mFormat);
1797 lStatus = BAD_VALUE;
1798 goto Exit;
1799 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001800 }
1801 } else {
1802 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1803 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001804 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001805 lStatus = BAD_VALUE;
1806 goto Exit;
1807 }
1808 }
1809
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001810 lStatus = initCheck();
1811 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001812 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001813 goto Exit;
1814 }
1815
1816 { // scope for mLock
1817 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001818
1819 // all tracks in same audio session must share the same routing strategy otherwise
1820 // conflicts will happen when tracks are moved from one output to another by audio policy
1821 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001822 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001823 for (size_t i = 0; i < mTracks.size(); ++i) {
1824 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001825 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001826 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001827 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001828 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001829 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001830 lStatus = BAD_VALUE;
1831 goto Exit;
1832 }
1833 }
1834 }
1835
John Grossman4ff14ba2012-02-08 16:37:41 -08001836 if (!isTimed) {
1837 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001838 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001839 } else {
1840 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1841 channelMask, frameCount, sharedBuffer, sessionId);
1842 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001843 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001844 lStatus = NO_MEMORY;
1845 goto Exit;
1846 }
1847 mTracks.add(track);
1848
1849 sp<EffectChain> chain = getEffectChain_l(sessionId);
1850 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001851 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001852 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001853 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001854 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001856
Eric Laurent896adcd2012-09-13 11:18:23 -07001857 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1858 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1859 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1860 // so ask activity manager to do this on our behalf
1861 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001862 }
1863 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001864
Mathias Agopian65ab4712010-07-14 17:59:35 -07001865 lStatus = NO_ERROR;
1866
1867Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001868 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001869 *status = lStatus;
1870 }
1871 return track;
1872}
1873
Eric Laurente737cda2012-05-22 18:55:44 -07001874uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1875{
1876 if (mFastMixer != NULL) {
1877 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1878 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1879 }
1880 return latency;
1881}
1882
1883uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1884{
1885 return latency;
1886}
1887
Mathias Agopian65ab4712010-07-14 17:59:35 -07001888uint32_t AudioFlinger::PlaybackThread::latency() const
1889{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001890 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001891 return latency_l();
1892}
1893uint32_t AudioFlinger::PlaybackThread::latency_l() const
1894{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001895 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001896 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001897 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001898 return 0;
1899 }
1900}
1901
Glenn Kasten6637baa2012-01-09 09:40:36 -08001902void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001903{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001904 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001905 // Don't apply master volume in SW if our HAL can do it for us.
1906 if (mOutput && mOutput->audioHwDev &&
1907 mOutput->audioHwDev->canSetMasterVolume()) {
1908 mMasterVolume = 1.0;
1909 } else {
1910 mMasterVolume = value;
1911 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001912}
1913
Glenn Kasten6637baa2012-01-09 09:40:36 -08001914void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001915{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001916 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001917 // Don't apply master mute in SW if our HAL can do it for us.
1918 if (mOutput && mOutput->audioHwDev &&
1919 mOutput->audioHwDev->canSetMasterMute()) {
1920 mMasterMute = false;
1921 } else {
1922 mMasterMute = muted;
1923 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001924}
1925
Glenn Kasten6637baa2012-01-09 09:40:36 -08001926void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001927{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001928 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001929 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001930}
1931
Glenn Kasten6637baa2012-01-09 09:40:36 -08001932void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001933{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001934 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001935 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001936}
1937
Glenn Kastenfff6d712012-01-12 16:38:12 -08001938float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001940 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001941 return mStreamTypes[stream].volume;
1942}
1943
Mathias Agopian65ab4712010-07-14 17:59:35 -07001944// addTrack_l() must be called with ThreadBase::mLock held
1945status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1946{
1947 status_t status = ALREADY_EXISTS;
1948
1949 // set retry count for buffer fill
1950 track->mRetryCount = kMaxTrackStartupRetries;
1951 if (mActiveTracks.indexOf(track) < 0) {
1952 // the track is newly added, make sure it fills up all its
1953 // buffers before playing. This is to ensure the client will
1954 // effectively get the latency it requested.
1955 track->mFillingUpStatus = Track::FS_FILLING;
1956 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001957 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001958 mActiveTracks.add(track);
1959 if (track->mainBuffer() != mMixBuffer) {
1960 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1961 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001962 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001963 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001964 }
1965 }
1966
1967 status = NO_ERROR;
1968 }
1969
Steve Block3856b092011-10-20 11:56:00 +01001970 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001971 mWaitWorkCV.broadcast();
1972
1973 return status;
1974}
1975
1976// destroyTrack_l() must be called with ThreadBase::mLock held
1977void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1978{
1979 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001980 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001981 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001982 removeTrack_l(track);
1983 }
1984}
1985
1986void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1987{
Eric Laurent29864602012-05-08 18:57:51 -07001988 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001989 mTracks.remove(track);
1990 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001991 // redundant as track is about to be destroyed, for dumpsys only
1992 track->mName = -1;
1993 if (track->isFastTrack()) {
1994 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001995 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001996 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1997 mFastTrackAvailMask |= 1 << index;
1998 // redundant as track is about to be destroyed, for dumpsys only
1999 track->mFastIndex = -1;
2000 }
Eric Laurentb469b942011-05-09 12:09:06 -07002001 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2002 if (chain != 0) {
2003 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002004 }
2005}
2006
2007String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2008{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002009 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07002010 char *s;
2011
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002012 Mutex::Autolock _l(mLock);
2013 if (initCheck() != NO_ERROR) {
2014 return out_s8;
2015 }
2016
Dima Zavin799a70e2011-04-18 16:57:27 -07002017 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07002018 out_s8 = String8(s);
2019 free(s);
2020 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002021}
2022
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002023// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002024void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
2025 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08002026 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002027
Steve Block3856b092011-10-20 11:56:00 +01002028 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002029
2030 switch (event) {
2031 case AudioSystem::OUTPUT_OPENED:
2032 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002033 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002034 desc.samplingRate = mSampleRate;
2035 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07002036 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037 desc.latency = latency();
2038 param2 = &desc;
2039 break;
2040
2041 case AudioSystem::STREAM_CONFIG_CHANGED:
2042 param2 = &param;
2043 case AudioSystem::OUTPUT_CLOSED:
2044 default:
2045 break;
2046 }
2047 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2048}
2049
2050void AudioFlinger::PlaybackThread::readOutputParameters()
2051{
Dima Zavin799a70e2011-04-18 16:57:27 -07002052 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002053 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2054 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07002055 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002056 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002057 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002058 if (mFrameCount & 15) {
2059 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2060 mFrameCount);
2061 }
2062
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002063 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002064 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002065 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002066 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002067 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2068 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2069 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2070 maxNormalFrameCount = maxNormalFrameCount & ~15;
2071 if (maxNormalFrameCount < minNormalFrameCount) {
2072 maxNormalFrameCount = minNormalFrameCount;
2073 }
2074 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2075 if (multiplier <= 1.0) {
2076 multiplier = 1.0;
2077 } else if (multiplier <= 2.0) {
2078 if (2 * mFrameCount <= maxNormalFrameCount) {
2079 multiplier = 2.0;
2080 } else {
2081 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2082 }
2083 } else {
2084 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2085 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2086 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2087 // FIXME this rounding up should not be done if no HAL SRC
2088 uint32_t truncMult = (uint32_t) multiplier;
2089 if ((truncMult & 1)) {
2090 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2091 ++truncMult;
2092 }
2093 }
2094 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002095 }
Glenn Kasten58912562012-04-03 10:45:00 -07002096 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002097 mNormalFrameCount = multiplier * mFrameCount;
2098 // round up to nearest 16 frames to satisfy AudioMixer
2099 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002100 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002101
Glenn Kastene9dd0172012-01-27 18:08:45 -08002102 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002103 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2104 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105
Eric Laurentde070132010-07-13 04:45:46 -07002106 // force reconfiguration of effect chains and engines to take new buffer size and audio
2107 // parameters into account
2108 // Note that mLock is not held when readOutputParameters() is called from the constructor
2109 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2110 // matter.
2111 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2112 Vector< sp<EffectChain> > effectChains = mEffectChains;
2113 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002114 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002115 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002116}
2117
Eric Laurente737cda2012-05-22 18:55:44 -07002118
Mathias Agopian65ab4712010-07-14 17:59:35 -07002119status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2120{
Glenn Kastena0d68332012-01-27 16:47:15 -08002121 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002122 return BAD_VALUE;
2123 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002124 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002125 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002126 return INVALID_OPERATION;
2127 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002128 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002129
Eric Laurent1afc26d2012-09-23 15:20:50 -07002130 if (isSuspended()) {
2131 // return an estimation of rendered frames when the output is suspended
2132 int32_t frames = mBytesWritten - latency_l();
2133 if (frames < 0) {
2134 frames = 0;
2135 }
2136 *dspFrames = (uint32_t)frames;
2137 return NO_ERROR;
2138 } else {
2139 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
2140 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002141}
2142
Glenn Kasten106e8a42012-08-02 13:37:12 -07002143uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002144{
2145 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002146 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002147 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002148 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002149 }
2150
2151 for (size_t i = 0; i < mTracks.size(); ++i) {
2152 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002153 if (sessionId == track->sessionId() &&
2154 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002155 result |= TRACK_SESSION;
2156 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002157 }
2158 }
2159
Eric Laurent39e94f82010-07-28 01:32:47 -07002160 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002161}
2162
Eric Laurentde070132010-07-13 04:45:46 -07002163uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2164{
Dima Zavinfce7a472011-04-19 22:30:36 -07002165 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002166 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002167 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2168 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002169 }
2170 for (size_t i = 0; i < mTracks.size(); i++) {
2171 sp<Track> track = mTracks[i];
2172 if (sessionId == track->sessionId() &&
2173 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002174 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002175 }
2176 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002177 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002178}
2179
Mathias Agopian65ab4712010-07-14 17:59:35 -07002180
Glenn Kastenaed850d2012-01-26 09:46:34 -08002181AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002182{
2183 Mutex::Autolock _l(mLock);
2184 return mOutput;
2185}
2186
2187AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2188{
2189 Mutex::Autolock _l(mLock);
2190 AudioStreamOut *output = mOutput;
2191 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002192 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2193 // must push a NULL and wait for ack
2194 mOutputSink.clear();
2195 mPipeSink.clear();
2196 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002197 return output;
2198}
2199
2200// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002201audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002202{
2203 if (mOutput == NULL) {
2204 return NULL;
2205 }
2206 return &mOutput->stream->common;
2207}
2208
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002209uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002210{
Eric Laurentab9071b2012-06-04 13:45:29 -07002211 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002212}
2213
Eric Laurenta011e352012-03-29 15:51:43 -07002214status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2215{
2216 if (!isValidSyncEvent(event)) {
2217 return BAD_VALUE;
2218 }
2219
2220 Mutex::Autolock _l(mLock);
2221
2222 for (size_t i = 0; i < mTracks.size(); ++i) {
2223 sp<Track> track = mTracks[i];
2224 if (event->triggerSession() == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07002225 (void) track->setSyncEvent(event);
Eric Laurenta011e352012-03-29 15:51:43 -07002226 return NO_ERROR;
2227 }
2228 }
2229
2230 return NAME_NOT_FOUND;
2231}
2232
Glenn Kasten106e8a42012-08-02 13:37:12 -07002233bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07002234{
Glenn Kasten0dbb3562012-08-02 16:36:50 -07002235 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
Eric Laurenta011e352012-03-29 15:51:43 -07002236}
2237
Eric Laurent44a957f2012-05-15 15:26:05 -07002238void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2239{
2240 size_t count = tracksToRemove.size();
2241 if (CC_UNLIKELY(count)) {
2242 for (size_t i = 0 ; i < count ; i++) {
2243 const sp<Track>& track = tracksToRemove.itemAt(i);
2244 if ((track->sharedBuffer() != 0) &&
2245 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2246 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2247 }
2248 }
2249 }
2250
2251}
2252
Mathias Agopian65ab4712010-07-14 17:59:35 -07002253// ----------------------------------------------------------------------------
2254
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002255AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002256 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002257 : PlaybackThread(audioFlinger, output, id, device, type),
2258 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002259 // mFastMixer below
2260 mFastMixerFutex(0)
2261 // mOutputSink below
2262 // mPipeSink below
2263 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002264{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002265 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002266 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002267 "mFrameCount=%d, mNormalFrameCount=%d",
2268 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2269 mNormalFrameCount);
2270 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2271
Mathias Agopian65ab4712010-07-14 17:59:35 -07002272 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002273 if (mChannelCount != FCC_2) {
2274 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002275 }
Glenn Kasten58912562012-04-03 10:45:00 -07002276
2277 // create an NBAIO sink for the HAL output stream, and negotiate
2278 mOutputSink = new AudioStreamOutSink(output->stream);
2279 size_t numCounterOffers = 0;
2280 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2281 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2282 ALOG_ASSERT(index == 0);
2283
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002284 // initialize fast mixer depending on configuration
2285 bool initFastMixer;
2286 switch (kUseFastMixer) {
2287 case FastMixer_Never:
2288 initFastMixer = false;
2289 break;
2290 case FastMixer_Always:
2291 initFastMixer = true;
2292 break;
2293 case FastMixer_Static:
2294 case FastMixer_Dynamic:
2295 initFastMixer = mFrameCount < mNormalFrameCount;
2296 break;
2297 }
2298 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002299
2300 // create a MonoPipe to connect our submix to FastMixer
2301 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002302 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2303 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2304 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2305 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002306 const NBAIO_Format offers[1] = {format};
2307 size_t numCounterOffers = 0;
2308 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2309 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002310 monoPipe->setAvgFrames((mScreenState & 1) ?
2311 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002312 mPipeSink = monoPipe;
2313
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002314#ifdef TEE_SINK_FRAMES
2315 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2316 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2317 numCounterOffers = 0;
2318 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2319 ALOG_ASSERT(index == 0);
2320 mTeeSink = teeSink;
2321 PipeReader *teeSource = new PipeReader(*teeSink);
2322 numCounterOffers = 0;
2323 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2324 ALOG_ASSERT(index == 0);
2325 mTeeSource = teeSource;
2326#endif
2327
Glenn Kasten58912562012-04-03 10:45:00 -07002328 // create fast mixer and configure it initially with just one fast track for our submix
2329 mFastMixer = new FastMixer();
2330 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002331#ifdef STATE_QUEUE_DUMP
2332 sq->setObserverDump(&mStateQueueObserverDump);
2333 sq->setMutatorDump(&mStateQueueMutatorDump);
2334#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002335 FastMixerState *state = sq->begin();
2336 FastTrack *fastTrack = &state->mFastTracks[0];
2337 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2338 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2339 fastTrack->mVolumeProvider = NULL;
2340 fastTrack->mGeneration++;
2341 state->mFastTracksGen++;
2342 state->mTrackMask = 1;
2343 // fast mixer will use the HAL output sink
2344 state->mOutputSink = mOutputSink.get();
2345 state->mOutputSinkGen++;
2346 state->mFrameCount = mFrameCount;
2347 state->mCommand = FastMixerState::COLD_IDLE;
2348 // already done in constructor initialization list
2349 //mFastMixerFutex = 0;
2350 state->mColdFutexAddr = &mFastMixerFutex;
2351 state->mColdGen++;
2352 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002353 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002354 sq->end();
2355 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2356
2357 // start the fast mixer
2358 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002359 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002360 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002361 if (err != 0) {
2362 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002363 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002364 }
Glenn Kasten58912562012-04-03 10:45:00 -07002365
Glenn Kastenc15d6652012-05-30 14:52:57 -07002366#ifdef AUDIO_WATCHDOG
2367 // create and start the watchdog
2368 mAudioWatchdog = new AudioWatchdog();
2369 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2370 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2371 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002372 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002373 if (err != 0) {
2374 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002375 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002376 }
2377#endif
2378
Glenn Kasten58912562012-04-03 10:45:00 -07002379 } else {
2380 mFastMixer = NULL;
2381 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002382
2383 switch (kUseFastMixer) {
2384 case FastMixer_Never:
2385 case FastMixer_Dynamic:
2386 mNormalSink = mOutputSink;
2387 break;
2388 case FastMixer_Always:
2389 mNormalSink = mPipeSink;
2390 break;
2391 case FastMixer_Static:
2392 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2393 break;
2394 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002395}
2396
2397AudioFlinger::MixerThread::~MixerThread()
2398{
Glenn Kasten58912562012-04-03 10:45:00 -07002399 if (mFastMixer != NULL) {
2400 FastMixerStateQueue *sq = mFastMixer->sq();
2401 FastMixerState *state = sq->begin();
2402 if (state->mCommand == FastMixerState::COLD_IDLE) {
2403 int32_t old = android_atomic_inc(&mFastMixerFutex);
2404 if (old == -1) {
2405 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2406 }
2407 }
2408 state->mCommand = FastMixerState::EXIT;
2409 sq->end();
2410 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2411 mFastMixer->join();
2412 // Though the fast mixer thread has exited, it's state queue is still valid.
2413 // We'll use that extract the final state which contains one remaining fast track
2414 // corresponding to our sub-mix.
2415 state = sq->begin();
2416 ALOG_ASSERT(state->mTrackMask == 1);
2417 FastTrack *fastTrack = &state->mFastTracks[0];
2418 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2419 delete fastTrack->mBufferProvider;
2420 sq->end(false /*didModify*/);
2421 delete mFastMixer;
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002422#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002423 if (mAudioWatchdog != 0) {
2424 mAudioWatchdog->requestExit();
2425 mAudioWatchdog->requestExitAndWait();
2426 mAudioWatchdog.clear();
2427 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002428#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002429 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002430 delete mAudioMixer;
2431}
2432
Glenn Kasten83efdd02012-02-24 07:21:32 -08002433class CpuStats {
2434public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002435 CpuStats();
2436 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002437#ifdef DEBUG_CPU_USAGE
2438private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002439 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2440 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2441
2442 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2443
2444 int mCpuNum; // thread's current CPU number
2445 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002446#endif
2447};
2448
Glenn Kasten190a46f2012-03-06 11:27:10 -08002449CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002450#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002451 : mCpuNum(-1), mCpukHz(-1)
2452#endif
2453{
2454}
2455
2456void CpuStats::sample(const String8 &title) {
2457#ifdef DEBUG_CPU_USAGE
2458 // get current thread's delta CPU time in wall clock ns
2459 double wcNs;
2460 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2461
2462 // record sample for wall clock statistics
2463 if (valid) {
2464 mWcStats.sample(wcNs);
2465 }
2466
2467 // get the current CPU number
2468 int cpuNum = sched_getcpu();
2469
2470 // get the current CPU frequency in kHz
2471 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2472
2473 // check if either CPU number or frequency changed
2474 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2475 mCpuNum = cpuNum;
2476 mCpukHz = cpukHz;
2477 // ignore sample for purposes of cycles
2478 valid = false;
2479 }
2480
2481 // if no change in CPU number or frequency, then record sample for cycle statistics
2482 if (valid && mCpukHz > 0) {
2483 double cycles = wcNs * cpukHz * 0.000001;
2484 mHzStats.sample(cycles);
2485 }
2486
2487 unsigned n = mWcStats.n();
2488 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002489 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002490 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002491 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2492 double perLoop = elapsed / (double) n;
2493 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002494 double perLoop1k = perLoop * 0.001;
2495 double mean = mWcStats.mean();
2496 double stddev = mWcStats.stddev();
2497 double minimum = mWcStats.minimum();
2498 double maximum = mWcStats.maximum();
2499 double meanCycles = mHzStats.mean();
2500 double stddevCycles = mHzStats.stddev();
2501 double minCycles = mHzStats.minimum();
2502 double maxCycles = mHzStats.maximum();
2503 mCpuUsage.resetElapsed();
2504 mWcStats.reset();
2505 mHzStats.reset();
2506 ALOGD("CPU usage for %s over past %.1f secs\n"
2507 " (%u mixer loops at %.1f mean ms per loop):\n"
2508 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2509 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2510 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2511 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002512 elapsed * .000000001, n, perLoop * .000001,
2513 mean * .001,
2514 stddev * .001,
2515 minimum * .001,
2516 maximum * .001,
2517 mean / perLoop100,
2518 stddev / perLoop100,
2519 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002520 maximum / perLoop100,
2521 meanCycles / perLoop1k,
2522 stddevCycles / perLoop1k,
2523 minCycles / perLoop1k,
2524 maxCycles / perLoop1k);
2525
Glenn Kasten83efdd02012-02-24 07:21:32 -08002526 }
2527 }
2528#endif
2529};
2530
Glenn Kasten37d825e2012-02-24 07:21:48 -08002531void AudioFlinger::PlaybackThread::checkSilentMode_l()
2532{
2533 if (!mMasterMute) {
2534 char value[PROPERTY_VALUE_MAX];
2535 if (property_get("ro.audio.silent", value, "0") > 0) {
2536 char *endptr;
2537 unsigned long ul = strtoul(value, &endptr, 0);
2538 if (*endptr == '\0' && ul != 0) {
2539 ALOGD("Silence is golden");
2540 // The setprop command will not allow a property to be changed after
2541 // the first time it is set, so we don't have to worry about un-muting.
2542 setMasterMute_l(true);
2543 }
2544 }
2545 }
2546}
2547
Glenn Kasten000f0e32012-03-01 17:10:56 -08002548bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002549{
2550 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002551
Glenn Kasten000f0e32012-03-01 17:10:56 -08002552 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002553
2554 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002555 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002556
Glenn Kasten000f0e32012-03-01 17:10:56 -08002557 // DUPLICATING
2558 // FIXME could this be made local to while loop?
2559 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002560
Glenn Kasten66fcab92012-02-24 14:59:21 -08002561 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002562 sleepTime = idleSleepTime;
2563
Glenn Kasten9f34a362012-03-20 16:46:41 -07002564 if (mType == MIXER) {
2565 sleepTimeShift = 0;
2566 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002567
Glenn Kasten83efdd02012-02-24 07:21:32 -08002568 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002569 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002570
Eric Laurentfeb0db62011-07-22 09:04:31 -07002571 acquireWakeLock();
2572
Mathias Agopian65ab4712010-07-14 17:59:35 -07002573 while (!exitPending())
2574 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002575 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002576
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002577 Vector< sp<EffectChain> > effectChains;
2578
Mathias Agopian65ab4712010-07-14 17:59:35 -07002579 processConfigEvents();
2580
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581 { // scope for mLock
2582
2583 Mutex::Autolock _l(mLock);
2584
2585 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002586 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002587 }
2588
Glenn Kastenfa26a852012-03-06 11:28:04 -08002589 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002590
Mathias Agopian65ab4712010-07-14 17:59:35 -07002591 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002592 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002593 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002594 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002595
2596 threadLoop_standby();
2597
Mathias Agopian65ab4712010-07-14 17:59:35 -07002598 mStandby = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002599 }
2600
Glenn Kasten3e074702012-02-28 18:40:35 -08002601 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002602 // we're about to wait, flush the binder command buffer
2603 IPCThreadState::self()->flushCommands();
2604
Glenn Kastenfa26a852012-03-06 11:28:04 -08002605 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002606
Mathias Agopian65ab4712010-07-14 17:59:35 -07002607 if (exitPending()) break;
2608
Eric Laurentfeb0db62011-07-22 09:04:31 -07002609 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002610 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002611 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002612 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002613 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002614 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002615
Eric Laurentda747442012-04-25 18:53:13 -07002616 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002617 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Eric Laurent1afc26d2012-09-23 15:20:50 -07002618 mBytesWritten = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002619
Glenn Kasten37d825e2012-02-24 07:21:48 -08002620 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621
Glenn Kasten000f0e32012-03-01 17:10:56 -08002622 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002623 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002624 if (mType == MIXER) {
2625 sleepTimeShift = 0;
2626 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002627
Mathias Agopian65ab4712010-07-14 17:59:35 -07002628 continue;
2629 }
2630 }
2631
Glenn Kasten81028042012-04-30 18:15:12 -07002632 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002633 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002634
2635 // prevent any changes in effect chain list and in each effect chain
2636 // during mixing and effect process as the audio buffers could be deleted
2637 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002638 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002639 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002640
Glenn Kastenfec279f2012-03-08 07:47:15 -08002641 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002642 threadLoop_mix();
2643 } else {
2644 threadLoop_sleepTime();
2645 }
2646
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002647 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002648 sleepTime = suspendSleepTimeUs();
Eric Laurent1afc26d2012-09-23 15:20:50 -07002649 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002650 }
2651
2652 // only process effects if we're going to write
2653 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002654 for (size_t i = 0; i < effectChains.size(); i ++) {
2655 effectChains[i]->process_l();
2656 }
2657 }
2658
2659 // enable changes in effect chain
2660 unlockEffectChains(effectChains);
2661
2662 // sleepTime == 0 means we must write to audio hardware
2663 if (sleepTime == 0) {
2664
2665 threadLoop_write();
2666
2667if (mType == MIXER) {
2668 // write blocked detection
2669 nsecs_t now = systemTime();
2670 nsecs_t delta = now - mLastWriteTime;
2671 if (!mStandby && delta > maxPeriod) {
2672 mNumDelayedWrites++;
2673 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002674#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002675 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002676#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002677 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2678 ns2ms(delta), mNumDelayedWrites, this);
2679 lastWarning = now;
2680 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002681 }
2682}
2683
2684 mStandby = false;
2685 } else {
2686 usleep(sleepTime);
2687 }
2688
Glenn Kasten58912562012-04-03 10:45:00 -07002689 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002690 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002691 // same lock. This will also mutate and push a new fast mixer state.
2692 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002693 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002694
Glenn Kastenfa26a852012-03-06 11:28:04 -08002695 // FIXME I don't understand the need for this here;
2696 // it was in the original code but maybe the
2697 // assignment in saveOutputTracks() makes this unnecessary?
2698 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002699
2700 // Effect chains will be actually deleted here if they were removed from
2701 // mEffectChains list during mixing or effects processing
2702 effectChains.clear();
2703
2704 // FIXME Note that the above .clear() is no longer necessary since effectChains
2705 // is now local to this block, but will keep it for now (at least until merge done).
2706 }
2707
Glenn Kasten9f34a362012-03-20 16:46:41 -07002708 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2709 if (mType == MIXER || mType == DIRECT) {
2710 // put output stream into standby mode
2711 if (!mStandby) {
2712 mOutput->stream->common.standby(&mOutput->stream->common);
2713 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002714 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002715
2716 releaseWakeLock();
2717
2718 ALOGV("Thread %p type %d exiting", this, mType);
2719 return false;
2720}
2721
Glenn Kasten58912562012-04-03 10:45:00 -07002722void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2723{
Glenn Kasten58912562012-04-03 10:45:00 -07002724 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2725}
2726
2727void AudioFlinger::MixerThread::threadLoop_write()
2728{
2729 // FIXME we should only do one push per cycle; confirm this is true
2730 // Start the fast mixer if it's not already running
2731 if (mFastMixer != NULL) {
2732 FastMixerStateQueue *sq = mFastMixer->sq();
2733 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002734 if (state->mCommand != FastMixerState::MIX_WRITE &&
2735 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002736 if (state->mCommand == FastMixerState::COLD_IDLE) {
2737 int32_t old = android_atomic_inc(&mFastMixerFutex);
2738 if (old == -1) {
2739 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2740 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002741#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002742 if (mAudioWatchdog != 0) {
2743 mAudioWatchdog->resume();
2744 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002745#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002746 }
2747 state->mCommand = FastMixerState::MIX_WRITE;
2748 sq->end();
2749 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002750 if (kUseFastMixer == FastMixer_Dynamic) {
2751 mNormalSink = mPipeSink;
2752 }
Glenn Kasten58912562012-04-03 10:45:00 -07002753 } else {
2754 sq->end(false /*didModify*/);
2755 }
2756 }
2757 PlaybackThread::threadLoop_write();
2758}
2759
Glenn Kasten000f0e32012-03-01 17:10:56 -08002760// shared by MIXER and DIRECT, overridden by DUPLICATING
2761void AudioFlinger::PlaybackThread::threadLoop_write()
2762{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002763 // FIXME rewrite to reduce number of system calls
2764 mLastWriteTime = systemTime();
2765 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002766 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002767
Eric Laurent67c0a582012-05-01 19:31:12 -07002768 // If an NBAIO sink is present, use it to write the normal mixer's submix
2769 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002770#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002771 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002772#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002773 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002774#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002775 // update the setpoint when gScreenState changes
2776 uint32_t screenState = gScreenState;
2777 if (screenState != mScreenState) {
2778 mScreenState = screenState;
2779 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2780 if (pipe != NULL) {
2781 pipe->setAvgFrames((mScreenState & 1) ?
2782 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2783 }
2784 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002785 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002786#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002787 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002788#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002789 if (framesWritten > 0) {
2790 bytesWritten = framesWritten << mBitShift;
2791 } else {
2792 bytesWritten = framesWritten;
2793 }
2794 // otherwise use the HAL / AudioStreamOut directly
2795 } else {
2796 // Direct output thread.
2797 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002798 }
2799
Eric Laurent67c0a582012-05-01 19:31:12 -07002800 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002801 mNumWrites++;
2802 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002803}
2804
Glenn Kasten58912562012-04-03 10:45:00 -07002805void AudioFlinger::MixerThread::threadLoop_standby()
2806{
2807 // Idle the fast mixer if it's currently running
2808 if (mFastMixer != NULL) {
2809 FastMixerStateQueue *sq = mFastMixer->sq();
2810 FastMixerState *state = sq->begin();
2811 if (!(state->mCommand & FastMixerState::IDLE)) {
2812 state->mCommand = FastMixerState::COLD_IDLE;
2813 state->mColdFutexAddr = &mFastMixerFutex;
2814 state->mColdGen++;
2815 mFastMixerFutex = 0;
2816 sq->end();
2817 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2818 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002819 if (kUseFastMixer == FastMixer_Dynamic) {
2820 mNormalSink = mOutputSink;
2821 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002822#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002823 if (mAudioWatchdog != 0) {
2824 mAudioWatchdog->pause();
2825 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002826#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002827 } else {
2828 sq->end(false /*didModify*/);
2829 }
2830 }
2831 PlaybackThread::threadLoop_standby();
2832}
2833
Glenn Kasten000f0e32012-03-01 17:10:56 -08002834// shared by MIXER and DIRECT, overridden by DUPLICATING
2835void AudioFlinger::PlaybackThread::threadLoop_standby()
2836{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002837 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002838 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002839}
2840
2841void AudioFlinger::MixerThread::threadLoop_mix()
2842{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002843 // obtain the presentation timestamp of the next output buffer
2844 int64_t pts;
2845 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002846
John Grossman2c3b2da2012-08-02 17:08:54 -07002847 if (mNormalSink != 0) {
2848 status = mNormalSink->getNextWriteTimestamp(&pts);
2849 } else {
2850 status = mOutputSink->getNextWriteTimestamp(&pts);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002851 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002852
Glenn Kasten952eeb22012-03-06 11:30:57 -08002853 if (status != NO_ERROR) {
2854 pts = AudioBufferProvider::kInvalidPTS;
2855 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002856
Glenn Kasten952eeb22012-03-06 11:30:57 -08002857 // mix buffers...
2858 mAudioMixer->process(pts);
2859 // increase sleep time progressively when application underrun condition clears.
2860 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2861 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2862 // such that we would underrun the audio HAL.
2863 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2864 sleepTimeShift--;
2865 }
2866 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002867 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002868 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002869}
2870
2871void AudioFlinger::MixerThread::threadLoop_sleepTime()
2872{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002873 // If no tracks are ready, sleep once for the duration of an output
2874 // buffer size, then write 0s to the output
2875 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002876 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002877 sleepTime = activeSleepTime >> sleepTimeShift;
2878 if (sleepTime < kMinThreadSleepTimeUs) {
2879 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002880 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002881 // reduce sleep time in case of consecutive application underruns to avoid
2882 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2883 // duration we would end up writing less data than needed by the audio HAL if
2884 // the condition persists.
2885 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2886 sleepTimeShift++;
2887 }
2888 } else {
2889 sleepTime = idleSleepTime;
2890 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002891 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002892 memset (mMixBuffer, 0, mixBufferSize);
2893 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002894 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002895 }
2896 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002897}
2898
2899// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002900AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002901 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002902{
2903
Glenn Kasten29c23c32012-01-26 13:37:52 -08002904 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002905 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002906 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002907 size_t mixedTracks = 0;
2908 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002909 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002910 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002911 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002912
2913 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002914 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002915
Eric Laurent571d49c2010-08-11 05:20:11 -07002916 if (masterMute) {
2917 masterVolume = 0;
2918 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002919 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002920 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002921 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002922 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002923 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002924 masterVolume = (float)((v + (1 << 23)) >> 24);
2925 chain.clear();
2926 }
2927
Glenn Kasten288ed212012-04-25 17:52:27 -07002928 // prepare a new state to push
2929 FastMixerStateQueue *sq = NULL;
2930 FastMixerState *state = NULL;
2931 bool didModify = false;
2932 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2933 if (mFastMixer != NULL) {
2934 sq = mFastMixer->sq();
2935 state = sq->begin();
2936 }
2937
Mathias Agopian65ab4712010-07-14 17:59:35 -07002938 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002939 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002940 if (t == 0) continue;
2941
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002942 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002943 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002944
Glenn Kasten288ed212012-04-25 17:52:27 -07002945 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002946 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002947
2948 // It's theoretically possible (though unlikely) for a fast track to be created
2949 // and then removed within the same normal mix cycle. This is not a problem, as
2950 // the track never becomes active so it's fast mixer slot is never touched.
2951 // The converse, of removing an (active) track and then creating a new track
2952 // at the identical fast mixer slot within the same normal mix cycle,
2953 // is impossible because the slot isn't marked available until the end of each cycle.
2954 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002955 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2956 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002957 FastTrack *fastTrack = &state->mFastTracks[j];
2958
2959 // Determine whether the track is currently in underrun condition,
2960 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002961 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2962 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002963 uint32_t recentFull = (underruns.mBitFields.mFull -
2964 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2965 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2966 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2967 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2968 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2969 uint32_t recentUnderruns = recentPartial + recentEmpty;
2970 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002971 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002972 // or stopped which can occur when flush() is called while active
2973 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002974 track->mUnderrunCount += recentUnderruns;
2975 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002976
Glenn Kastend08f48c2012-05-01 18:14:02 -07002977 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002978 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002979 bool isActive = true;
2980 switch (track->mState) {
2981 case TrackBase::STOPPING_1:
2982 // track stays active in STOPPING_1 state until first underrun
2983 if (recentUnderruns > 0) {
2984 track->mState = TrackBase::STOPPING_2;
2985 }
2986 break;
2987 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002988 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002989 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002990 break;
2991 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002992 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002993 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002994 break;
2995 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002996 if (recentFull > 0 || recentPartial > 0) {
2997 // track has provided at least some frames recently: reset retry count
2998 track->mRetryCount = kMaxTrackRetries;
2999 }
3000 if (recentUnderruns == 0) {
3001 // no recent underruns: stay active
3002 break;
3003 }
3004 // there has recently been an underrun of some kind
3005 if (track->sharedBuffer() == 0) {
3006 // were any of the recent underruns "empty" (no frames available)?
3007 if (recentEmpty == 0) {
3008 // no, then ignore the partial underruns as they are allowed indefinitely
3009 break;
3010 }
3011 // there has recently been an "empty" underrun: decrement the retry counter
3012 if (--(track->mRetryCount) > 0) {
3013 break;
3014 }
3015 // indicate to client process that the track was disabled because of underrun;
3016 // it will then automatically call start() when data is available
3017 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
3018 // remove from active list, but state remains ACTIVE [confusing but true]
3019 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003020 break;
3021 }
3022 // fall through
3023 case TrackBase::STOPPING_2:
3024 case TrackBase::PAUSED:
3025 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07003026 case TrackBase::STOPPED:
3027 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07003028 // Check for presentation complete if track is inactive
3029 // We have consumed all the buffers of this track.
3030 // This would be incomplete if we auto-paused on underrun
3031 {
3032 size_t audioHALFrames =
3033 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3034 size_t framesWritten =
3035 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003036 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
Glenn Kastend08f48c2012-05-01 18:14:02 -07003037 // track stays in active list until presentation is complete
3038 break;
3039 }
3040 }
3041 if (track->isStopping_2()) {
3042 track->mState = TrackBase::STOPPED;
3043 }
3044 if (track->isStopped()) {
3045 // Can't reset directly, as fast mixer is still polling this track
3046 // track->reset();
3047 // So instead mark this track as needing to be reset after push with ack
3048 resetMask |= 1 << i;
3049 }
3050 isActive = false;
3051 break;
3052 case TrackBase::IDLE:
3053 default:
3054 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003055 }
3056
3057 if (isActive) {
3058 // was it previously inactive?
3059 if (!(state->mTrackMask & (1 << j))) {
3060 ExtendedAudioBufferProvider *eabp = track;
3061 VolumeProvider *vp = track;
3062 fastTrack->mBufferProvider = eabp;
3063 fastTrack->mVolumeProvider = vp;
3064 fastTrack->mSampleRate = track->mSampleRate;
3065 fastTrack->mChannelMask = track->mChannelMask;
3066 fastTrack->mGeneration++;
3067 state->mTrackMask |= 1 << j;
3068 didModify = true;
3069 // no acknowledgement required for newly active tracks
3070 }
3071 // cache the combined master volume and stream type volume for fast mixer; this
3072 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3073 track->mCachedVolume = track->isMuted() ?
3074 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3075 ++fastTracks;
3076 } else {
3077 // was it previously active?
3078 if (state->mTrackMask & (1 << j)) {
3079 fastTrack->mBufferProvider = NULL;
3080 fastTrack->mGeneration++;
3081 state->mTrackMask &= ~(1 << j);
3082 didModify = true;
3083 // If any fast tracks were removed, we must wait for acknowledgement
3084 // because we're about to decrement the last sp<> on those tracks.
3085 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003086 } else {
3087 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003088 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003089 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003090 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003091 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003092 }
3093 continue;
3094 }
3095
3096 { // local variable scope to avoid goto warning
3097
Mathias Agopian65ab4712010-07-14 17:59:35 -07003098 audio_track_cblk_t* cblk = track->cblk();
3099
3100 // The first time a track is added we wait
3101 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003102 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003103 // make sure that we have enough frames to mix one full buffer.
3104 // enforce this condition only once to enable draining the buffer in case the client
3105 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003106 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003107 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003108 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003109 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003110 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003111 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003112 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003113 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003114 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003115 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003116 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003117 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003118 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3119 // the minimum track buffer size is normally twice the number of frames necessary
3120 // to fill one buffer and the resampler should not leave more than one buffer worth
3121 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003122 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003123 }
3124 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003125 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003126 !track->isPaused() && !track->isTerminated())
3127 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003128 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003129
3130 mixedTracks++;
3131
3132 // track->mainBuffer() != mMixBuffer means there is an effect chain
3133 // connected to the track
3134 chain.clear();
3135 if (track->mainBuffer() != mMixBuffer) {
3136 chain = getEffectChain_l(track->sessionId());
3137 // Delegate volume control to effect in track effect chain if needed
3138 if (chain != 0) {
3139 tracksWithEffect++;
3140 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003141 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003142 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003143 }
3144 }
3145
3146
3147 int param = AudioMixer::VOLUME;
3148 if (track->mFillingUpStatus == Track::FS_FILLED) {
3149 // no ramp for the first volume setting
3150 track->mFillingUpStatus = Track::FS_ACTIVE;
3151 if (track->mState == TrackBase::RESUMING) {
3152 track->mState = TrackBase::ACTIVE;
3153 param = AudioMixer::RAMP_VOLUME;
3154 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003155 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003156 } else if (cblk->server != 0) {
3157 // If the track is stopped before the first frame was mixed,
3158 // do not apply ramp
3159 param = AudioMixer::RAMP_VOLUME;
3160 }
3161
3162 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003163 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003164 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003165 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003166 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003167 if (track->isPausing()) {
3168 track->setPaused();
3169 }
3170 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003171
Mathias Agopian65ab4712010-07-14 17:59:35 -07003172 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003173 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003174 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003175 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003176 vl = vlr & 0xFFFF;
3177 vr = vlr >> 16;
3178 // track volumes come from shared memory, so can't be trusted and must be clamped
3179 if (vl > MAX_GAIN_INT) {
3180 ALOGV("Track left volume out of range: %04X", vl);
3181 vl = MAX_GAIN_INT;
3182 }
3183 if (vr > MAX_GAIN_INT) {
3184 ALOGV("Track right volume out of range: %04X", vr);
3185 vr = MAX_GAIN_INT;
3186 }
3187 // now apply the master volume and stream type volume
3188 vl = (uint32_t)(v * vl) << 12;
3189 vr = (uint32_t)(v * vr) << 12;
3190 // assuming master volume and stream type volume each go up to 1.0,
3191 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003192
Glenn Kasten05632a52012-01-03 14:22:33 -08003193 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3194 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003195 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003196 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003197 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003198 }
3199 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003200 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003201 // Delegate volume control to effect in track effect chain if needed
3202 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3203 // Do not ramp volume if volume is controlled by effect
3204 param = AudioMixer::VOLUME;
3205 track->mHasVolumeController = true;
3206 } else {
3207 // force no volume ramp when volume controller was just disabled or removed
3208 // from effect chain to avoid volume spike
3209 if (track->mHasVolumeController) {
3210 param = AudioMixer::VOLUME;
3211 }
3212 track->mHasVolumeController = false;
3213 }
3214
3215 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003216 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003217 vl = (vl + (1 << 11)) >> 12;
3218 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3219 vr = (vr + (1 << 11)) >> 12;
3220 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003221
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003222 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 -07003223
Mathias Agopian65ab4712010-07-14 17:59:35 -07003224 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003225 mAudioMixer->setBufferProvider(name, track);
3226 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003227
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003228 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3229 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3230 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003231 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003232 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003233 AudioMixer::TRACK,
3234 AudioMixer::FORMAT, (void *)track->format());
3235 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003236 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003237 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003238 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003239 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003240 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003241 AudioMixer::RESAMPLE,
3242 AudioMixer::SAMPLE_RATE,
3243 (void *)(cblk->sampleRate));
3244 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003245 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003246 AudioMixer::TRACK,
3247 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3248 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003249 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003250 AudioMixer::TRACK,
3251 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3252
3253 // reset retry count
3254 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003255
Eric Laurent27741442012-01-17 19:20:12 -08003256 // If one track is ready, set the mixer ready if:
3257 // - the mixer was not ready during previous round OR
3258 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003259 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003260 mixerStatus != MIXER_TRACKS_ENABLED) {
3261 mixerStatus = MIXER_TRACKS_READY;
3262 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003263 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003264 // clear effect chain input buffer if an active track underruns to avoid sending
3265 // previous audio buffer again to effects
3266 chain = getEffectChain_l(track->sessionId());
3267 if (chain != 0) {
3268 chain->clearInputBuffer();
3269 }
3270
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003271 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Glenn Kasten842c5d92012-09-26 08:34:10 -07003272 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent83faee02012-04-27 18:24:29 -07003273 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003274 // We have consumed all the buffers of this track.
3275 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003276 // TODO: use actual buffer filling status instead of latency when available from
3277 // audio HAL
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07003278 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07003279 size_t framesWritten =
3280 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003281 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003282 if (track->isStopped()) {
3283 track->reset();
3284 }
Eric Laurenta011e352012-03-29 15:51:43 -07003285 tracksToRemove->add(track);
3286 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003287 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003288 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003289 // No buffers for this track. Give it a few chances to
3290 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07003291 if (--(track->mRetryCount) <= 0) {
3292 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003293 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003294 // indicate to client process that the track was disabled because of underrun;
3295 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003296 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003297 // If one track is not ready, mark the mixer also not ready if:
3298 // - the mixer was ready during previous round OR
3299 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003300 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003301 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003302 mixerStatus = MIXER_TRACKS_ENABLED;
3303 }
3304 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003305 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003306 }
Glenn Kasten58912562012-04-03 10:45:00 -07003307
3308 } // local variable scope to avoid goto warning
3309track_is_ready: ;
3310
Mathias Agopian65ab4712010-07-14 17:59:35 -07003311 }
3312
Glenn Kasten288ed212012-04-25 17:52:27 -07003313 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003314 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003315 if (didModify) {
3316 state->mFastTracksGen++;
3317 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3318 if (kUseFastMixer == FastMixer_Dynamic &&
3319 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3320 state->mCommand = FastMixerState::COLD_IDLE;
3321 state->mColdFutexAddr = &mFastMixerFutex;
3322 state->mColdGen++;
3323 mFastMixerFutex = 0;
3324 if (kUseFastMixer == FastMixer_Dynamic) {
3325 mNormalSink = mOutputSink;
3326 }
3327 // If we go into cold idle, need to wait for acknowledgement
3328 // so that fast mixer stops doing I/O.
3329 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003330 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003331 }
3332 sq->end();
3333 }
3334 if (sq != NULL) {
3335 sq->end(didModify);
3336 sq->push(block);
3337 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003338#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003339 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3340 mAudioWatchdog->pause();
3341 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003342#endif
Glenn Kasten288ed212012-04-25 17:52:27 -07003343
3344 // Now perform the deferred reset on fast tracks that have stopped
3345 while (resetMask != 0) {
3346 size_t i = __builtin_ctz(resetMask);
3347 ALOG_ASSERT(i < count);
3348 resetMask &= ~(1 << i);
3349 sp<Track> t = mActiveTracks[i].promote();
3350 if (t == 0) continue;
3351 Track* track = t.get();
3352 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3353 track->reset();
3354 }
Glenn Kasten58912562012-04-03 10:45:00 -07003355
Mathias Agopian65ab4712010-07-14 17:59:35 -07003356 // remove all the tracks that need to be...
3357 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003358 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003359 for (size_t i=0 ; i<count ; i++) {
3360 const sp<Track>& track = tracksToRemove->itemAt(i);
3361 mActiveTracks.remove(track);
3362 if (track->mainBuffer() != mMixBuffer) {
3363 chain = getEffectChain_l(track->sessionId());
3364 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003365 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003366 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003367 }
3368 }
3369 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003370 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003371 }
3372 }
3373 }
3374
3375 // mix buffer must be cleared if all tracks are connected to an
3376 // effect chain as in this case the mixer will not write to
3377 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003378 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3379 // FIXME as a performance optimization, should remember previous zero status
3380 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003381 }
3382
Glenn Kasten58912562012-04-03 10:45:00 -07003383 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003384 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003385 if (fastTracks > 0) {
3386 mixerStatus = MIXER_TRACKS_READY;
3387 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003388 return mixerStatus;
3389}
3390
Glenn Kasten66fcab92012-02-24 14:59:21 -08003391/*
3392The derived values that are cached:
3393 - mixBufferSize from frame count * frame size
3394 - activeSleepTime from activeSleepTimeUs()
3395 - idleSleepTime from idleSleepTimeUs()
3396 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3397 - maxPeriod from frame count and sample rate (MIXER only)
3398
3399The parameters that affect these derived values are:
3400 - frame count
3401 - frame size
3402 - sample rate
3403 - device type: A2DP or not
3404 - device latency
3405 - format: PCM or not
3406 - active sleep time
3407 - idle sleep time
3408*/
3409
3410void AudioFlinger::PlaybackThread::cacheParameters_l()
3411{
Glenn Kasten58912562012-04-03 10:45:00 -07003412 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003413 activeSleepTime = activeSleepTimeUs();
3414 idleSleepTime = idleSleepTimeUs();
3415}
3416
Eric Laurent22167852012-06-20 12:26:32 -07003417void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003418{
Steve Block3856b092011-10-20 11:56:00 +01003419 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003420 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003421 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003422
Mathias Agopian65ab4712010-07-14 17:59:35 -07003423 size_t size = mTracks.size();
3424 for (size_t i = 0; i < size; i++) {
3425 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003426 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003427 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003428 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003429 }
3430 }
3431}
3432
Mathias Agopian65ab4712010-07-14 17:59:35 -07003433// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003434int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003435{
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003436 return mAudioMixer->getTrackName(channelMask, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003437}
3438
3439// deleteTrackName_l() must be called with ThreadBase::mLock held
3440void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3441{
Steve Block3856b092011-10-20 11:56:00 +01003442 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003443 mAudioMixer->deleteTrackName(name);
3444}
3445
3446// checkForNewParameters_l() must be called with ThreadBase::mLock held
3447bool AudioFlinger::MixerThread::checkForNewParameters_l()
3448{
Glenn Kasten58912562012-04-03 10:45:00 -07003449 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3450 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003451 bool reconfig = false;
3452
3453 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003454
3455 if (mFastMixer != NULL) {
3456 FastMixerStateQueue *sq = mFastMixer->sq();
3457 FastMixerState *state = sq->begin();
3458 if (!(state->mCommand & FastMixerState::IDLE)) {
3459 previousCommand = state->mCommand;
3460 state->mCommand = FastMixerState::HOT_IDLE;
3461 sq->end();
3462 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3463 } else {
3464 sq->end(false /*didModify*/);
3465 }
3466 }
3467
Mathias Agopian65ab4712010-07-14 17:59:35 -07003468 status_t status = NO_ERROR;
3469 String8 keyValuePair = mNewParameters[0];
3470 AudioParameter param = AudioParameter(keyValuePair);
3471 int value;
3472
3473 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3474 reconfig = true;
3475 }
3476 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003477 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003478 status = BAD_VALUE;
3479 } else {
3480 reconfig = true;
3481 }
3482 }
3483 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003484 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003485 status = BAD_VALUE;
3486 } else {
3487 reconfig = true;
3488 }
3489 }
3490 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3491 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003492 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493 // if frame count is changed after track creation
3494 if (!mTracks.isEmpty()) {
3495 status = INVALID_OPERATION;
3496 } else {
3497 reconfig = true;
3498 }
3499 }
3500 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003501#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003502 // when changing the audio output device, call addBatteryData to notify
3503 // the change
Eric Laurentf1c04f92012-08-28 14:26:53 -07003504 if (mOutDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003505 uint32_t params = 0;
3506 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003507 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003508 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3509 }
3510
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003511 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003512 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003513 // check if any other device (except speaker) is on
3514 if (value & deviceWithoutSpeaker ) {
3515 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3516 }
3517
3518 if (params != 0) {
3519 addBatteryData(params);
3520 }
3521 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003522#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003523
Mathias Agopian65ab4712010-07-14 17:59:35 -07003524 // forward device change to effects that have requested to be
3525 // aware of attached audio device.
Eric Laurentf1c04f92012-08-28 14:26:53 -07003526 mOutDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003527 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07003528 mEffectChains[i]->setDevice_l(mOutDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003529 }
3530 }
3531
3532 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003533 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003534 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003535 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003536 mOutput->stream->common.standby(&mOutput->stream->common);
3537 mStandby = true;
3538 mBytesWritten = 0;
3539 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003540 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003541 }
3542 if (status == NO_ERROR && reconfig) {
3543 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003544 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3545 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003546 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003547 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003548 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003549 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003550 if (name < 0) break;
3551 mTracks[i]->mName = name;
3552 // limit track sample rate to 2 x new output sample rate
3553 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3554 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3555 }
3556 }
Eric Laurent896adcd2012-09-13 11:18:23 -07003557 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003558 }
3559 }
3560
3561 mNewParameters.removeAt(0);
3562
3563 mParamStatus = status;
3564 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003565 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3566 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003567 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003568 }
Glenn Kasten58912562012-04-03 10:45:00 -07003569
3570 if (!(previousCommand & FastMixerState::IDLE)) {
3571 ALOG_ASSERT(mFastMixer != NULL);
3572 FastMixerStateQueue *sq = mFastMixer->sq();
3573 FastMixerState *state = sq->begin();
3574 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3575 state->mCommand = previousCommand;
3576 sq->end();
3577 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3578 }
3579
Mathias Agopian65ab4712010-07-14 17:59:35 -07003580 return reconfig;
3581}
3582
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07003583void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003584{
3585 const size_t SIZE = 256;
3586 char buffer[SIZE];
3587 String8 result;
3588
3589 PlaybackThread::dumpInternals(fd, args);
3590
3591 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3592 result.append(buffer);
3593 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003594
3595 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3596 FastMixerDumpState copy = mFastMixerDumpState;
3597 copy.dump(fd);
3598
Glenn Kasten39993082012-05-31 13:40:27 -07003599#ifdef STATE_QUEUE_DUMP
3600 // Similar for state queue
3601 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3602 observerCopy.dump(fd);
3603 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3604 mutatorCopy.dump(fd);
3605#endif
3606
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003607 // Write the tee output to a .wav file
3608 NBAIO_Source *teeSource = mTeeSource.get();
3609 if (teeSource != NULL) {
3610 char teePath[64];
3611 struct timeval tv;
3612 gettimeofday(&tv, NULL);
3613 struct tm tm;
3614 localtime_r(&tv.tv_sec, &tm);
3615 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3616 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3617 if (teeFd >= 0) {
3618 char wavHeader[44];
3619 memcpy(wavHeader,
3620 "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",
3621 sizeof(wavHeader));
3622 NBAIO_Format format = teeSource->format();
3623 unsigned channelCount = Format_channelCount(format);
3624 ALOG_ASSERT(channelCount <= FCC_2);
3625 unsigned sampleRate = Format_sampleRate(format);
3626 wavHeader[22] = channelCount; // number of channels
3627 wavHeader[24] = sampleRate; // sample rate
3628 wavHeader[25] = sampleRate >> 8;
3629 wavHeader[32] = channelCount * 2; // block alignment
3630 write(teeFd, wavHeader, sizeof(wavHeader));
3631 size_t total = 0;
3632 bool firstRead = true;
3633 for (;;) {
3634#define TEE_SINK_READ 1024
3635 short buffer[TEE_SINK_READ * FCC_2];
3636 size_t count = TEE_SINK_READ;
John Grossman2c3b2da2012-08-02 17:08:54 -07003637 ssize_t actual = teeSource->read(buffer, count,
3638 AudioBufferProvider::kInvalidPTS);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003639 bool wasFirstRead = firstRead;
3640 firstRead = false;
3641 if (actual <= 0) {
3642 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3643 continue;
3644 }
3645 break;
3646 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003647 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003648 write(teeFd, buffer, actual * channelCount * sizeof(short));
3649 total += actual;
3650 }
3651 lseek(teeFd, (off_t) 4, SEEK_SET);
3652 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3653 write(teeFd, &temp, sizeof(temp));
3654 lseek(teeFd, (off_t) 40, SEEK_SET);
3655 temp = total * channelCount * sizeof(short);
3656 write(teeFd, &temp, sizeof(temp));
3657 close(teeFd);
3658 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3659 } else {
3660 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3661 }
3662 }
3663
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003664#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003665 if (mAudioWatchdog != 0) {
3666 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3667 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3668 wdCopy.dump(fd);
3669 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003670#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003671}
3672
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003673uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003674{
Glenn Kasten58912562012-04-03 10:45:00 -07003675 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003676}
3677
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003678uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003679{
Glenn Kasten58912562012-04-03 10:45:00 -07003680 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003681}
3682
Glenn Kasten66fcab92012-02-24 14:59:21 -08003683void AudioFlinger::MixerThread::cacheParameters_l()
3684{
3685 PlaybackThread::cacheParameters_l();
3686
3687 // FIXME: Relaxed timing because of a certain device that can't meet latency
3688 // Should be reduced to 2x after the vendor fixes the driver issue
3689 // increase threshold again due to low power audio mode. The way this warning
3690 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003691 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003692}
3693
Mathias Agopian65ab4712010-07-14 17:59:35 -07003694// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003695AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003696 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003697 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003698 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003699{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003700}
3701
3702AudioFlinger::DirectOutputThread::~DirectOutputThread()
3703{
3704}
3705
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003706AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3707 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003708)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003709{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003710 sp<Track> trackToRemove;
3711
Glenn Kastenfec279f2012-03-08 07:47:15 -08003712 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003713
Glenn Kasten952eeb22012-03-06 11:30:57 -08003714 // find out which tracks need to be processed
3715 if (mActiveTracks.size() != 0) {
3716 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003717 // The track died recently
3718 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003719
Glenn Kasten952eeb22012-03-06 11:30:57 -08003720 Track* const track = t.get();
3721 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003722
Glenn Kasten952eeb22012-03-06 11:30:57 -08003723 // The first time a track is added we wait
3724 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003725 uint32_t minFrames;
3726 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3727 minFrames = mNormalFrameCount;
3728 } else {
3729 minFrames = 1;
3730 }
3731 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003732 !track->isPaused() && !track->isTerminated())
3733 {
3734 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003735
Glenn Kasten952eeb22012-03-06 11:30:57 -08003736 if (track->mFillingUpStatus == Track::FS_FILLED) {
3737 track->mFillingUpStatus = Track::FS_ACTIVE;
3738 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003739 if (track->mState == TrackBase::RESUMING) {
3740 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003741 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003742 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003743
Glenn Kasten952eeb22012-03-06 11:30:57 -08003744 // compute volume for this track
3745 float left, right;
3746 if (track->isMuted() || mMasterMute || track->isPausing() ||
3747 mStreamTypes[track->streamType()].mute) {
3748 left = right = 0;
3749 if (track->isPausing()) {
3750 track->setPaused();
3751 }
3752 } else {
3753 float typeVolume = mStreamTypes[track->streamType()].volume;
3754 float v = mMasterVolume * typeVolume;
3755 uint32_t vlr = cblk->getVolumeLR();
3756 float v_clamped = v * (vlr & 0xFFFF);
3757 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3758 left = v_clamped/MAX_GAIN;
3759 v_clamped = v * (vlr >> 16);
3760 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3761 right = v_clamped/MAX_GAIN;
3762 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003763
Glenn Kasten952eeb22012-03-06 11:30:57 -08003764 if (left != mLeftVolFloat || right != mRightVolFloat) {
3765 mLeftVolFloat = left;
3766 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003767
Glenn Kasten952eeb22012-03-06 11:30:57 -08003768 // Convert volumes from float to 8.24
3769 uint32_t vl = (uint32_t)(left * (1 << 24));
3770 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003771
Glenn Kasten952eeb22012-03-06 11:30:57 -08003772 // Delegate volume control to effect in track effect chain if needed
3773 // only one effect chain can be present on DirectOutputThread, so if
3774 // there is one, the track is connected to it
3775 if (!mEffectChains.isEmpty()) {
3776 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003777 mEffectChains[0]->setVolume_l(&vl, &vr);
3778 left = (float)vl / (1 << 24);
3779 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003780 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003781 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003782 }
3783
3784 // reset retry count
3785 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003786 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003787 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003788 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003789 // clear effect chain input buffer if an active track underruns to avoid sending
3790 // previous audio buffer again to effects
3791 if (!mEffectChains.isEmpty()) {
3792 mEffectChains[0]->clearInputBuffer();
3793 }
3794
Glenn Kasten952eeb22012-03-06 11:30:57 -08003795 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten842c5d92012-09-26 08:34:10 -07003796 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent67c0a582012-05-01 19:31:12 -07003797 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003798 // We have consumed all the buffers of this track.
3799 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003800 // TODO: implement behavior for compressed audio
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07003801 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07003802 size_t framesWritten =
3803 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003804 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003805 if (track->isStopped()) {
3806 track->reset();
3807 }
Eric Laurenta011e352012-03-29 15:51:43 -07003808 trackToRemove = track;
3809 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003810 } else {
3811 // No buffers for this track. Give it a few chances to
3812 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07003813 if (--(track->mRetryCount) <= 0) {
3814 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Glenn Kasten952eeb22012-03-06 11:30:57 -08003815 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003816 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003817 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003818 }
3819 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003820 }
3821 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003822
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003823 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003824 // remove all the tracks that need to be...
3825 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003826 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003827 mActiveTracks.remove(trackToRemove);
3828 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003829 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003830 trackToRemove->sessionId());
3831 mEffectChains[0]->decActiveTrackCnt();
3832 }
3833 if (trackToRemove->isTerminated()) {
3834 removeTrack_l(trackToRemove);
3835 }
3836 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003837
Glenn Kastenfec279f2012-03-08 07:47:15 -08003838 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003839}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003840
Glenn Kasten000f0e32012-03-01 17:10:56 -08003841void AudioFlinger::DirectOutputThread::threadLoop_mix()
3842{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003843 AudioBufferProvider::Buffer buffer;
3844 size_t frameCount = mFrameCount;
3845 int8_t *curBuf = (int8_t *)mMixBuffer;
3846 // output audio to hardware
3847 while (frameCount) {
3848 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003849 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003850 if (CC_UNLIKELY(buffer.raw == NULL)) {
3851 memset(curBuf, 0, frameCount * mFrameSize);
3852 break;
3853 }
3854 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3855 frameCount -= buffer.frameCount;
3856 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003857 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003858 }
3859 sleepTime = 0;
3860 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003861 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003862
Glenn Kasten000f0e32012-03-01 17:10:56 -08003863}
3864
3865void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3866{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003867 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003868 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003869 sleepTime = activeSleepTime;
3870 } else {
3871 sleepTime = idleSleepTime;
3872 }
3873 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003874 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003875 sleepTime = 0;
3876 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003877}
3878
3879// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003880int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3881 int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003882{
3883 return 0;
3884}
3885
3886// deleteTrackName_l() must be called with ThreadBase::mLock held
3887void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3888{
3889}
3890
3891// checkForNewParameters_l() must be called with ThreadBase::mLock held
3892bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3893{
3894 bool reconfig = false;
3895
3896 while (!mNewParameters.isEmpty()) {
3897 status_t status = NO_ERROR;
3898 String8 keyValuePair = mNewParameters[0];
3899 AudioParameter param = AudioParameter(keyValuePair);
3900 int value;
3901
3902 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3903 // do not accept frame count changes if tracks are open as the track buffer
3904 // size depends on frame count and correct behavior would not be garantied
3905 // if frame count is changed after track creation
3906 if (!mTracks.isEmpty()) {
3907 status = INVALID_OPERATION;
3908 } else {
3909 reconfig = true;
3910 }
3911 }
3912 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003913 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003914 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003915 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003916 mOutput->stream->common.standby(&mOutput->stream->common);
3917 mStandby = true;
3918 mBytesWritten = 0;
3919 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003920 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003921 }
3922 if (status == NO_ERROR && reconfig) {
3923 readOutputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07003924 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003925 }
3926 }
3927
3928 mNewParameters.removeAt(0);
3929
3930 mParamStatus = status;
3931 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003932 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3933 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003934 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003935 }
3936 return reconfig;
3937}
3938
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003939uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003940{
3941 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003942 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003943 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003944 } else {
3945 time = 10000;
3946 }
3947 return time;
3948}
3949
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003950uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003951{
3952 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003953 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003954 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003955 } else {
3956 time = 10000;
3957 }
3958 return time;
3959}
3960
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003961uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003962{
3963 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003964 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003965 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3966 } else {
3967 time = 10000;
3968 }
3969 return time;
3970}
3971
Glenn Kasten66fcab92012-02-24 14:59:21 -08003972void AudioFlinger::DirectOutputThread::cacheParameters_l()
3973{
3974 PlaybackThread::cacheParameters_l();
3975
3976 // use shorter standby delay as on normal output to release
3977 // hardware resources as soon as possible
3978 standbyDelay = microseconds(activeSleepTime*2);
3979}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003980
Mathias Agopian65ab4712010-07-14 17:59:35 -07003981// ----------------------------------------------------------------------------
3982
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003983AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003984 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Eric Laurentf1c04f92012-08-28 14:26:53 -07003985 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), DUPLICATING),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003986 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003987{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003988 addOutputTrack(mainThread);
3989}
3990
3991AudioFlinger::DuplicatingThread::~DuplicatingThread()
3992{
3993 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3994 mOutputTracks[i]->destroy();
3995 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003996}
3997
Glenn Kasten000f0e32012-03-01 17:10:56 -08003998void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003999{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004000 // mix buffers...
4001 if (outputsReady(outputTracks)) {
4002 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4003 } else {
4004 memset(mMixBuffer, 0, mixBufferSize);
4005 }
4006 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07004007 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004008 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004009}
4010
4011void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4012{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004013 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004014 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004015 sleepTime = activeSleepTime;
4016 } else {
4017 sleepTime = idleSleepTime;
4018 }
4019 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004020 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4021 writeFrames = mNormalFrameCount;
4022 memset(mMixBuffer, 0, mixBufferSize);
4023 } else {
4024 // flush remaining overflow buffers in output tracks
4025 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004026 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004027 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004028 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08004029}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004030
Glenn Kasten000f0e32012-03-01 17:10:56 -08004031void AudioFlinger::DuplicatingThread::threadLoop_write()
4032{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004033 for (size_t i = 0; i < outputTracks.size(); i++) {
4034 outputTracks[i]->write(mMixBuffer, writeFrames);
4035 }
4036 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004037}
Glenn Kasten688a6402012-02-29 07:57:06 -08004038
Glenn Kasten000f0e32012-03-01 17:10:56 -08004039void AudioFlinger::DuplicatingThread::threadLoop_standby()
4040{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004041 // DuplicatingThread implements standby by stopping all tracks
4042 for (size_t i = 0; i < outputTracks.size(); i++) {
4043 outputTracks[i]->stop();
4044 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004045}
4046
Glenn Kastenfa26a852012-03-06 11:28:04 -08004047void AudioFlinger::DuplicatingThread::saveOutputTracks()
4048{
4049 outputTracks = mOutputTracks;
4050}
4051
4052void AudioFlinger::DuplicatingThread::clearOutputTracks()
4053{
4054 outputTracks.clear();
4055}
4056
Mathias Agopian65ab4712010-07-14 17:59:35 -07004057void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4058{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004059 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004060 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004061 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004062 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004063 this,
4064 mSampleRate,
4065 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004066 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004067 frameCount);
4068 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004069 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004070 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004071 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004072 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004073 }
4074}
4075
4076void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4077{
4078 Mutex::Autolock _l(mLock);
4079 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004080 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004081 mOutputTracks[i]->destroy();
4082 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004083 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004084 return;
4085 }
4086 }
Steve Block3856b092011-10-20 11:56:00 +01004087 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004088}
4089
Glenn Kasten438b0362012-03-06 11:24:48 -08004090// caller must hold mLock
4091void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004092{
4093 mWaitTimeMs = UINT_MAX;
4094 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4095 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004096 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004097 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4098 if (waitTimeMs < mWaitTimeMs) {
4099 mWaitTimeMs = waitTimeMs;
4100 }
4101 }
4102 }
4103}
4104
4105
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004106bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004107{
4108 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004109 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004110 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004111 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004112 return false;
4113 }
4114 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004115 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004116 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004117 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004118 return false;
4119 }
4120 }
4121 return true;
4122}
4123
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004124uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004125{
4126 return (mWaitTimeMs * 1000) / 2;
4127}
4128
Glenn Kasten66fcab92012-02-24 14:59:21 -08004129void AudioFlinger::DuplicatingThread::cacheParameters_l()
4130{
4131 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4132 updateWaitTime_l();
4133
4134 MixerThread::cacheParameters_l();
4135}
4136
Mathias Agopian65ab4712010-07-14 17:59:35 -07004137// ----------------------------------------------------------------------------
4138
4139// TrackBase constructor must be called with AudioFlinger::mLock held
4140AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004141 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004142 const sp<Client>& client,
4143 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004144 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004145 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004146 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004147 const sp<IMemory>& sharedBuffer,
4148 int sessionId)
4149 : RefBase(),
4150 mThread(thread),
4151 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004152 mCblk(NULL),
4153 // mBuffer
4154 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004155 mFrameCount(0),
4156 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004157 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004158 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004159 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004160 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004161 // mChannelCount
4162 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004163{
Steve Block3856b092011-10-20 11:56:00 +01004164 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004165
Steve Blockb8a80522011-12-20 16:23:08 +00004166 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004167 size_t size = sizeof(audio_track_cblk_t);
4168 uint8_t channelCount = popcount(channelMask);
4169 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4170 if (sharedBuffer == 0) {
4171 size += bufferSize;
4172 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004173
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004174 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004175 mCblkMemory = client->heap()->allocate(size);
4176 if (mCblkMemory != 0) {
4177 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004178 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004179 new(mCblk) audio_track_cblk_t();
4180 // clear all buffers
4181 mCblk->frameCount = frameCount;
4182 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004183// uncomment the following lines to quickly test 32-bit wraparound
4184// mCblk->user = 0xffff0000;
4185// mCblk->server = 0xffff0000;
4186// mCblk->userBase = 0xffff0000;
4187// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004188 mChannelCount = channelCount;
4189 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004190 if (sharedBuffer == 0) {
4191 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4192 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4193 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004194 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004195 mCblk->flags = CBLK_UNDERRUN_ON;
4196 } else {
4197 mBuffer = sharedBuffer->pointer();
4198 }
4199 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4200 }
4201 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004202 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203 client->heap()->dump("AudioTrack");
4204 return;
4205 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004206 } else {
4207 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004208 // construct the shared structure in-place.
4209 new(mCblk) audio_track_cblk_t();
4210 // clear all buffers
4211 mCblk->frameCount = frameCount;
4212 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004213// uncomment the following lines to quickly test 32-bit wraparound
4214// mCblk->user = 0xffff0000;
4215// mCblk->server = 0xffff0000;
4216// mCblk->userBase = 0xffff0000;
4217// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004218 mChannelCount = channelCount;
4219 mChannelMask = channelMask;
4220 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4221 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4222 // Force underrun condition to avoid false underrun callback until first data is
4223 // written to buffer (other flags are cleared)
4224 mCblk->flags = CBLK_UNDERRUN_ON;
4225 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004226 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004227}
4228
4229AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4230{
Glenn Kastena0d68332012-01-27 16:47:15 -08004231 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004232 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004233 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004234 } else {
4235 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004236 }
4237 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004238 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004239 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004240 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004241 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004242 // If the client's reference count drops to zero, the associated destructor
4243 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4244 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004245 mClient.clear();
4246 }
4247}
4248
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004249// AudioBufferProvider interface
4250// getNextBuffer() = 0;
4251// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004252void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4253{
Glenn Kastene0feee32011-12-13 11:53:26 -08004254 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004255 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004256 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004257 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004258 buffer->frameCount = 0;
4259}
4260
4261bool AudioFlinger::ThreadBase::TrackBase::step() {
4262 bool result;
4263 audio_track_cblk_t* cblk = this->cblk();
4264
4265 result = cblk->stepServer(mFrameCount);
4266 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004267 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004268 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004269 }
4270 return result;
4271}
4272
4273void AudioFlinger::ThreadBase::TrackBase::reset() {
4274 audio_track_cblk_t* cblk = this->cblk();
4275
4276 cblk->user = 0;
4277 cblk->server = 0;
4278 cblk->userBase = 0;
4279 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004280 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004281 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004282}
4283
Mathias Agopian65ab4712010-07-14 17:59:35 -07004284int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4285 return (int)mCblk->sampleRate;
4286}
4287
Mathias Agopian65ab4712010-07-14 17:59:35 -07004288void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4289 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004290 size_t frameSize = cblk->frameSize;
4291 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4292 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004293
4294 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004295 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4296 "TrackBase::getBuffer buffer out of range:\n"
4297 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4298 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004299 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004300 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004301
4302 return bufferStart;
4303}
4304
Eric Laurenta011e352012-03-29 15:51:43 -07004305status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4306{
4307 mSyncEvents.add(event);
4308 return NO_ERROR;
4309}
4310
Mathias Agopian65ab4712010-07-14 17:59:35 -07004311// ----------------------------------------------------------------------------
4312
4313// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4314AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004315 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004316 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004317 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004318 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004319 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004320 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004321 int frameCount,
4322 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004323 int sessionId,
4324 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004325 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004326 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004327 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004328 // mRetryCount initialized later when needed
4329 mSharedBuffer(sharedBuffer),
4330 mStreamType(streamType),
4331 mName(-1), // see note below
4332 mMainBuffer(thread->mixBuffer()),
4333 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004334 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004335 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004336 mFlags(flags),
4337 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004338 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004339 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004340{
4341 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004342 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4343 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004344 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004345 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07004346 mName = thread->getTrackName_l(channelMask, sessionId);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004347 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004348 if (mName < 0) {
4349 ALOGE("no more track names available");
4350 return;
4351 }
4352 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004353 if (flags & IAudioFlinger::TRACK_FAST) {
4354 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4355 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4356 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004357 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004358 // FIXME This is too eager. We allocate a fast track index before the
4359 // fast track becomes active. Since fast tracks are a scarce resource,
4360 // this means we are potentially denying other more important fast tracks from
4361 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004362 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004363 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004364 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004365 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004366 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004367 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004368 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004369 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004370}
4371
4372AudioFlinger::PlaybackThread::Track::~Track()
4373{
Steve Block3856b092011-10-20 11:56:00 +01004374 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004375}
4376
4377void AudioFlinger::PlaybackThread::Track::destroy()
4378{
4379 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4380 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004381 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004382 // we must acquire a strong reference on this Track before locking mLock
4383 // here so that the destructor is called only when exiting this function.
4384 // On the other hand, as long as Track::destroy() is only called by
4385 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4386 // this Track with its member mTrack.
4387 sp<Track> keep(this);
4388 { // scope for mLock
4389 sp<ThreadBase> thread = mThread.promote();
4390 if (thread != 0) {
4391 if (!isOutputTrack()) {
4392 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004393 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004394
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004395#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004396 // to track the speaker usage
4397 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004398#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004399 }
4400 AudioSystem::releaseOutput(thread->id());
4401 }
4402 Mutex::Autolock _l(thread->mLock);
4403 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4404 playbackThread->destroyTrack_l(this);
4405 }
4406 }
4407}
4408
Glenn Kasten288ed212012-04-25 17:52:27 -07004409/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4410{
Glenn Kastene213c862012-04-25 13:46:15 -07004411 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 -07004412 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004413}
4414
Mathias Agopian65ab4712010-07-14 17:59:35 -07004415void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4416{
Glenn Kasten83d86532012-01-17 14:39:34 -08004417 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004418 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004419 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004420 } else {
4421 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4422 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004423 track_state state = mState;
4424 char stateChar;
4425 switch (state) {
4426 case IDLE:
4427 stateChar = 'I';
4428 break;
4429 case TERMINATED:
4430 stateChar = 'T';
4431 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004432 case STOPPING_1:
4433 stateChar = 's';
4434 break;
4435 case STOPPING_2:
4436 stateChar = '5';
4437 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004438 case STOPPED:
4439 stateChar = 'S';
4440 break;
4441 case RESUMING:
4442 stateChar = 'R';
4443 break;
4444 case ACTIVE:
4445 stateChar = 'A';
4446 break;
4447 case PAUSING:
4448 stateChar = 'p';
4449 break;
4450 case PAUSED:
4451 stateChar = 'P';
4452 break;
Eric Laurent29864602012-05-08 18:57:51 -07004453 case FLUSHED:
4454 stateChar = 'F';
4455 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004456 default:
4457 stateChar = '?';
4458 break;
4459 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004460 char nowInUnderrun;
4461 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4462 case UNDERRUN_FULL:
4463 nowInUnderrun = ' ';
4464 break;
4465 case UNDERRUN_PARTIAL:
4466 nowInUnderrun = '<';
4467 break;
4468 case UNDERRUN_EMPTY:
4469 nowInUnderrun = '*';
4470 break;
4471 default:
4472 nowInUnderrun = '?';
4473 break;
4474 }
Glenn Kastene213c862012-04-25 13:46:15 -07004475 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4476 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004477 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004478 mStreamType,
4479 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004480 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004481 mSessionId,
4482 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004483 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004484 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004485 mMute,
4486 mFillingUpStatus,
4487 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004488 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4489 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004490 mCblk->server,
4491 mCblk->user,
4492 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004493 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004494 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004495 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004496 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004497}
4498
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004499// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004500status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004501 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004502{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004503 audio_track_cblk_t* cblk = this->cblk();
4504 uint32_t framesReady;
4505 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004506
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004507 // Check if last stepServer failed, try to step now
4508 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004509 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4510 // Since the fast mixer is higher priority than client callback thread,
4511 // it does not result in priority inversion for client.
4512 // But a non-blocking solution would be preferable to avoid
4513 // fast mixer being unable to tryLock(), and
4514 // to avoid the extra context switches if the client wakes up,
4515 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004516 if (!step()) goto getNextBuffer_exit;
4517 ALOGV("stepServer recovered");
4518 mStepServerFailed = false;
4519 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004520
Glenn Kasten288ed212012-04-25 17:52:27 -07004521 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004522 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004523
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004524 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004525 uint32_t s = cblk->server;
4526 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4527
4528 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4529 if (framesReq > framesReady) {
4530 framesReq = framesReady;
4531 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004532 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004533 framesReq = bufferEnd - s;
4534 }
4535
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004536 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004537 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004538 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004539 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004540
4541getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004542 buffer->raw = NULL;
4543 buffer->frameCount = 0;
4544 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4545 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004546}
4547
Glenn Kasten288ed212012-04-25 17:52:27 -07004548// Note that framesReady() takes a mutex on the control block using tryLock().
4549// This could result in priority inversion if framesReady() is called by the normal mixer,
4550// as the normal mixer thread runs at lower
4551// priority than the client's callback thread: there is a short window within framesReady()
4552// during which the normal mixer could be preempted, and the client callback would block.
4553// Another problem can occur if framesReady() is called by the fast mixer:
4554// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4555// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4556size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004557 return mCblk->framesReady();
4558}
4559
Glenn Kasten288ed212012-04-25 17:52:27 -07004560// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004561bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004562 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004563
John Grossman4ff14ba2012-02-08 16:37:41 -08004564 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004565 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4566 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004567 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004568 return true;
4569 }
4570 return false;
4571}
4572
Glenn Kasten3acbd052012-02-28 10:39:56 -08004573status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004574 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004575{
4576 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004577 ALOGV("start(%d), calling pid %d session %d",
4578 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004579
Mathias Agopian65ab4712010-07-14 17:59:35 -07004580 sp<ThreadBase> thread = mThread.promote();
4581 if (thread != 0) {
4582 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004583 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004584 // here the track could be either new, or restarted
4585 // in both cases "unstop" the track
4586 if (mState == PAUSED) {
4587 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004588 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004589 } else {
4590 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004591 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004592 }
4593
4594 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4595 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004596 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004597 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004598
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004599#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004600 // to track the speaker usage
4601 if (status == NO_ERROR) {
4602 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4603 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004604#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004605 }
4606 if (status == NO_ERROR) {
4607 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4608 playbackThread->addTrack_l(this);
4609 } else {
4610 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004611 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004612 }
4613 } else {
4614 status = BAD_VALUE;
4615 }
4616 return status;
4617}
4618
4619void AudioFlinger::PlaybackThread::Track::stop()
4620{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004621 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004622 sp<ThreadBase> thread = mThread.promote();
4623 if (thread != 0) {
4624 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004625 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004626 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004627 // If the track is not active (PAUSED and buffers full), flush buffers
4628 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4629 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4630 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004631 mState = STOPPED;
4632 } else if (!isFastTrack()) {
4633 mState = STOPPED;
4634 } else {
4635 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4636 // and then to STOPPED and reset() when presentation is complete
4637 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004638 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004639 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004640 }
4641 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4642 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004643 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004644 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004645
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004646#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004647 // to track the speaker usage
4648 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004649#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004650 }
4651 }
4652}
4653
4654void AudioFlinger::PlaybackThread::Track::pause()
4655{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004656 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004657 sp<ThreadBase> thread = mThread.promote();
4658 if (thread != 0) {
4659 Mutex::Autolock _l(thread->mLock);
4660 if (mState == ACTIVE || mState == RESUMING) {
4661 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004662 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004663 if (!isOutputTrack()) {
4664 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004665 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004666 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004667
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004668#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004669 // to track the speaker usage
4670 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004671#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004672 }
4673 }
4674 }
4675}
4676
4677void AudioFlinger::PlaybackThread::Track::flush()
4678{
Steve Block3856b092011-10-20 11:56:00 +01004679 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004680 sp<ThreadBase> thread = mThread.promote();
4681 if (thread != 0) {
4682 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004683 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4684 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004685 return;
4686 }
4687 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004688 // FLUSHED state
4689 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004690 // do not reset the track if it is still in the process of being stopped or paused.
4691 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004692 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004693 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004694 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4695 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4696 reset();
4697 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004698 }
4699}
4700
4701void AudioFlinger::PlaybackThread::Track::reset()
4702{
4703 // Do not reset twice to avoid discarding data written just after a flush and before
4704 // the audioflinger thread detects the track is stopped.
4705 if (!mResetDone) {
4706 TrackBase::reset();
4707 // Force underrun condition to avoid false underrun callback until first data is
4708 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004709 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4710 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004711 mFillingUpStatus = FS_FILLING;
4712 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004713 if (mState == FLUSHED) {
4714 mState = IDLE;
4715 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004716 }
4717}
4718
4719void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4720{
4721 mMute = muted;
4722}
4723
Mathias Agopian65ab4712010-07-14 17:59:35 -07004724status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4725{
4726 status_t status = DEAD_OBJECT;
4727 sp<ThreadBase> thread = mThread.promote();
4728 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004729 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004730 sp<AudioFlinger> af = mClient->audioFlinger();
4731
4732 Mutex::Autolock _l(af->mLock);
4733
4734 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004735
Eric Laurent109347d2012-07-02 12:31:03 -07004736 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004737 Mutex::Autolock _dl(playbackThread->mLock);
4738 Mutex::Autolock _sl(srcThread->mLock);
4739 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4740 if (chain == 0) {
4741 return INVALID_OPERATION;
4742 }
4743
4744 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4745 if (effect == 0) {
4746 return INVALID_OPERATION;
4747 }
4748 srcThread->removeEffect_l(effect);
4749 playbackThread->addEffect_l(effect);
4750 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4751 if (effect->state() == EffectModule::ACTIVE ||
4752 effect->state() == EffectModule::STOPPING) {
4753 effect->start();
4754 }
4755
4756 sp<EffectChain> dstChain = effect->chain().promote();
4757 if (dstChain == 0) {
4758 srcThread->addEffect_l(effect);
4759 return INVALID_OPERATION;
4760 }
4761 AudioSystem::unregisterEffect(effect->id());
4762 AudioSystem::registerEffect(&effect->desc(),
4763 srcThread->id(),
4764 dstChain->strategy(),
4765 AUDIO_SESSION_OUTPUT_MIX,
4766 effect->id());
4767 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004768 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004769 }
4770 return status;
4771}
4772
4773void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4774{
4775 mAuxEffectId = EffectId;
4776 mAuxBuffer = buffer;
4777}
4778
Eric Laurenta011e352012-03-29 15:51:43 -07004779bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4780 size_t audioHalFrames)
4781{
4782 // a track is considered presented when the total number of frames written to audio HAL
4783 // corresponds to the number of frames written when presentationComplete() is called for the
4784 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4785 if (mPresentationCompleteFrames == 0) {
4786 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4787 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4788 mPresentationCompleteFrames, audioHalFrames);
4789 }
4790 if (framesWritten >= mPresentationCompleteFrames) {
4791 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4792 mSessionId, framesWritten);
4793 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004794 return true;
4795 }
4796 return false;
4797}
4798
4799void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4800{
4801 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4802 if (mSyncEvents[i]->type() == type) {
4803 mSyncEvents[i]->trigger();
4804 mSyncEvents.removeAt(i);
4805 i--;
4806 }
4807 }
4808}
4809
Glenn Kasten58912562012-04-03 10:45:00 -07004810// implement VolumeBufferProvider interface
4811
4812uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4813{
4814 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4815 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4816 uint32_t vlr = mCblk->getVolumeLR();
4817 uint32_t vl = vlr & 0xFFFF;
4818 uint32_t vr = vlr >> 16;
4819 // track volumes come from shared memory, so can't be trusted and must be clamped
4820 if (vl > MAX_GAIN_INT) {
4821 vl = MAX_GAIN_INT;
4822 }
4823 if (vr > MAX_GAIN_INT) {
4824 vr = MAX_GAIN_INT;
4825 }
4826 // now apply the cached master volume and stream type volume;
4827 // this is trusted but lacks any synchronization or barrier so may be stale
4828 float v = mCachedVolume;
4829 vl *= v;
4830 vr *= v;
4831 // re-combine into U4.16
4832 vlr = (vr << 16) | (vl & 0xFFFF);
4833 // FIXME look at mute, pause, and stop flags
4834 return vlr;
4835}
Eric Laurenta011e352012-03-29 15:51:43 -07004836
Eric Laurent29864602012-05-08 18:57:51 -07004837status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4838{
4839 if (mState == TERMINATED || mState == PAUSED ||
4840 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4841 (mState == STOPPED)))) {
4842 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4843 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4844 event->cancel();
4845 return INVALID_OPERATION;
4846 }
Glenn Kastend23eedc2012-08-02 13:35:47 -07004847 (void) TrackBase::setSyncEvent(event);
Eric Laurent29864602012-05-08 18:57:51 -07004848 return NO_ERROR;
4849}
4850
John Grossman4ff14ba2012-02-08 16:37:41 -08004851// timed audio tracks
4852
4853sp<AudioFlinger::PlaybackThread::TimedTrack>
4854AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004855 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004856 const sp<Client>& client,
4857 audio_stream_type_t streamType,
4858 uint32_t sampleRate,
4859 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004860 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004861 int frameCount,
4862 const sp<IMemory>& sharedBuffer,
4863 int sessionId) {
4864 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004865 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004866
Glenn Kastena0356762012-03-19 10:38:51 -07004867 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004868 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4869 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004870}
4871
4872AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004873 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004874 const sp<Client>& client,
4875 audio_stream_type_t streamType,
4876 uint32_t sampleRate,
4877 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004878 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004879 int frameCount,
4880 const sp<IMemory>& sharedBuffer,
4881 int sessionId)
4882 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004883 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004884 mQueueHeadInFlight(false),
4885 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004886 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004887 mTimedSilenceBuffer(NULL),
4888 mTimedSilenceBufferSize(0),
4889 mTimedAudioOutputOnTime(false),
4890 mMediaTimeTransformValid(false)
4891{
4892 LocalClock lc;
4893 mLocalTimeFreq = lc.getLocalFreq();
4894
4895 mLocalTimeToSampleTransform.a_zero = 0;
4896 mLocalTimeToSampleTransform.b_zero = 0;
4897 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4898 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4899 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4900 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004901
4902 mMediaTimeToSampleTransform.a_zero = 0;
4903 mMediaTimeToSampleTransform.b_zero = 0;
4904 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4905 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4906 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4907 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004908}
4909
4910AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4911 mClient->releaseTimedTrack();
4912 delete [] mTimedSilenceBuffer;
4913}
4914
4915status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4916 size_t size, sp<IMemory>* buffer) {
4917
4918 Mutex::Autolock _l(mTimedBufferQueueLock);
4919
4920 trimTimedBufferQueue_l();
4921
4922 // lazily initialize the shared memory heap for timed buffers
4923 if (mTimedMemoryDealer == NULL) {
4924 const int kTimedBufferHeapSize = 512 << 10;
4925
4926 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4927 "AudioFlingerTimed");
4928 if (mTimedMemoryDealer == NULL)
4929 return NO_MEMORY;
4930 }
4931
4932 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4933 if (newBuffer == NULL) {
4934 newBuffer = mTimedMemoryDealer->allocate(size);
4935 if (newBuffer == NULL)
4936 return NO_MEMORY;
4937 }
4938
4939 *buffer = newBuffer;
4940 return NO_ERROR;
4941}
4942
4943// caller must hold mTimedBufferQueueLock
4944void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4945 int64_t mediaTimeNow;
4946 {
4947 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4948 if (!mMediaTimeTransformValid)
4949 return;
4950
4951 int64_t targetTimeNow;
4952 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4953 ? mCCHelper.getCommonTime(&targetTimeNow)
4954 : mCCHelper.getLocalTime(&targetTimeNow);
4955
4956 if (OK != res)
4957 return;
4958
4959 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4960 &mediaTimeNow)) {
4961 return;
4962 }
4963 }
4964
John Grossman1c345192012-03-27 14:00:17 -07004965 size_t trimEnd;
4966 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004967 int64_t bufEnd;
4968
John Grossmanc95cfbb2012-04-12 11:53:11 -07004969 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4970 // We have a next buffer. Just use its PTS as the PTS of the frame
4971 // following the last frame in this buffer. If the stream is sparse
4972 // (ie, there are deliberate gaps left in the stream which should be
4973 // filled with silence by the TimedAudioTrack), then this can result
4974 // in one extra buffer being left un-trimmed when it could have
4975 // been. In general, this is not typical, and we would rather
4976 // optimized away the TS calculation below for the more common case
4977 // where PTSes are contiguous.
4978 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4979 } else {
4980 // We have no next buffer. Compute the PTS of the frame following
4981 // the last frame in this buffer by computing the duration of of
4982 // this frame in media time units and adding it to the PTS of the
4983 // buffer.
4984 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4985 / mCblk->frameSize;
4986
4987 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4988 &bufEnd)) {
4989 ALOGE("Failed to convert frame count of %lld to media time"
4990 " duration" " (scale factor %d/%u) in %s",
4991 frameCount,
4992 mMediaTimeToSampleTransform.a_to_b_numer,
4993 mMediaTimeToSampleTransform.a_to_b_denom,
4994 __PRETTY_FUNCTION__);
4995 break;
4996 }
4997 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004998 }
John Grossman9fbdee12012-03-26 17:51:46 -07004999
5000 if (bufEnd > mediaTimeNow)
5001 break;
5002
5003 // Is the buffer we want to use in the middle of a mix operation right
5004 // now? If so, don't actually trim it. Just wait for the releaseBuffer
5005 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07005006 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07005007 mTrimQueueHeadOnRelease = true;
5008 }
John Grossman4ff14ba2012-02-08 16:37:41 -08005009 }
5010
John Grossman9fbdee12012-03-26 17:51:46 -07005011 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07005012 if (trimStart < trimEnd) {
5013 // Update the bookkeeping for framesReady()
5014 for (size_t i = trimStart; i < trimEnd; ++i) {
5015 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
5016 }
5017
5018 // Now actually remove the buffers from the queue.
5019 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08005020 }
5021}
5022
John Grossman1c345192012-03-27 14:00:17 -07005023void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
5024 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07005025 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
5026 "%s called (reason \"%s\"), but timed buffer queue has no"
5027 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005028
5029 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
5030 mTimedBufferQueue.removeAt(0);
5031}
5032
5033void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
5034 const TimedBuffer& buf,
5035 const char* logTag) {
5036 uint32_t bufBytes = buf.buffer()->size();
5037 uint32_t consumedAlready = buf.position();
5038
Eric Laurentb388e532012-04-14 13:32:48 -07005039 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07005040 "Bad bookkeeping while updating frames pending. Timed buffer is"
5041 " only %u bytes long, but claims to have consumed %u"
5042 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07005043 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005044
5045 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07005046 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5047 "Bad bookkeeping while updating frames pending. Should have at"
5048 " least %u queued frames, but we think we have only %u. (update"
5049 " reason: \"%s\")",
5050 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005051
5052 mFramesPendingInQueue -= bufFrames;
5053}
5054
John Grossman4ff14ba2012-02-08 16:37:41 -08005055status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5056 const sp<IMemory>& buffer, int64_t pts) {
5057
5058 {
5059 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5060 if (!mMediaTimeTransformValid)
5061 return INVALID_OPERATION;
5062 }
5063
5064 Mutex::Autolock _l(mTimedBufferQueueLock);
5065
John Grossman1c345192012-03-27 14:00:17 -07005066 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5067 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005068 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5069
5070 return NO_ERROR;
5071}
5072
5073status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5074 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5075
John Grossman1c345192012-03-27 14:00:17 -07005076 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5077 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5078 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005079
5080 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5081 target == TimedAudioTrack::COMMON_TIME)) {
5082 return BAD_VALUE;
5083 }
5084
5085 Mutex::Autolock lock(mMediaTimeTransformLock);
5086 mMediaTimeTransform = xform;
5087 mMediaTimeTransformTarget = target;
5088 mMediaTimeTransformValid = true;
5089
5090 return NO_ERROR;
5091}
5092
5093#define min(a, b) ((a) < (b) ? (a) : (b))
5094
5095// implementation of getNextBuffer for tracks whose buffers have timestamps
5096status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5097 AudioBufferProvider::Buffer* buffer, int64_t pts)
5098{
5099 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005100 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005101 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005102 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005103 return INVALID_OPERATION;
5104 }
5105
John Grossman4ff14ba2012-02-08 16:37:41 -08005106 Mutex::Autolock _l(mTimedBufferQueueLock);
5107
John Grossman9fbdee12012-03-26 17:51:46 -07005108 ALOG_ASSERT(!mQueueHeadInFlight,
5109 "getNextBuffer called without releaseBuffer!");
5110
John Grossman4ff14ba2012-02-08 16:37:41 -08005111 while (true) {
5112
5113 // if we have no timed buffers, then fail
5114 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005115 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005116 buffer->frameCount = 0;
5117 return NOT_ENOUGH_DATA;
5118 }
5119
5120 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5121
5122 // calculate the PTS of the head of the timed buffer queue expressed in
5123 // local time
5124 int64_t headLocalPTS;
5125 {
5126 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5127
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005128 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005129
5130 if (mMediaTimeTransform.a_to_b_denom == 0) {
5131 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005132 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005133 return NO_ERROR;
5134 }
5135
5136 int64_t transformedPTS;
5137 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5138 &transformedPTS)) {
5139 // the transform failed. this shouldn't happen, but if it does
5140 // then just drop this buffer
5141 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005142 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005143 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005144 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005145 return NO_ERROR;
5146 }
5147
5148 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5149 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5150 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005151 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005152 buffer->frameCount = 0;
5153 return INVALID_OPERATION;
5154 }
5155 } else {
5156 headLocalPTS = transformedPTS;
5157 }
5158 }
5159
5160 // adjust the head buffer's PTS to reflect the portion of the head buffer
5161 // that has already been consumed
5162 int64_t effectivePTS = headLocalPTS +
5163 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5164
5165 // Calculate the delta in samples between the head of the input buffer
5166 // queue and the start of the next output buffer that will be written.
5167 // If the transformation fails because of over or underflow, it means
5168 // that the sample's position in the output stream is so far out of
5169 // whack that it should just be dropped.
5170 int64_t sampleDelta;
5171 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5172 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005173 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5174 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005175 continue;
5176 }
5177 if (!mLocalTimeToSampleTransform.doForwardTransform(
5178 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005179 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005180 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005181 continue;
5182 }
5183
John Grossman1c345192012-03-27 14:00:17 -07005184 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5185 " sampleDelta=[%d.%08x]",
5186 head.pts(), head.position(), pts,
5187 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5188 + (sampleDelta >> 32)),
5189 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005190
5191 // if the delta between the ideal placement for the next input sample and
5192 // the current output position is within this threshold, then we will
5193 // concatenate the next input samples to the previous output
5194 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005195 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005196
5197 // if this is the first buffer of audio that we're emitting from this track
5198 // then it should be almost exactly on time.
5199 const int64_t kSampleStartupThreshold = 1LL << 32;
5200
5201 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005202 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005203 // the next input is close enough to being on time, so concatenate it
5204 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005205 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005206
John Grossman1c345192012-03-27 14:00:17 -07005207 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5208 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005209 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005210 }
5211
5212 // Looks like our output is not on time. Reset our on timed status.
5213 // Next time we mix samples from our input queue, then should be within
5214 // the StartupThreshold.
5215 mTimedAudioOutputOnTime = false;
5216 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005217 // the gap between the current output position and the proper start of
5218 // the next input sample is too big, so fill it with silence
5219 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5220
John Grossman9fbdee12012-03-26 17:51:46 -07005221 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005222 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5223 return NO_ERROR;
5224 } else {
5225 // the next input sample is late
5226 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5227 size_t onTimeSamplePosition =
5228 head.position() + lateFrames * mCblk->frameSize;
5229
5230 if (onTimeSamplePosition > head.buffer()->size()) {
5231 // all the remaining samples in the head are too late, so
5232 // drop it and move on
5233 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005234 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005235 continue;
5236 } else {
5237 // skip over the late samples
5238 head.setPosition(onTimeSamplePosition);
5239
5240 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005241 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005242
5243 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5244 return NO_ERROR;
5245 }
5246 }
5247 }
5248}
5249
5250// Yield samples from the timed buffer queue head up to the given output
5251// buffer's capacity.
5252//
5253// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005254void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005255 AudioBufferProvider::Buffer* buffer) {
5256
5257 const TimedBuffer& head = mTimedBufferQueue[0];
5258
5259 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5260 head.position());
5261
5262 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5263 mCblk->frameSize);
5264 size_t framesRequested = buffer->frameCount;
5265 buffer->frameCount = min(framesLeftInHead, framesRequested);
5266
John Grossman9fbdee12012-03-26 17:51:46 -07005267 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005268 mTimedAudioOutputOnTime = true;
5269}
5270
5271// Yield samples of silence up to the given output buffer's capacity
5272//
5273// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005274void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005275 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5276
5277 // lazily allocate a buffer filled with silence
5278 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5279 delete [] mTimedSilenceBuffer;
5280 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5281 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5282 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5283 }
5284
5285 buffer->raw = mTimedSilenceBuffer;
5286 size_t framesRequested = buffer->frameCount;
5287 buffer->frameCount = min(numFrames, framesRequested);
5288
5289 mTimedAudioOutputOnTime = false;
5290}
5291
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005292// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005293void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5294 AudioBufferProvider::Buffer* buffer) {
5295
5296 Mutex::Autolock _l(mTimedBufferQueueLock);
5297
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005298 // If the buffer which was just released is part of the buffer at the head
5299 // of the queue, be sure to update the amt of the buffer which has been
5300 // consumed. If the buffer being returned is not part of the head of the
5301 // queue, its either because the buffer is part of the silence buffer, or
5302 // because the head of the timed queue was trimmed after the mixer called
5303 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005304 if (buffer->raw == mTimedSilenceBuffer) {
5305 ALOG_ASSERT(!mQueueHeadInFlight,
5306 "Queue head in flight during release of silence buffer!");
5307 goto done;
5308 }
5309
5310 ALOG_ASSERT(mQueueHeadInFlight,
5311 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5312 " head in flight.");
5313
5314 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005315 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005316
5317 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005318 void* end = reinterpret_cast<void*>(
5319 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5320 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005321
John Grossman9fbdee12012-03-26 17:51:46 -07005322 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5323 "released buffer not within the head of the timed buffer"
5324 " queue; qHead = [%p, %p], released buffer = %p",
5325 start, end, buffer->raw);
5326
5327 head.setPosition(head.position() +
5328 (buffer->frameCount * mCblk->frameSize));
5329 mQueueHeadInFlight = false;
5330
John Grossman1c345192012-03-27 14:00:17 -07005331 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5332 "Bad bookkeeping during releaseBuffer! Should have at"
5333 " least %u queued frames, but we think we have only %u",
5334 buffer->frameCount, mFramesPendingInQueue);
5335
5336 mFramesPendingInQueue -= buffer->frameCount;
5337
John Grossman9fbdee12012-03-26 17:51:46 -07005338 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5339 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005340 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005341 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005342 }
John Grossman9fbdee12012-03-26 17:51:46 -07005343 } else {
5344 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5345 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005346 }
5347
John Grossman9fbdee12012-03-26 17:51:46 -07005348done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005349 buffer->raw = 0;
5350 buffer->frameCount = 0;
5351}
5352
Glenn Kasten288ed212012-04-25 17:52:27 -07005353size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005354 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005355 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005356}
5357
5358AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5359 : mPTS(0), mPosition(0) {}
5360
5361AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5362 const sp<IMemory>& buffer, int64_t pts)
5363 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5364
Mathias Agopian65ab4712010-07-14 17:59:35 -07005365// ----------------------------------------------------------------------------
5366
5367// RecordTrack constructor must be called with AudioFlinger::mLock held
5368AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005369 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005370 const sp<Client>& client,
5371 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005372 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005373 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005374 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005375 int sessionId)
5376 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005377 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005378 mOverflow(false)
5379{
5380 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005381 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5382 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5383 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5384 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5385 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5386 } else {
5387 mCblk->frameSize = sizeof(int8_t);
5388 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005389 }
5390}
5391
5392AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5393{
Glenn Kasten510a3d62012-07-16 14:24:34 -07005394 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005395}
5396
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005397// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005398status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005399{
5400 audio_track_cblk_t* cblk = this->cblk();
5401 uint32_t framesAvail;
5402 uint32_t framesReq = buffer->frameCount;
5403
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005404 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005405 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005406 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005407 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005408 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005409 }
5410
5411 framesAvail = cblk->framesAvailable_l();
5412
Glenn Kastenf6b16782011-12-15 09:51:17 -08005413 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005414 uint32_t s = cblk->server;
5415 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5416
5417 if (framesReq > framesAvail) {
5418 framesReq = framesAvail;
5419 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005420 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005421 framesReq = bufferEnd - s;
5422 }
5423
5424 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005425 buffer->frameCount = framesReq;
5426 return NO_ERROR;
5427 }
5428
5429getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005430 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005431 buffer->frameCount = 0;
5432 return NOT_ENOUGH_DATA;
5433}
5434
Glenn Kasten3acbd052012-02-28 10:39:56 -08005435status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005436 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005437{
5438 sp<ThreadBase> thread = mThread.promote();
5439 if (thread != 0) {
5440 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005441 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005442 } else {
5443 return BAD_VALUE;
5444 }
5445}
5446
5447void AudioFlinger::RecordThread::RecordTrack::stop()
5448{
5449 sp<ThreadBase> thread = mThread.promote();
5450 if (thread != 0) {
5451 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005452 recordThread->mLock.lock();
5453 bool doStop = recordThread->stop_l(this);
5454 if (doStop) {
5455 TrackBase::reset();
5456 // Force overrun condition to avoid false overrun callback until first data is
5457 // read from buffer
5458 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5459 }
5460 recordThread->mLock.unlock();
5461 if (doStop) {
5462 AudioSystem::stopInput(recordThread->id());
5463 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005464 }
5465}
5466
Glenn Kasten510a3d62012-07-16 14:24:34 -07005467/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
5468{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005469 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User FrameCount\n");
Glenn Kasten510a3d62012-07-16 14:24:34 -07005470}
5471
Mathias Agopian65ab4712010-07-14 17:59:35 -07005472void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5473{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005474 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x %05d\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005475 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005476 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005477 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005478 mSessionId,
5479 mFrameCount,
5480 mState,
5481 mCblk->sampleRate,
5482 mCblk->server,
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005483 mCblk->user,
5484 mCblk->frameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005485}
5486
5487
5488// ----------------------------------------------------------------------------
5489
5490AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005491 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005492 DuplicatingThread *sourceThread,
5493 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005494 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005495 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005496 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005497 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5498 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005499 mActive(false), mSourceThread(sourceThread)
5500{
5501
Mathias Agopian65ab4712010-07-14 17:59:35 -07005502 if (mCblk != NULL) {
5503 mCblk->flags |= CBLK_DIRECTION_OUT;
5504 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005505 mOutBuffer.frameCount = 0;
5506 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005507 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005508 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5509 mCblk, mBuffer, mCblk->buffers,
5510 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005511 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005512 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005513 }
5514}
5515
5516AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5517{
5518 clearBufferQueue();
5519}
5520
Glenn Kasten3acbd052012-02-28 10:39:56 -08005521status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005522 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005523{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005524 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005525 if (status != NO_ERROR) {
5526 return status;
5527 }
5528
5529 mActive = true;
5530 mRetryCount = 127;
5531 return status;
5532}
5533
5534void AudioFlinger::PlaybackThread::OutputTrack::stop()
5535{
5536 Track::stop();
5537 clearBufferQueue();
5538 mOutBuffer.frameCount = 0;
5539 mActive = false;
5540}
5541
5542bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5543{
5544 Buffer *pInBuffer;
5545 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005546 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005547 bool outputBufferFull = false;
5548 inBuffer.frameCount = frames;
5549 inBuffer.i16 = data;
5550
5551 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5552
5553 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005554 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005555 sp<ThreadBase> thread = mThread.promote();
5556 if (thread != 0) {
5557 MixerThread *mixerThread = (MixerThread *)thread.get();
5558 if (mCblk->frameCount > frames){
5559 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5560 uint32_t startFrames = (mCblk->frameCount - frames);
5561 pInBuffer = new Buffer;
5562 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5563 pInBuffer->frameCount = startFrames;
5564 pInBuffer->i16 = pInBuffer->mBuffer;
5565 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5566 mBufferQueue.add(pInBuffer);
5567 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005568 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005569 }
5570 }
5571 }
5572 }
5573
5574 while (waitTimeLeftMs) {
5575 // First write pending buffers, then new data
5576 if (mBufferQueue.size()) {
5577 pInBuffer = mBufferQueue.itemAt(0);
5578 } else {
5579 pInBuffer = &inBuffer;
5580 }
5581
5582 if (pInBuffer->frameCount == 0) {
5583 break;
5584 }
5585
5586 if (mOutBuffer.frameCount == 0) {
5587 mOutBuffer.frameCount = pInBuffer->frameCount;
5588 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005589 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005590 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005591 outputBufferFull = true;
5592 break;
5593 }
5594 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5595 if (waitTimeLeftMs >= waitTimeMs) {
5596 waitTimeLeftMs -= waitTimeMs;
5597 } else {
5598 waitTimeLeftMs = 0;
5599 }
5600 }
5601
5602 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5603 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5604 mCblk->stepUser(outFrames);
5605 pInBuffer->frameCount -= outFrames;
5606 pInBuffer->i16 += outFrames * channelCount;
5607 mOutBuffer.frameCount -= outFrames;
5608 mOutBuffer.i16 += outFrames * channelCount;
5609
5610 if (pInBuffer->frameCount == 0) {
5611 if (mBufferQueue.size()) {
5612 mBufferQueue.removeAt(0);
5613 delete [] pInBuffer->mBuffer;
5614 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005615 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005616 } else {
5617 break;
5618 }
5619 }
5620 }
5621
5622 // If we could not write all frames, allocate a buffer and queue it for next time.
5623 if (inBuffer.frameCount) {
5624 sp<ThreadBase> thread = mThread.promote();
5625 if (thread != 0 && !thread->standby()) {
5626 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5627 pInBuffer = new Buffer;
5628 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5629 pInBuffer->frameCount = inBuffer.frameCount;
5630 pInBuffer->i16 = pInBuffer->mBuffer;
5631 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5632 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005633 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005634 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005635 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005636 }
5637 }
5638 }
5639
5640 // Calling write() with a 0 length buffer, means that no more data will be written:
5641 // If no more buffers are pending, fill output track buffer to make sure it is started
5642 // by output mixer.
5643 if (frames == 0 && mBufferQueue.size() == 0) {
5644 if (mCblk->user < mCblk->frameCount) {
5645 frames = mCblk->frameCount - mCblk->user;
5646 pInBuffer = new Buffer;
5647 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5648 pInBuffer->frameCount = frames;
5649 pInBuffer->i16 = pInBuffer->mBuffer;
5650 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5651 mBufferQueue.add(pInBuffer);
5652 } else if (mActive) {
5653 stop();
5654 }
5655 }
5656
5657 return outputBufferFull;
5658}
5659
5660status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5661{
5662 int active;
5663 status_t result;
5664 audio_track_cblk_t* cblk = mCblk;
5665 uint32_t framesReq = buffer->frameCount;
5666
Steve Block3856b092011-10-20 11:56:00 +01005667// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005668 buffer->frameCount = 0;
5669
5670 uint32_t framesAvail = cblk->framesAvailable();
5671
5672
5673 if (framesAvail == 0) {
5674 Mutex::Autolock _l(cblk->lock);
5675 goto start_loop_here;
5676 while (framesAvail == 0) {
5677 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005678 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005679 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005680 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005681 }
5682 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5683 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005684 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005685 }
5686 // read the server count again
5687 start_loop_here:
5688 framesAvail = cblk->framesAvailable_l();
5689 }
5690 }
5691
5692// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005693// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005694// }
5695
5696 if (framesReq > framesAvail) {
5697 framesReq = framesAvail;
5698 }
5699
5700 uint32_t u = cblk->user;
5701 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5702
Marco Nelissena1472d92012-03-30 14:36:54 -07005703 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704 framesReq = bufferEnd - u;
5705 }
5706
5707 buffer->frameCount = framesReq;
5708 buffer->raw = (void *)cblk->buffer(u);
5709 return NO_ERROR;
5710}
5711
5712
5713void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5714{
5715 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005716
5717 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005718 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005719 delete [] pBuffer->mBuffer;
5720 delete pBuffer;
5721 }
5722 mBufferQueue.clear();
5723}
5724
5725// ----------------------------------------------------------------------------
5726
5727AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5728 : RefBase(),
5729 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005730 // 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 -07005731 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005732 mPid(pid),
5733 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005734{
5735 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5736}
5737
5738// Client destructor must be called with AudioFlinger::mLock held
5739AudioFlinger::Client::~Client()
5740{
5741 mAudioFlinger->removeClient_l(mPid);
5742}
5743
Glenn Kasten435dbe62012-01-30 10:15:48 -08005744sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005745{
5746 return mMemoryDealer;
5747}
5748
John Grossman4ff14ba2012-02-08 16:37:41 -08005749// Reserve one of the limited slots for a timed audio track associated
5750// with this client
5751bool AudioFlinger::Client::reserveTimedTrack()
5752{
5753 const int kMaxTimedTracksPerClient = 4;
5754
5755 Mutex::Autolock _l(mTimedTrackLock);
5756
5757 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5758 ALOGW("can not create timed track - pid %d has exceeded the limit",
5759 mPid);
5760 return false;
5761 }
5762
5763 mTimedTrackCount++;
5764 return true;
5765}
5766
5767// Release a slot for a timed audio track
5768void AudioFlinger::Client::releaseTimedTrack()
5769{
5770 Mutex::Autolock _l(mTimedTrackLock);
5771 mTimedTrackCount--;
5772}
5773
Mathias Agopian65ab4712010-07-14 17:59:35 -07005774// ----------------------------------------------------------------------------
5775
5776AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5777 const sp<IAudioFlingerClient>& client,
5778 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005779 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005780{
5781}
5782
5783AudioFlinger::NotificationClient::~NotificationClient()
5784{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005785}
5786
5787void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5788{
5789 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005790 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005791}
5792
5793// ----------------------------------------------------------------------------
5794
5795AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5796 : BnAudioTrack(),
5797 mTrack(track)
5798{
5799}
5800
5801AudioFlinger::TrackHandle::~TrackHandle() {
5802 // just stop the track on deletion, associated resources
5803 // will be freed from the main thread once all pending buffers have
5804 // been played. Unless it's not in the active track list, in which
5805 // case we free everything now...
5806 mTrack->destroy();
5807}
5808
Glenn Kasten90716c52012-01-26 13:40:12 -08005809sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5810 return mTrack->getCblk();
5811}
5812
Glenn Kasten3acbd052012-02-28 10:39:56 -08005813status_t AudioFlinger::TrackHandle::start() {
5814 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005815}
5816
5817void AudioFlinger::TrackHandle::stop() {
5818 mTrack->stop();
5819}
5820
5821void AudioFlinger::TrackHandle::flush() {
5822 mTrack->flush();
5823}
5824
5825void AudioFlinger::TrackHandle::mute(bool e) {
5826 mTrack->mute(e);
5827}
5828
5829void AudioFlinger::TrackHandle::pause() {
5830 mTrack->pause();
5831}
5832
Mathias Agopian65ab4712010-07-14 17:59:35 -07005833status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5834{
5835 return mTrack->attachAuxEffect(EffectId);
5836}
5837
John Grossman4ff14ba2012-02-08 16:37:41 -08005838status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5839 sp<IMemory>* buffer) {
5840 if (!mTrack->isTimedTrack())
5841 return INVALID_OPERATION;
5842
5843 PlaybackThread::TimedTrack* tt =
5844 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5845 return tt->allocateTimedBuffer(size, buffer);
5846}
5847
5848status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5849 int64_t pts) {
5850 if (!mTrack->isTimedTrack())
5851 return INVALID_OPERATION;
5852
5853 PlaybackThread::TimedTrack* tt =
5854 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5855 return tt->queueTimedBuffer(buffer, pts);
5856}
5857
5858status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5859 const LinearTransform& xform, int target) {
5860
5861 if (!mTrack->isTimedTrack())
5862 return INVALID_OPERATION;
5863
5864 PlaybackThread::TimedTrack* tt =
5865 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5866 return tt->setMediaTimeTransform(
5867 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5868}
5869
Mathias Agopian65ab4712010-07-14 17:59:35 -07005870status_t AudioFlinger::TrackHandle::onTransact(
5871 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5872{
5873 return BnAudioTrack::onTransact(code, data, reply, flags);
5874}
5875
5876// ----------------------------------------------------------------------------
5877
5878sp<IAudioRecord> AudioFlinger::openRecord(
5879 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005880 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005881 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005882 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005883 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005884 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005885 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07005886 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005887 int *sessionId,
5888 status_t *status)
5889{
5890 sp<RecordThread::RecordTrack> recordTrack;
5891 sp<RecordHandle> recordHandle;
5892 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005893 status_t lStatus;
5894 RecordThread *thread;
5895 size_t inFrameCount;
5896 int lSessionId;
5897
5898 // check calling permissions
5899 if (!recordingAllowed()) {
5900 lStatus = PERMISSION_DENIED;
5901 goto Exit;
5902 }
5903
5904 // add client to list
5905 { // scope for mLock
5906 Mutex::Autolock _l(mLock);
5907 thread = checkRecordThread_l(input);
5908 if (thread == NULL) {
5909 lStatus = BAD_VALUE;
5910 goto Exit;
5911 }
5912
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005913 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005914
5915 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005916 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005917 lSessionId = *sessionId;
5918 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005919 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005920 if (sessionId != NULL) {
5921 *sessionId = lSessionId;
5922 }
5923 }
5924 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07005925 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5926 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005927 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005928 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005929 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5930 // destructor is called by the TrackBase destructor with mLock held
5931 client.clear();
5932 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005933 goto Exit;
5934 }
5935
5936 // return to handle to client
5937 recordHandle = new RecordHandle(recordTrack);
5938 lStatus = NO_ERROR;
5939
5940Exit:
5941 if (status) {
5942 *status = lStatus;
5943 }
5944 return recordHandle;
5945}
5946
5947// ----------------------------------------------------------------------------
5948
5949AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5950 : BnAudioRecord(),
5951 mRecordTrack(recordTrack)
5952{
5953}
5954
5955AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005956 stop_nonvirtual();
Glenn Kasten510a3d62012-07-16 14:24:34 -07005957 mRecordTrack->destroy();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958}
5959
Glenn Kasten90716c52012-01-26 13:40:12 -08005960sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5961 return mRecordTrack->getCblk();
5962}
5963
Glenn Kasten0ec23ce2012-07-10 12:56:08 -07005964status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005965 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005966 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005967}
5968
5969void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005970 stop_nonvirtual();
5971}
5972
5973void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01005974 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005975 mRecordTrack->stop();
5976}
5977
Mathias Agopian65ab4712010-07-14 17:59:35 -07005978status_t AudioFlinger::RecordHandle::onTransact(
5979 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5980{
5981 return BnAudioRecord::onTransact(code, data, reply, flags);
5982}
5983
5984// ----------------------------------------------------------------------------
5985
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005986AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5987 AudioStreamIn *input,
5988 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07005989 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005990 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07005991 audio_devices_t device) :
Eric Laurentf1c04f92012-08-28 14:26:53 -07005992 ThreadBase(audioFlinger, id, AUDIO_DEVICE_NONE, device, RECORD),
Glenn Kasten510a3d62012-07-16 14:24:34 -07005993 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005994 // mRsmpInIndex and mInputBytes set by readInputParameters()
Glenn Kasten254af182012-07-03 14:59:05 -07005995 mReqChannelCount(popcount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005996 mReqSampleRate(sampleRate)
5997 // mBytesRead is only meaningful while active, and so is cleared in start()
5998 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005999{
Glenn Kasten480b4682012-02-28 12:30:08 -08006000 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07006001
Mathias Agopian65ab4712010-07-14 17:59:35 -07006002 readInputParameters();
6003}
6004
6005
6006AudioFlinger::RecordThread::~RecordThread()
6007{
6008 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08006009 delete mResampler;
6010 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006011}
6012
6013void AudioFlinger::RecordThread::onFirstRef()
6014{
Eric Laurentfeb0db62011-07-22 09:04:31 -07006015 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006016}
6017
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006018status_t AudioFlinger::RecordThread::readyToRun()
6019{
6020 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00006021 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006022 return status;
6023}
6024
Mathias Agopian65ab4712010-07-14 17:59:35 -07006025bool AudioFlinger::RecordThread::threadLoop()
6026{
6027 AudioBufferProvider::Buffer buffer;
6028 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006029 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006030
Eric Laurent44d98482010-09-30 16:12:31 -07006031 nsecs_t lastWarning = 0;
6032
Glenn Kastene4e2a372012-07-23 12:55:09 -07006033 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07006034 acquireWakeLock();
6035
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07006036 // used to verify we've read at least once before evaluating how many bytes were read
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006037 bool readOnce = false;
6038
Mathias Agopian65ab4712010-07-14 17:59:35 -07006039 // start recording
6040 while (!exitPending()) {
6041
6042 processConfigEvents();
6043
6044 { // scope for mLock
6045 Mutex::Autolock _l(mLock);
6046 checkForNewParameters_l();
6047 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006048 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006049
6050 if (exitPending()) break;
6051
Eric Laurentfeb0db62011-07-22 09:04:31 -07006052 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01006053 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006054 // go to sleep
6055 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006056 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006057 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006058 continue;
6059 }
6060 if (mActiveTrack != 0) {
6061 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006062 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006063 mActiveTrack.clear();
6064 mStartStopCond.broadcast();
6065 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6066 if (mReqChannelCount != mActiveTrack->channelCount()) {
6067 mActiveTrack.clear();
6068 mStartStopCond.broadcast();
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006069 } else if (readOnce) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006070 // record start succeeds only if first read from audio input
6071 // succeeds
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006072 if (mBytesRead >= 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006073 mActiveTrack->mState = TrackBase::ACTIVE;
6074 } else {
6075 mActiveTrack.clear();
6076 }
6077 mStartStopCond.broadcast();
6078 }
6079 mStandby = false;
Glenn Kasten510a3d62012-07-16 14:24:34 -07006080 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
6081 removeTrack_l(mActiveTrack);
6082 mActiveTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006083 }
6084 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006085 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006086 }
6087
6088 if (mActiveTrack != 0) {
6089 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6090 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006091 unlockEffectChains(effectChains);
6092 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006093 continue;
6094 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006095 for (size_t i = 0; i < effectChains.size(); i ++) {
6096 effectChains[i]->process_l();
6097 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006098
Mathias Agopian65ab4712010-07-14 17:59:35 -07006099 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006100 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006101 readOnce = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006102 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006103 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006104 // no resampling
6105 while (framesOut) {
6106 size_t framesIn = mFrameCount - mRsmpInIndex;
6107 if (framesIn) {
6108 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6109 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6110 if (framesIn > framesOut)
6111 framesIn = framesOut;
6112 mRsmpInIndex += framesIn;
6113 framesOut -= framesIn;
6114 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006115 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006116 memcpy(dst, src, framesIn * mFrameSize);
6117 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006118 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006119 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6120 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006121 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006122 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6123 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006124 }
6125 }
6126 }
6127 if (framesOut && mFrameCount == mRsmpInIndex) {
6128 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006129 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006130 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006131 framesOut = 0;
6132 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006133 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006134 mRsmpInIndex = 0;
6135 }
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006136 if (mBytesRead <= 0) {
6137 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
6138 {
6139 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006140 // Force input into standby so that it tries to
6141 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006142 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006143 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006144 }
6145 mRsmpInIndex = mFrameCount;
6146 framesOut = 0;
6147 buffer.frameCount = 0;
6148 }
6149 }
6150 }
6151 } else {
6152 // resampling
6153
6154 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6155 // alter output frame count as if we were expecting stereo samples
6156 if (mChannelCount == 1 && mReqChannelCount == 1) {
6157 framesOut >>= 1;
6158 }
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07006159 mResampler->resample(mRsmpOutBuffer, framesOut, this /* AudioBufferProvider* */);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006160 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6161 // are 32 bit aligned which should be always true.
6162 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006163 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006164 // the resampler always outputs stereo samples: do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006165 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6166 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006167 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006168 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006169 }
6170
6171 }
Eric Laurenta011e352012-03-29 15:51:43 -07006172 if (mFramestoDrop == 0) {
6173 mActiveTrack->releaseBuffer(&buffer);
6174 } else {
6175 if (mFramestoDrop > 0) {
6176 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006177 if (mFramestoDrop <= 0) {
6178 clearSyncStartEvent();
6179 }
6180 } else {
6181 mFramestoDrop += buffer.frameCount;
6182 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6183 mSyncStartEvent->isCancelled()) {
6184 ALOGW("Synced record %s, session %d, trigger session %d",
6185 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6186 mActiveTrack->sessionId(),
6187 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6188 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006189 }
6190 }
6191 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006192 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006193 }
6194 // client isn't retrieving buffers fast enough
6195 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006196 if (!mActiveTrack->setOverflow()) {
6197 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006198 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006199 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006200 lastWarning = now;
6201 }
6202 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006203 // Release the processor for a while before asking for a new buffer.
6204 // This will give the application more chance to read from the buffer and
6205 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006206 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006207 }
6208 }
Eric Laurentec437d82011-07-26 20:54:46 -07006209 // enable changes in effect chain
6210 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006211 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006212 }
6213
Glenn Kastene4e2a372012-07-23 12:55:09 -07006214 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006215
Glenn Kasten33e6e352012-07-16 15:56:57 -07006216 {
6217 Mutex::Autolock _l(mLock);
6218 mActiveTrack.clear();
6219 mStartStopCond.broadcast();
6220 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006221
Eric Laurentfeb0db62011-07-22 09:04:31 -07006222 releaseWakeLock();
6223
Steve Block3856b092011-10-20 11:56:00 +01006224 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006225 return false;
6226}
6227
Glenn Kastene4e2a372012-07-23 12:55:09 -07006228void AudioFlinger::RecordThread::standby()
6229{
6230 if (!mStandby) {
6231 inputStandBy();
6232 mStandby = true;
6233 }
6234}
6235
6236void AudioFlinger::RecordThread::inputStandBy()
6237{
6238 mInput->stream->common.standby(&mInput->stream->common);
6239}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006240
6241sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6242 const sp<AudioFlinger::Client>& client,
6243 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006244 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006245 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006246 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006247 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006248 IAudioFlinger::track_flags_t flags,
6249 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006250 status_t *status)
6251{
6252 sp<RecordTrack> track;
6253 status_t lStatus;
6254
6255 lStatus = initCheck();
6256 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006257 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006258 goto Exit;
6259 }
6260
Glenn Kasten1879fff2012-07-11 15:36:59 -07006261 // FIXME use flags and tid similar to createTrack_l()
6262
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006263 { // scope for mLock
6264 Mutex::Autolock _l(mLock);
6265
6266 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006267 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006268
Glenn Kasten7378ca52012-01-20 13:44:40 -08006269 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006270 lStatus = NO_MEMORY;
6271 goto Exit;
6272 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006273 mTracks.add(track);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006274
Eric Laurent59bd0da2011-08-01 09:52:20 -07006275 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1c04f92012-08-28 14:26:53 -07006276 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006277 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006278 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6279 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006280 }
6281 lStatus = NO_ERROR;
6282
6283Exit:
6284 if (status) {
6285 *status = lStatus;
6286 }
6287 return track;
6288}
6289
Eric Laurenta011e352012-03-29 15:51:43 -07006290status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006291 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006292 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006293{
Glenn Kasten58912562012-04-03 10:45:00 -07006294 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006295 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006296 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006297
6298 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006299 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006300 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6301 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6302 triggerSession,
6303 recordTrack->sessionId(),
6304 syncStartEventCallback,
6305 this);
Eric Laurent29864602012-05-08 18:57:51 -07006306 // Sync event can be cancelled by the trigger session if the track is not in a
6307 // compatible state in which case we start record immediately
6308 if (mSyncStartEvent->isCancelled()) {
6309 clearSyncStartEvent();
6310 } else {
6311 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6312 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6313 }
Eric Laurenta011e352012-03-29 15:51:43 -07006314 }
6315
Mathias Agopian65ab4712010-07-14 17:59:35 -07006316 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006317 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006318 if (mActiveTrack != 0) {
6319 if (recordTrack != mActiveTrack.get()) {
6320 status = -EBUSY;
6321 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6322 mActiveTrack->mState = TrackBase::ACTIVE;
6323 }
6324 return status;
6325 }
6326
6327 recordTrack->mState = TrackBase::IDLE;
6328 mActiveTrack = recordTrack;
6329 mLock.unlock();
6330 status_t status = AudioSystem::startInput(mId);
6331 mLock.lock();
6332 if (status != NO_ERROR) {
6333 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006334 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006335 return status;
6336 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006337 mRsmpInIndex = mFrameCount;
6338 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006339 if (mResampler != NULL) {
6340 mResampler->reset();
6341 }
6342 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006343 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006344 ALOGV("Signal record thread");
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07006345 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006346 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006347 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006348 mActiveTrack.clear();
6349 status = INVALID_OPERATION;
6350 goto startError;
6351 }
6352 mStartStopCond.wait(mLock);
6353 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006354 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006355 status = BAD_VALUE;
6356 goto startError;
6357 }
Steve Block3856b092011-10-20 11:56:00 +01006358 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006359 return status;
6360 }
6361startError:
6362 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006363 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006364 return status;
6365}
6366
Eric Laurenta011e352012-03-29 15:51:43 -07006367void AudioFlinger::RecordThread::clearSyncStartEvent()
6368{
6369 if (mSyncStartEvent != 0) {
6370 mSyncStartEvent->cancel();
6371 }
6372 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006373 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006374}
6375
6376void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6377{
6378 sp<SyncEvent> strongEvent = event.promote();
6379
6380 if (strongEvent != 0) {
6381 RecordThread *me = (RecordThread *)strongEvent->cookie();
6382 me->handleSyncStartEvent(strongEvent);
6383 }
6384}
6385
6386void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6387{
Eric Laurent29864602012-05-08 18:57:51 -07006388 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006389 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6390 // from audio HAL
6391 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006392 }
6393}
6394
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006395bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006396 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006397 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
6398 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006399 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006400 recordTrack->mState = TrackBase::PAUSING;
6401 // do not wait for mStartStopCond if exiting
6402 if (exitPending()) {
6403 return true;
6404 }
6405 mStartStopCond.wait(mLock);
6406 // if we have been restarted, recordTrack == mActiveTrack.get() here
6407 if (exitPending() || recordTrack != mActiveTrack.get()) {
6408 ALOGV("Record stopped OK");
6409 return true;
6410 }
6411 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006412}
6413
Glenn Kasten106e8a42012-08-02 13:37:12 -07006414bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07006415{
6416 return false;
6417}
6418
6419status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6420{
Glenn Kasten7aa25592012-08-02 16:37:07 -07006421#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 -07006422 if (!isValidSyncEvent(event)) {
6423 return BAD_VALUE;
6424 }
6425
Glenn Kasten510a3d62012-07-16 14:24:34 -07006426 int eventSession = event->triggerSession();
6427 status_t ret = NAME_NOT_FOUND;
6428
Eric Laurenta011e352012-03-29 15:51:43 -07006429 Mutex::Autolock _l(mLock);
6430
Glenn Kasten510a3d62012-07-16 14:24:34 -07006431 for (size_t i = 0; i < mTracks.size(); i++) {
6432 sp<RecordTrack> track = mTracks[i];
6433 if (eventSession == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07006434 (void) track->setSyncEvent(event);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006435 ret = NO_ERROR;
6436 }
Eric Laurenta011e352012-03-29 15:51:43 -07006437 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006438 return ret;
Glenn Kasten7aa25592012-08-02 16:37:07 -07006439#else
6440 return BAD_VALUE;
6441#endif
Glenn Kasten510a3d62012-07-16 14:24:34 -07006442}
6443
6444void AudioFlinger::RecordThread::RecordTrack::destroy()
6445{
6446 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
6447 sp<RecordTrack> keep(this);
6448 {
6449 sp<ThreadBase> thread = mThread.promote();
6450 if (thread != 0) {
6451 if (mState == ACTIVE || mState == RESUMING) {
6452 AudioSystem::stopInput(thread->id());
6453 }
6454 AudioSystem::releaseInput(thread->id());
6455 Mutex::Autolock _l(thread->mLock);
6456 RecordThread *recordThread = (RecordThread *) thread.get();
6457 recordThread->destroyTrack_l(this);
6458 }
6459 }
6460}
6461
6462// destroyTrack_l() must be called with ThreadBase::mLock held
6463void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6464{
6465 track->mState = TrackBase::TERMINATED;
6466 // active tracks are removed by threadLoop()
6467 if (mActiveTrack != track) {
6468 removeTrack_l(track);
6469 }
6470}
6471
6472void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6473{
6474 mTracks.remove(track);
6475 // need anything related to effects here?
Eric Laurenta011e352012-03-29 15:51:43 -07006476}
6477
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07006478void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006479{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006480 dumpInternals(fd, args);
6481 dumpTracks(fd, args);
6482 dumpEffectChains(fd, args);
6483}
6484
6485void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6486{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006487 const size_t SIZE = 256;
6488 char buffer[SIZE];
6489 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006490
6491 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6492 result.append(buffer);
6493
6494 if (mActiveTrack != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006495 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6496 result.append(buffer);
6497 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6498 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006499 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006500 result.append(buffer);
6501 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6502 result.append(buffer);
6503 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6504 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006505 } else {
Glenn Kasten510a3d62012-07-16 14:24:34 -07006506 result.append("No active record client\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006507 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006508
Mathias Agopian65ab4712010-07-14 17:59:35 -07006509 write(fd, result.string(), result.size());
6510
6511 dumpBase(fd, args);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006512}
6513
6514void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
6515{
6516 const size_t SIZE = 256;
6517 char buffer[SIZE];
6518 String8 result;
6519
6520 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
6521 result.append(buffer);
6522 RecordTrack::appendDumpHeader(result);
6523 for (size_t i = 0; i < mTracks.size(); ++i) {
6524 sp<RecordTrack> track = mTracks[i];
6525 if (track != 0) {
6526 track->dump(buffer, SIZE);
6527 result.append(buffer);
6528 }
6529 }
6530
6531 if (mActiveTrack != 0) {
6532 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
6533 result.append(buffer);
6534 RecordTrack::appendDumpHeader(result);
6535 mActiveTrack->dump(buffer, SIZE);
6536 result.append(buffer);
6537
6538 }
6539 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006540}
6541
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006542// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006543status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006544{
6545 size_t framesReq = buffer->frameCount;
6546 size_t framesReady = mFrameCount - mRsmpInIndex;
6547 int channelCount;
6548
6549 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006550 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07006551 if (mBytesRead <= 0) {
6552 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
6553 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006554 // Force input into standby so that it tries to
6555 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006556 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006557 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006558 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006559 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006560 buffer->frameCount = 0;
6561 return NOT_ENOUGH_DATA;
6562 }
6563 mRsmpInIndex = 0;
6564 framesReady = mFrameCount;
6565 }
6566
6567 if (framesReq > framesReady) {
6568 framesReq = framesReady;
6569 }
6570
6571 if (mChannelCount == 1 && mReqChannelCount == 2) {
6572 channelCount = 1;
6573 } else {
6574 channelCount = 2;
6575 }
6576 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6577 buffer->frameCount = framesReq;
6578 return NO_ERROR;
6579}
6580
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006581// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006582void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6583{
6584 mRsmpInIndex += buffer->frameCount;
6585 buffer->frameCount = 0;
6586}
6587
6588bool AudioFlinger::RecordThread::checkForNewParameters_l()
6589{
6590 bool reconfig = false;
6591
6592 while (!mNewParameters.isEmpty()) {
6593 status_t status = NO_ERROR;
6594 String8 keyValuePair = mNewParameters[0];
6595 AudioParameter param = AudioParameter(keyValuePair);
6596 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006597 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006598 int reqSamplingRate = mReqSampleRate;
6599 int reqChannelCount = mReqChannelCount;
6600
6601 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6602 reqSamplingRate = value;
6603 reconfig = true;
6604 }
6605 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006606 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006607 reconfig = true;
6608 }
6609 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006610 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006611 reconfig = true;
6612 }
6613 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6614 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006615 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006616 // if frame count is changed after track creation
6617 if (mActiveTrack != 0) {
6618 status = INVALID_OPERATION;
6619 } else {
6620 reconfig = true;
6621 }
6622 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006623 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6624 // forward device change to effects that have requested to be
6625 // aware of attached audio device.
6626 for (size_t i = 0; i < mEffectChains.size(); i++) {
6627 mEffectChains[i]->setDevice_l(value);
6628 }
Eric Laurentf1c04f92012-08-28 14:26:53 -07006629
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006630 // store input device and output device but do not forward output device to audio HAL.
6631 // Note that status is ignored by the caller for output device
6632 // (see AudioFlinger::setParameters()
Eric Laurentf1c04f92012-08-28 14:26:53 -07006633 if (audio_is_output_devices(value)) {
6634 mOutDevice = value;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006635 status = BAD_VALUE;
6636 } else {
Eric Laurentf1c04f92012-08-28 14:26:53 -07006637 mInDevice = value;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006638 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kasten510a3d62012-07-16 14:24:34 -07006639 if (mTracks.size() > 0) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07006640 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6641 mAudioFlinger->btNrecIsOff();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006642 for (size_t i = 0; i < mTracks.size(); i++) {
6643 sp<RecordTrack> track = mTracks[i];
6644 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6645 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6646 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07006647 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006648 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006649 }
Eric Laurent57b2dd12012-08-31 17:44:06 -07006650 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6651 mAudioSource != (audio_source_t)value) {
6652 // forward device change to effects that have requested to be
6653 // aware of attached audio device.
6654 for (size_t i = 0; i < mEffectChains.size(); i++) {
6655 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
6656 }
6657 mAudioSource = (audio_source_t)value;
6658 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006659 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006660 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006661 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006662 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006663 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6664 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006665 }
6666 if (reconfig) {
6667 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006668 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006669 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006670 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006671 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6672 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006673 status = NO_ERROR;
6674 }
6675 if (status == NO_ERROR) {
6676 readInputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07006677 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006678 }
6679 }
6680 }
6681
6682 mNewParameters.removeAt(0);
6683
6684 mParamStatus = status;
6685 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006686 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6687 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006688 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006689 }
6690 return reconfig;
6691}
6692
6693String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6694{
Dima Zavinfce7a472011-04-19 22:30:36 -07006695 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006696 String8 out_s8 = String8();
6697
6698 Mutex::Autolock _l(mLock);
6699 if (initCheck() != NO_ERROR) {
6700 return out_s8;
6701 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006702
Dima Zavin799a70e2011-04-18 16:57:27 -07006703 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006704 out_s8 = String8(s);
6705 free(s);
6706 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006707}
6708
6709void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6710 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006711 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006712
6713 switch (event) {
6714 case AudioSystem::INPUT_OPENED:
6715 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006716 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006717 desc.samplingRate = mSampleRate;
6718 desc.format = mFormat;
6719 desc.frameCount = mFrameCount;
6720 desc.latency = 0;
6721 param2 = &desc;
6722 break;
6723
6724 case AudioSystem::INPUT_CLOSED:
6725 default:
6726 break;
6727 }
6728 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6729}
6730
6731void AudioFlinger::RecordThread::readInputParameters()
6732{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006733 delete mRsmpInBuffer;
6734 // mRsmpInBuffer is always assigned a new[] below
6735 delete mRsmpOutBuffer;
6736 mRsmpOutBuffer = NULL;
6737 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006738 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006739
Dima Zavin799a70e2011-04-18 16:57:27 -07006740 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006741 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6742 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006743 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006744 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006745 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006746 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006747 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006748 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6749
Glenn Kasten53d76db2012-03-08 12:32:47 -08006750 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006751 {
6752 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006753 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6754 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006755 if (mChannelCount == 1 && mReqChannelCount == 2) {
6756 channelCount = 1;
6757 } else {
6758 channelCount = 2;
6759 }
6760 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6761 mResampler->setSampleRate(mSampleRate);
6762 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6763 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6764
6765 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6766 if (mChannelCount == 1 && mReqChannelCount == 1) {
6767 mFrameCount >>= 1;
6768 }
6769
6770 }
6771 mRsmpInIndex = mFrameCount;
6772}
6773
6774unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6775{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006776 Mutex::Autolock _l(mLock);
6777 if (initCheck() != NO_ERROR) {
6778 return 0;
6779 }
6780
Dima Zavin799a70e2011-04-18 16:57:27 -07006781 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006782}
6783
Glenn Kasten106e8a42012-08-02 13:37:12 -07006784uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006785{
6786 Mutex::Autolock _l(mLock);
6787 uint32_t result = 0;
6788 if (getEffectChain_l(sessionId) != 0) {
6789 result = EFFECT_SESSION;
6790 }
6791
Glenn Kasten510a3d62012-07-16 14:24:34 -07006792 for (size_t i = 0; i < mTracks.size(); ++i) {
6793 if (sessionId == mTracks[i]->sessionId()) {
6794 result |= TRACK_SESSION;
6795 break;
6796 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006797 }
6798
6799 return result;
6800}
6801
Glenn Kasten106e8a42012-08-02 13:37:12 -07006802KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent59bd0da2011-08-01 09:52:20 -07006803{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006804 KeyedVector<int, bool> ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006805 Mutex::Autolock _l(mLock);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006806 for (size_t j = 0; j < mTracks.size(); ++j) {
6807 sp<RecordThread::RecordTrack> track = mTracks[j];
6808 int sessionId = track->sessionId();
6809 if (ids.indexOfKey(sessionId) < 0) {
6810 ids.add(sessionId, true);
6811 }
6812 }
6813 return ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006814}
6815
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006816AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6817{
6818 Mutex::Autolock _l(mLock);
6819 AudioStreamIn *input = mInput;
6820 mInput = NULL;
6821 return input;
6822}
6823
6824// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006825audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006826{
6827 if (mInput == NULL) {
6828 return NULL;
6829 }
6830 return &mInput->stream->common;
6831}
6832
6833
Mathias Agopian65ab4712010-07-14 17:59:35 -07006834// ----------------------------------------------------------------------------
6835
Eric Laurenta4c5a552012-03-29 10:12:40 -07006836audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6837{
6838 if (!settingsAllowed()) {
6839 return 0;
6840 }
6841 Mutex::Autolock _l(mLock);
6842 return loadHwModule_l(name);
6843}
6844
6845// loadHwModule_l() must be called with AudioFlinger::mLock held
6846audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6847{
6848 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6849 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6850 ALOGW("loadHwModule() module %s already loaded", name);
6851 return mAudioHwDevs.keyAt(i);
6852 }
6853 }
6854
Eric Laurenta4c5a552012-03-29 10:12:40 -07006855 audio_hw_device_t *dev;
6856
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006857 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006858 if (rc) {
6859 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6860 return 0;
6861 }
6862
6863 mHardwareStatus = AUDIO_HW_INIT;
6864 rc = dev->init_check(dev);
6865 mHardwareStatus = AUDIO_HW_IDLE;
6866 if (rc) {
6867 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6868 return 0;
6869 }
6870
John Grossmanee578c02012-07-23 17:05:46 -07006871 // Check and cache this HAL's level of support for master mute and master
6872 // volume. If this is the first HAL opened, and it supports the get
6873 // methods, use the initial values provided by the HAL as the current
6874 // master mute and volume settings.
6875
6876 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
6877 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07006878 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07006879
6880 if (0 == mAudioHwDevs.size()) {
6881 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6882 if (NULL != dev->get_master_volume) {
6883 float mv;
6884 if (OK == dev->get_master_volume(dev, &mv)) {
6885 mMasterVolume = mv;
6886 }
6887 }
6888
6889 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
6890 if (NULL != dev->get_master_mute) {
6891 bool mm;
6892 if (OK == dev->get_master_mute(dev, &mm)) {
6893 mMasterMute = mm;
6894 }
6895 }
6896 }
6897
Eric Laurenta4c5a552012-03-29 10:12:40 -07006898 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07006899 if ((NULL != dev->set_master_volume) &&
6900 (OK == dev->set_master_volume(dev, mMasterVolume))) {
6901 flags = static_cast<AudioHwDevice::Flags>(flags |
6902 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
6903 }
6904
6905 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
6906 if ((NULL != dev->set_master_mute) &&
6907 (OK == dev->set_master_mute(dev, mMasterMute))) {
6908 flags = static_cast<AudioHwDevice::Flags>(flags |
6909 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
6910 }
6911
Eric Laurenta4c5a552012-03-29 10:12:40 -07006912 mHardwareStatus = AUDIO_HW_IDLE;
6913 }
6914
6915 audio_module_handle_t handle = nextUniqueId();
John Grossmanee578c02012-07-23 17:05:46 -07006916 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07006917
6918 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006919 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006920
6921 return handle;
6922
6923}
6924
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07006925// ----------------------------------------------------------------------------
6926
6927int32_t AudioFlinger::getPrimaryOutputSamplingRate()
6928{
6929 Mutex::Autolock _l(mLock);
6930 PlaybackThread *thread = primaryPlaybackThread_l();
6931 return thread != NULL ? thread->sampleRate() : 0;
6932}
6933
6934int32_t AudioFlinger::getPrimaryOutputFrameCount()
6935{
6936 Mutex::Autolock _l(mLock);
6937 PlaybackThread *thread = primaryPlaybackThread_l();
6938 return thread != NULL ? thread->frameCountHAL() : 0;
6939}
6940
6941// ----------------------------------------------------------------------------
6942
Eric Laurenta4c5a552012-03-29 10:12:40 -07006943audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6944 audio_devices_t *pDevices,
6945 uint32_t *pSamplingRate,
6946 audio_format_t *pFormat,
6947 audio_channel_mask_t *pChannelMask,
6948 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006949 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006950{
6951 status_t status;
6952 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006953 struct audio_config config = {
6954 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6955 channel_mask: pChannelMask ? *pChannelMask : 0,
6956 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6957 };
6958 audio_stream_out_t *outStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07006959 AudioHwDevice *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006960
Eric Laurenta4c5a552012-03-29 10:12:40 -07006961 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6962 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006963 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006964 config.sample_rate,
6965 config.format,
6966 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006967 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006968
6969 if (pDevices == NULL || *pDevices == 0) {
6970 return 0;
6971 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006972
Mathias Agopian65ab4712010-07-14 17:59:35 -07006973 Mutex::Autolock _l(mLock);
6974
Eric Laurenta4c5a552012-03-29 10:12:40 -07006975 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006976 if (outHwDev == NULL)
6977 return 0;
6978
John Grossmanee578c02012-07-23 17:05:46 -07006979 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006980 audio_io_handle_t id = nextUniqueId();
6981
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006982 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006983
John Grossmanee578c02012-07-23 17:05:46 -07006984 status = hwDevHal->open_output_stream(hwDevHal,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006985 id,
6986 *pDevices,
6987 (audio_output_flags_t)flags,
6988 &config,
6989 &outStream);
6990
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006991 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006992 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006993 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006994 config.sample_rate,
6995 config.format,
6996 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006997 status);
6998
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006999 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007000 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007001
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007002 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007003 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
7004 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007005 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007006 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007007 } else {
7008 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007009 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007010 }
7011 mPlaybackThreads.add(id, thread);
7012
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007013 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
7014 if (pFormat != NULL) *pFormat = config.format;
7015 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08007016 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007017
7018 // notify client processes of the new output creation
7019 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007020
7021 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007022 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07007023 ALOGI("Using module %d has the primary audio interface", module);
7024 mPrimaryHardwareDev = outHwDev;
7025
7026 AutoMutex lock(mHardwareLock);
7027 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -07007028 hwDevHal->set_mode(hwDevHal, mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007029 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007030 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007031 return id;
7032 }
7033
7034 return 0;
7035}
7036
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007037audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
7038 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007039{
7040 Mutex::Autolock _l(mLock);
7041 MixerThread *thread1 = checkMixerThread_l(output1);
7042 MixerThread *thread2 = checkMixerThread_l(output2);
7043
7044 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007045 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007046 return 0;
7047 }
7048
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007049 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007050 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
7051 thread->addOutputTrack(thread2);
7052 mPlaybackThreads.add(id, thread);
7053 // notify client processes of the new output creation
7054 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7055 return id;
7056}
7057
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007058status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007059{
Glenn Kastend96c5722012-04-25 13:44:49 -07007060 return closeOutput_nonvirtual(output);
7061}
7062
7063status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
7064{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007065 // keep strong reference on the playback thread so that
7066 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007067 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007068 {
7069 Mutex::Autolock _l(mLock);
7070 thread = checkPlaybackThread_l(output);
7071 if (thread == NULL) {
7072 return BAD_VALUE;
7073 }
7074
Steve Block3856b092011-10-20 11:56:00 +01007075 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007076
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007077 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007078 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007079 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007080 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
7081 dupThread->removeOutputTrack((MixerThread *)thread.get());
7082 }
7083 }
7084 }
Glenn Kastena1117922012-01-26 10:53:32 -08007085 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007086 mPlaybackThreads.removeItem(output);
7087 }
7088 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007089 // The thread entity (active unit of execution) is no longer running here,
7090 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007091
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007092 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007093 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007094 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007095 // from now on thread->mOutput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007096 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007097 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007098 }
7099 return NO_ERROR;
7100}
7101
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007102status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007103{
7104 Mutex::Autolock _l(mLock);
7105 PlaybackThread *thread = checkPlaybackThread_l(output);
7106
7107 if (thread == NULL) {
7108 return BAD_VALUE;
7109 }
7110
Steve Block3856b092011-10-20 11:56:00 +01007111 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007112 thread->suspend();
7113
7114 return NO_ERROR;
7115}
7116
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007117status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007118{
7119 Mutex::Autolock _l(mLock);
7120 PlaybackThread *thread = checkPlaybackThread_l(output);
7121
7122 if (thread == NULL) {
7123 return BAD_VALUE;
7124 }
7125
Steve Block3856b092011-10-20 11:56:00 +01007126 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007127
7128 thread->restore();
7129
7130 return NO_ERROR;
7131}
7132
Eric Laurenta4c5a552012-03-29 10:12:40 -07007133audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
7134 audio_devices_t *pDevices,
7135 uint32_t *pSamplingRate,
7136 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07007137 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007138{
7139 status_t status;
7140 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007141 struct audio_config config = {
7142 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7143 channel_mask: pChannelMask ? *pChannelMask : 0,
7144 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7145 };
7146 uint32_t reqSamplingRate = config.sample_rate;
7147 audio_format_t reqFormat = config.format;
7148 audio_channel_mask_t reqChannels = config.channel_mask;
7149 audio_stream_in_t *inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007150 AudioHwDevice *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007151
7152 if (pDevices == NULL || *pDevices == 0) {
7153 return 0;
7154 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007155
Mathias Agopian65ab4712010-07-14 17:59:35 -07007156 Mutex::Autolock _l(mLock);
7157
Eric Laurenta4c5a552012-03-29 10:12:40 -07007158 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007159 if (inHwDev == NULL)
7160 return 0;
7161
John Grossmanee578c02012-07-23 17:05:46 -07007162 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007163 audio_io_handle_t id = nextUniqueId();
7164
John Grossmanee578c02012-07-23 17:05:46 -07007165 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007166 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007167 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007168 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007169 config.sample_rate,
7170 config.format,
7171 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007172 status);
7173
7174 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7175 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7176 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007177 if (status == BAD_VALUE &&
7178 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7179 (config.sample_rate <= 2 * reqSamplingRate) &&
7180 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007181 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007182 inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007183 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007184 }
7185
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007186 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007187 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7188
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007189 // Start record thread
7190 // RecorThread require both input and output device indication to forward to audio
7191 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007192 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007193 thread = new RecordThread(this,
7194 input,
7195 reqSamplingRate,
7196 reqChannels,
7197 id,
7198 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007199 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007200 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007201 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007202 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007203 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007204
Mathias Agopian65ab4712010-07-14 17:59:35 -07007205 // notify client processes of the new input creation
7206 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7207 return id;
7208 }
7209
7210 return 0;
7211}
7212
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007213status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007214{
Glenn Kastend96c5722012-04-25 13:44:49 -07007215 return closeInput_nonvirtual(input);
7216}
7217
7218status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7219{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007220 // keep strong reference on the record thread so that
7221 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007222 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007223 {
7224 Mutex::Autolock _l(mLock);
7225 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007226 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007227 return BAD_VALUE;
7228 }
7229
Steve Block3856b092011-10-20 11:56:00 +01007230 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007231 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007232 mRecordThreads.removeItem(input);
7233 }
7234 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007235 // The thread entity (active unit of execution) is no longer running here,
7236 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007237
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007238 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007239 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007240 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007241 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007242 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007243
7244 return NO_ERROR;
7245}
7246
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007247status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007248{
7249 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007250 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007251
7252 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7253 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007254 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007255 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007256
7257 return NO_ERROR;
7258}
7259
7260
7261int AudioFlinger::newAudioSessionId()
7262{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007263 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007264}
7265
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007266void AudioFlinger::acquireAudioSessionId(int audioSession)
7267{
7268 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007269 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007270 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007271 size_t num = mAudioSessionRefs.size();
7272 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007273 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007274 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7275 ref->mCnt++;
7276 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007277 return;
7278 }
7279 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007280 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7281 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007282}
7283
7284void AudioFlinger::releaseAudioSessionId(int audioSession)
7285{
7286 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007287 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007288 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007289 size_t num = mAudioSessionRefs.size();
7290 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007291 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007292 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7293 ref->mCnt--;
7294 ALOGV(" decremented refcount to %d", ref->mCnt);
7295 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007296 mAudioSessionRefs.removeAt(i);
7297 delete ref;
7298 purgeStaleEffects_l();
7299 }
7300 return;
7301 }
7302 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007303 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007304}
7305
7306void AudioFlinger::purgeStaleEffects_l() {
7307
Steve Block3856b092011-10-20 11:56:00 +01007308 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007309
7310 Vector< sp<EffectChain> > chains;
7311
7312 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7313 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7314 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7315 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007316 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7317 chains.push(ec);
7318 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007319 }
7320 }
7321 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7322 sp<RecordThread> t = mRecordThreads.valueAt(i);
7323 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7324 sp<EffectChain> ec = t->mEffectChains[j];
7325 chains.push(ec);
7326 }
7327 }
7328
7329 for (size_t i = 0; i < chains.size(); i++) {
7330 sp<EffectChain> ec = chains[i];
7331 int sessionid = ec->sessionId();
7332 sp<ThreadBase> t = ec->mThread.promote();
7333 if (t == 0) {
7334 continue;
7335 }
7336 size_t numsessionrefs = mAudioSessionRefs.size();
7337 bool found = false;
7338 for (size_t k = 0; k < numsessionrefs; k++) {
7339 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007340 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007341 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007342 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007343 found = true;
7344 break;
7345 }
7346 }
7347 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007348 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007349 // remove all effects from the chain
7350 while (ec->mEffects.size()) {
7351 sp<EffectModule> effect = ec->mEffects[0];
7352 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007353 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007354 if (effect->purgeHandles()) {
7355 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007356 }
7357 AudioSystem::unregisterEffect(effect->id());
7358 }
7359 }
7360 }
7361 return;
7362}
7363
Mathias Agopian65ab4712010-07-14 17:59:35 -07007364// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007365AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007366{
Glenn Kastena1117922012-01-26 10:53:32 -08007367 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007368}
7369
7370// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007371AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007372{
7373 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007374 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007375}
7376
7377// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007378AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007379{
Glenn Kastena1117922012-01-26 10:53:32 -08007380 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007381}
7382
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007383uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007384{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007385 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007386}
7387
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007388AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007389{
7390 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7391 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007392 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07007393 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007394 return thread;
7395 }
7396 }
7397 return NULL;
7398}
7399
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007400audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007401{
7402 PlaybackThread *thread = primaryPlaybackThread_l();
7403
7404 if (thread == NULL) {
7405 return 0;
7406 }
7407
Eric Laurentf1c04f92012-08-28 14:26:53 -07007408 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007409}
7410
Eric Laurenta011e352012-03-29 15:51:43 -07007411sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7412 int triggerSession,
7413 int listenerSession,
7414 sync_event_callback_t callBack,
7415 void *cookie)
7416{
7417 Mutex::Autolock _l(mLock);
7418
7419 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7420 status_t playStatus = NAME_NOT_FOUND;
7421 status_t recStatus = NAME_NOT_FOUND;
7422 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7423 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7424 if (playStatus == NO_ERROR) {
7425 return event;
7426 }
7427 }
7428 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7429 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7430 if (recStatus == NO_ERROR) {
7431 return event;
7432 }
7433 }
7434 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7435 mPendingSyncEvents.add(event);
7436 } else {
7437 ALOGV("createSyncEvent() invalid event %d", event->type());
7438 event.clear();
7439 }
7440 return event;
7441}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007442
Mathias Agopian65ab4712010-07-14 17:59:35 -07007443// ----------------------------------------------------------------------------
7444// Effect management
7445// ----------------------------------------------------------------------------
7446
7447
Glenn Kastenf587ba52012-01-26 16:25:10 -08007448status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007449{
7450 Mutex::Autolock _l(mLock);
7451 return EffectQueryNumberEffects(numEffects);
7452}
7453
Glenn Kastenf587ba52012-01-26 16:25:10 -08007454status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007455{
7456 Mutex::Autolock _l(mLock);
7457 return EffectQueryEffect(index, descriptor);
7458}
7459
Glenn Kasten5e92a782012-01-30 07:40:52 -08007460status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007461 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007462{
7463 Mutex::Autolock _l(mLock);
7464 return EffectGetDescriptor(pUuid, descriptor);
7465}
7466
7467
Mathias Agopian65ab4712010-07-14 17:59:35 -07007468sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7469 effect_descriptor_t *pDesc,
7470 const sp<IEffectClient>& effectClient,
7471 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007472 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007473 int sessionId,
7474 status_t *status,
7475 int *id,
7476 int *enabled)
7477{
7478 status_t lStatus = NO_ERROR;
7479 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007480 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007481
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007482 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007483 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007484
7485 if (pDesc == NULL) {
7486 lStatus = BAD_VALUE;
7487 goto Exit;
7488 }
7489
Eric Laurent84e9a102010-09-23 16:10:16 -07007490 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007491 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007492 lStatus = PERMISSION_DENIED;
7493 goto Exit;
7494 }
7495
Dima Zavinfce7a472011-04-19 22:30:36 -07007496 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007497 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007498 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007499 lStatus = PERMISSION_DENIED;
7500 goto Exit;
7501 }
7502
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007503 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007504 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007505 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007506 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007507 lStatus = BAD_VALUE;
7508 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007509 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007510 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007511 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007512 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007513 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007514 }
7515 }
7516
Mathias Agopian65ab4712010-07-14 17:59:35 -07007517 {
7518 Mutex::Autolock _l(mLock);
7519
Mathias Agopian65ab4712010-07-14 17:59:35 -07007520
7521 if (!EffectIsNullUuid(&pDesc->uuid)) {
7522 // if uuid is specified, request effect descriptor
7523 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7524 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007525 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007526 goto Exit;
7527 }
7528 } else {
7529 // if uuid is not specified, look for an available implementation
7530 // of the required type in effect factory
7531 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007532 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007533 lStatus = BAD_VALUE;
7534 goto Exit;
7535 }
7536 uint32_t numEffects = 0;
7537 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007538 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007539 bool found = false;
7540
7541 lStatus = EffectQueryNumberEffects(&numEffects);
7542 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007543 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007544 goto Exit;
7545 }
7546 for (uint32_t i = 0; i < numEffects; i++) {
7547 lStatus = EffectQueryEffect(i, &desc);
7548 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007549 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007550 continue;
7551 }
7552 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7553 // If matching type found save effect descriptor. If the session is
7554 // 0 and the effect is not auxiliary, continue enumeration in case
7555 // an auxiliary version of this effect type is available
7556 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08007557 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07007558 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007559 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7560 break;
7561 }
7562 }
7563 }
7564 if (!found) {
7565 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007566 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007567 goto Exit;
7568 }
7569 // For same effect type, chose auxiliary version over insert version if
7570 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007571 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007572 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08007573 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007574 }
7575 }
7576
7577 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007578 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007579 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7580 lStatus = INVALID_OPERATION;
7581 goto Exit;
7582 }
7583
Eric Laurent59255e42011-07-27 19:49:51 -07007584 // check recording permission for visualizer
7585 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7586 !recordingAllowed()) {
7587 lStatus = PERMISSION_DENIED;
7588 goto Exit;
7589 }
7590
Mathias Agopian65ab4712010-07-14 17:59:35 -07007591 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08007592 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007593
7594 // If output is not specified try to find a matching audio session ID in one of the
7595 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007596 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7597 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007598 // Note: io is never 0 when creating an effect on an input
7599 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007600 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007601 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7602 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007603 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007604 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007605 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007606 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007607 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007608 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7609 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7610 io = mRecordThreads.keyAt(i);
7611 break;
7612 }
7613 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007614 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007615 // If no output thread contains the requested session ID, default to
7616 // first output. The effect chain will be moved to the correct output
7617 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007618 if (io == 0 && mPlaybackThreads.size()) {
7619 io = mPlaybackThreads.keyAt(0);
7620 }
Steve Block3856b092011-10-20 11:56:00 +01007621 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007622 }
7623 ThreadBase *thread = checkRecordThread_l(io);
7624 if (thread == NULL) {
7625 thread = checkPlaybackThread_l(io);
7626 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007627 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007628 lStatus = BAD_VALUE;
7629 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007630 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007631 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007632
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007633 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007634
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007635 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007636 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7637 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007638 if (handle != 0 && id != NULL) {
7639 *id = handle->id();
7640 }
7641 }
7642
7643Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007644 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007645 *status = lStatus;
7646 }
7647 return handle;
7648}
7649
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007650status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7651 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007652{
Steve Block3856b092011-10-20 11:56:00 +01007653 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007654 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007655 Mutex::Autolock _l(mLock);
7656 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007657 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007658 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007659 }
Eric Laurentde070132010-07-13 04:45:46 -07007660 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7661 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007662 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007663 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007664 }
Eric Laurentde070132010-07-13 04:45:46 -07007665 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7666 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007667 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007668 return BAD_VALUE;
7669 }
7670
7671 Mutex::Autolock _dl(dstThread->mLock);
7672 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007673 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007674
Mathias Agopian65ab4712010-07-14 17:59:35 -07007675 return NO_ERROR;
7676}
7677
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007678// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007679status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007680 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007681 AudioFlinger::PlaybackThread *dstThread,
7682 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007683{
Steve Block3856b092011-10-20 11:56:00 +01007684 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007685 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007686
Eric Laurent59255e42011-07-27 19:49:51 -07007687 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007688 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007689 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007690 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007691 return INVALID_OPERATION;
7692 }
7693
Eric Laurent39e94f82010-07-28 01:32:47 -07007694 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007695 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007696 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007697 // removed.
7698 srcThread->removeEffectChain_l(chain);
7699
7700 // transfer all effects one by one so that new effect chain is created on new thread with
7701 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007702 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007703 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007704 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007705 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7706 while (effect != 0) {
7707 srcThread->removeEffect_l(effect);
7708 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007709 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7710 if (effect->state() == EffectModule::ACTIVE ||
7711 effect->state() == EffectModule::STOPPING) {
7712 effect->start();
7713 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007714 // if the move request is not received from audio policy manager, the effect must be
7715 // re-registered with the new strategy and output
7716 if (dstChain == 0) {
7717 dstChain = effect->chain().promote();
7718 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007719 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007720 srcThread->addEffect_l(effect);
7721 return NO_INIT;
7722 }
7723 strategy = dstChain->strategy();
7724 }
7725 if (reRegister) {
7726 AudioSystem::unregisterEffect(effect->id());
7727 AudioSystem::registerEffect(&effect->desc(),
7728 dstOutput,
7729 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007730 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007731 effect->id());
7732 }
Eric Laurentde070132010-07-13 04:45:46 -07007733 effect = chain->getEffectFromId_l(0);
7734 }
7735
7736 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007737}
7738
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007739
Mathias Agopian65ab4712010-07-14 17:59:35 -07007740// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007741sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007742 const sp<AudioFlinger::Client>& client,
7743 const sp<IEffectClient>& effectClient,
7744 int32_t priority,
7745 int sessionId,
7746 effect_descriptor_t *desc,
7747 int *enabled,
7748 status_t *status
7749 )
7750{
7751 sp<EffectModule> effect;
7752 sp<EffectHandle> handle;
7753 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007754 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007755 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007756 bool effectCreated = false;
7757 bool effectRegistered = false;
7758
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007759 lStatus = initCheck();
7760 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007761 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007762 goto Exit;
7763 }
7764
7765 // Do not allow effects with session ID 0 on direct output or duplicating threads
7766 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007767 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007768 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007769 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007770 lStatus = BAD_VALUE;
7771 goto Exit;
7772 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007773 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007774 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007775 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007776 desc->name, desc->flags, mType);
7777 lStatus = BAD_VALUE;
7778 goto Exit;
7779 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007780
Steve Block3856b092011-10-20 11:56:00 +01007781 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007782
7783 { // scope for mLock
7784 Mutex::Autolock _l(mLock);
7785
7786 // check for existing effect chain with the requested audio session
7787 chain = getEffectChain_l(sessionId);
7788 if (chain == 0) {
7789 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007790 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007791 chain = new EffectChain(this, sessionId);
7792 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007793 chain->setStrategy(getStrategyForSession_l(sessionId));
7794 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007795 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007796 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007797 }
7798
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007799 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007800
7801 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007802 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007803 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007804 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007805 if (lStatus != NO_ERROR) {
7806 goto Exit;
7807 }
7808 effectRegistered = true;
7809 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007810 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007811 lStatus = effect->status();
7812 if (lStatus != NO_ERROR) {
7813 goto Exit;
7814 }
Eric Laurentcab11242010-07-15 12:50:15 -07007815 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007816 if (lStatus != NO_ERROR) {
7817 goto Exit;
7818 }
7819 effectCreated = true;
7820
Eric Laurentf1c04f92012-08-28 14:26:53 -07007821 effect->setDevice(mOutDevice);
7822 effect->setDevice(mInDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007823 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07007824 effect->setAudioSource(mAudioSource);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007825 }
7826 // create effect handle and connect it to effect module
7827 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007828 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007829 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007830 *enabled = (int)effect->isEnabled();
7831 }
7832 }
7833
7834Exit:
7835 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007836 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007837 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007838 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007839 }
7840 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007841 AudioSystem::unregisterEffect(effect->id());
7842 }
7843 if (chainCreated) {
7844 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007845 }
7846 handle.clear();
7847 }
7848
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007849 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007850 *status = lStatus;
7851 }
7852 return handle;
7853}
7854
Eric Laurent717e1282012-06-29 16:36:52 -07007855sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7856{
7857 Mutex::Autolock _l(mLock);
7858 return getEffect_l(sessionId, effectId);
7859}
7860
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007861sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7862{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007863 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007864 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007865}
7866
Eric Laurentde070132010-07-13 04:45:46 -07007867// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7868// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007869status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007870{
7871 // check for existing effect chain with the requested audio session
7872 int sessionId = effect->sessionId();
7873 sp<EffectChain> chain = getEffectChain_l(sessionId);
7874 bool chainCreated = false;
7875
7876 if (chain == 0) {
7877 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007878 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007879 chain = new EffectChain(this, sessionId);
7880 addEffectChain_l(chain);
7881 chain->setStrategy(getStrategyForSession_l(sessionId));
7882 chainCreated = true;
7883 }
Steve Block3856b092011-10-20 11:56:00 +01007884 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007885
7886 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007887 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007888 this, effect->desc().name, chain.get());
7889 return BAD_VALUE;
7890 }
7891
7892 status_t status = chain->addEffect_l(effect);
7893 if (status != NO_ERROR) {
7894 if (chainCreated) {
7895 removeEffectChain_l(chain);
7896 }
7897 return status;
7898 }
7899
Eric Laurentf1c04f92012-08-28 14:26:53 -07007900 effect->setDevice(mOutDevice);
7901 effect->setDevice(mInDevice);
Eric Laurentde070132010-07-13 04:45:46 -07007902 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07007903 effect->setAudioSource(mAudioSource);
Eric Laurentde070132010-07-13 04:45:46 -07007904 return NO_ERROR;
7905}
7906
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007907void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007908
Steve Block3856b092011-10-20 11:56:00 +01007909 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007910 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007911 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7912 detachAuxEffect_l(effect->id());
7913 }
7914
7915 sp<EffectChain> chain = effect->chain().promote();
7916 if (chain != 0) {
7917 // remove effect chain if removing last effect
7918 if (chain->removeEffect_l(effect) == 0) {
7919 removeEffectChain_l(chain);
7920 }
7921 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007922 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007923 }
7924}
7925
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007926void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007927 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007928{
7929 effectChains = mEffectChains;
7930 for (size_t i = 0; i < mEffectChains.size(); i++) {
7931 mEffectChains[i]->lock();
7932 }
7933}
7934
7935void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007936 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007937{
7938 for (size_t i = 0; i < effectChains.size(); i++) {
7939 effectChains[i]->unlock();
7940 }
7941}
7942
7943sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7944{
7945 Mutex::Autolock _l(mLock);
7946 return getEffectChain_l(sessionId);
7947}
7948
Glenn Kasten106e8a42012-08-02 13:37:12 -07007949sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007950{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007951 size_t size = mEffectChains.size();
7952 for (size_t i = 0; i < size; i++) {
7953 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007954 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007955 }
7956 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007957 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007958}
7959
Glenn Kastenf78aee72012-01-04 11:00:47 -08007960void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007961{
7962 Mutex::Autolock _l(mLock);
7963 size_t size = mEffectChains.size();
7964 for (size_t i = 0; i < size; i++) {
7965 mEffectChains[i]->setMode_l(mode);
7966 }
7967}
7968
7969void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007970 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007971 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007972
Mathias Agopian65ab4712010-07-14 17:59:35 -07007973 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007974 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007975 // delete the effect module if removing last handle on it
7976 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007977 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007978 removeEffect_l(effect);
7979 AudioSystem::unregisterEffect(effect->id());
7980 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007981 }
7982}
7983
7984status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7985{
7986 int session = chain->sessionId();
7987 int16_t *buffer = mMixBuffer;
7988 bool ownsBuffer = false;
7989
Steve Block3856b092011-10-20 11:56:00 +01007990 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007991 if (session > 0) {
7992 // Only one effect chain can be present in direct output thread and it uses
7993 // the mix buffer as input
7994 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007995 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007996 buffer = new int16_t[numSamples];
7997 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007998 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007999 ownsBuffer = true;
8000 }
8001
8002 // Attach all tracks with same session ID to this chain.
8003 for (size_t i = 0; i < mTracks.size(); ++i) {
8004 sp<Track> track = mTracks[i];
8005 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008006 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008007 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008008 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008009 }
8010 }
8011
8012 // indicate all active tracks in the chain
8013 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8014 sp<Track> track = mActiveTracks[i].promote();
8015 if (track == 0) continue;
8016 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008017 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07008018 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008019 }
8020 }
8021 }
8022
8023 chain->setInBuffer(buffer, ownsBuffer);
8024 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07008025 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07008026 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008027 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
8028 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008029 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07008030 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
8031 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07008032 // Effect chain for other sessions are inserted at beginning of effect
8033 // chains list to be processed before output mix effects. Relative order between other
8034 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07008035 size_t size = mEffectChains.size();
8036 size_t i = 0;
8037 for (i = 0; i < size; i++) {
8038 if (mEffectChains[i]->sessionId() < session) break;
8039 }
8040 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008041 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008042
8043 return NO_ERROR;
8044}
8045
8046size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
8047{
8048 int session = chain->sessionId();
8049
Steve Block3856b092011-10-20 11:56:00 +01008050 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008051
8052 for (size_t i = 0; i < mEffectChains.size(); i++) {
8053 if (chain == mEffectChains[i]) {
8054 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07008055 // detach all active tracks from the chain
8056 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8057 sp<Track> track = mActiveTracks[i].promote();
8058 if (track == 0) continue;
8059 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008060 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07008061 chain.get(), session);
8062 chain->decActiveTrackCnt();
8063 }
8064 }
8065
Mathias Agopian65ab4712010-07-14 17:59:35 -07008066 // detach all tracks with same session ID from this chain
8067 for (size_t i = 0; i < mTracks.size(); ++i) {
8068 sp<Track> track = mTracks[i];
8069 if (session == track->sessionId()) {
8070 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008071 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008072 }
8073 }
Eric Laurentde070132010-07-13 04:45:46 -07008074 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008075 }
8076 }
8077 return mEffectChains.size();
8078}
8079
Eric Laurentde070132010-07-13 04:45:46 -07008080status_t AudioFlinger::PlaybackThread::attachAuxEffect(
8081 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008082{
8083 Mutex::Autolock _l(mLock);
8084 return attachAuxEffect_l(track, EffectId);
8085}
8086
Eric Laurentde070132010-07-13 04:45:46 -07008087status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
8088 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008089{
8090 status_t status = NO_ERROR;
8091
8092 if (EffectId == 0) {
8093 track->setAuxBuffer(0, NULL);
8094 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07008095 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
8096 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008097 if (effect != 0) {
8098 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8099 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
8100 } else {
8101 status = INVALID_OPERATION;
8102 }
8103 } else {
8104 status = BAD_VALUE;
8105 }
8106 }
8107 return status;
8108}
8109
8110void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
8111{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008112 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008113 sp<Track> track = mTracks[i];
8114 if (track->auxEffectId() == effectId) {
8115 attachAuxEffect_l(track, 0);
8116 }
8117 }
8118}
8119
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008120status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8121{
8122 // only one chain per input thread
8123 if (mEffectChains.size() != 0) {
8124 return INVALID_OPERATION;
8125 }
Steve Block3856b092011-10-20 11:56:00 +01008126 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008127
8128 chain->setInBuffer(NULL);
8129 chain->setOutBuffer(NULL);
8130
Eric Laurent59255e42011-07-27 19:49:51 -07008131 checkSuspendOnAddEffectChain_l(chain);
8132
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008133 mEffectChains.add(chain);
8134
8135 return NO_ERROR;
8136}
8137
8138size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8139{
Steve Block3856b092011-10-20 11:56:00 +01008140 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00008141 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008142 "removeEffectChain_l() %p invalid chain size %d on thread %p",
8143 chain.get(), mEffectChains.size(), this);
8144 if (mEffectChains.size() == 1) {
8145 mEffectChains.removeAt(0);
8146 }
8147 return 0;
8148}
8149
Mathias Agopian65ab4712010-07-14 17:59:35 -07008150// ----------------------------------------------------------------------------
8151// EffectModule implementation
8152// ----------------------------------------------------------------------------
8153
8154#undef LOG_TAG
8155#define LOG_TAG "AudioFlinger::EffectModule"
8156
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008157AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008158 const wp<AudioFlinger::EffectChain>& chain,
8159 effect_descriptor_t *desc,
8160 int id,
8161 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07008162 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
8163 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07008164 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07008165 // mConfig is set by configure() and not used before then
8166 mEffectInterface(NULL),
8167 mStatus(NO_INIT), mState(IDLE),
8168 // mMaxDisableWaitCnt is set by configure() and not used before then
8169 // mDisableWaitCnt is set by process() and updateState() and not used before then
8170 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008171{
Steve Block3856b092011-10-20 11:56:00 +01008172 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008173 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008174
8175 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008176 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008177
8178 if (mStatus != NO_ERROR) {
8179 return;
8180 }
8181 lStatus = init();
8182 if (lStatus < 0) {
8183 mStatus = lStatus;
8184 goto Error;
8185 }
8186
Steve Block3856b092011-10-20 11:56:00 +01008187 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008188 return;
8189Error:
8190 EffectRelease(mEffectInterface);
8191 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008192 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008193}
8194
8195AudioFlinger::EffectModule::~EffectModule()
8196{
Steve Block3856b092011-10-20 11:56:00 +01008197 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008198 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008199 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8200 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8201 sp<ThreadBase> thread = mThread.promote();
8202 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008203 audio_stream_t *stream = thread->stream();
8204 if (stream != NULL) {
8205 stream->remove_audio_effect(stream, mEffectInterface);
8206 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008207 }
8208 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008209 // release effect engine
8210 EffectRelease(mEffectInterface);
8211 }
8212}
8213
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008214status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008215{
8216 status_t status;
8217
8218 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008219 int priority = handle->priority();
8220 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008221 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008222 size_t i;
8223 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008224 EffectHandle *h = mHandles[i];
8225 if (h == NULL || h->destroyed_l()) continue;
8226 // first non destroyed handle is considered in control
8227 if (controlHandle == NULL)
8228 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008229 if (h->priority() <= priority) break;
8230 }
8231 // if inserted in first place, move effect control from previous owner to this handle
8232 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008233 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008234 if (controlHandle != NULL) {
8235 enabled = controlHandle->enabled();
8236 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008237 }
Eric Laurent59255e42011-07-27 19:49:51 -07008238 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008239 status = NO_ERROR;
8240 } else {
8241 status = ALREADY_EXISTS;
8242 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008243 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008244 mHandles.insertAt(handle, i);
8245 return status;
8246}
8247
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008248size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008249{
8250 Mutex::Autolock _l(mLock);
8251 size_t size = mHandles.size();
8252 size_t i;
8253 for (i = 0; i < size; i++) {
8254 if (mHandles[i] == handle) break;
8255 }
8256 if (i == size) {
8257 return size;
8258 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008259 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008260
Mathias Agopian65ab4712010-07-14 17:59:35 -07008261 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008262 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008263 if (i == 0) {
8264 EffectHandle *h = controlHandle_l();
8265 if (h != NULL) {
8266 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008267 }
8268 }
8269
Eric Laurentec437d82011-07-26 20:54:46 -07008270 // Prevent calls to process() and other functions on effect interface from now on.
8271 // The effect engine will be released by the destructor when the last strong reference on
8272 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008273 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008274 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008275 }
8276
Eric Laurente65c8912012-07-20 15:57:23 -07008277 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008278}
8279
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008280// must be called with EffectModule::mLock held
8281AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008282{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008283 // the first valid handle in the list has control over the module
8284 for (size_t i = 0; i < mHandles.size(); i++) {
8285 EffectHandle *h = mHandles[i];
8286 if (h != NULL && !h->destroyed_l()) {
8287 return h;
8288 }
8289 }
8290
8291 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008292}
8293
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008294size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008295{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008296 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008297 // keep a strong reference on this EffectModule to avoid calling the
8298 // destructor before we exit
8299 sp<EffectModule> keep(this);
8300 {
8301 sp<ThreadBase> thread = mThread.promote();
8302 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008303 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008304 }
8305 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008306 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008307}
8308
8309void AudioFlinger::EffectModule::updateState() {
8310 Mutex::Autolock _l(mLock);
8311
8312 switch (mState) {
8313 case RESTART:
8314 reset_l();
8315 // FALL THROUGH
8316
8317 case STARTING:
8318 // clear auxiliary effect input buffer for next accumulation
8319 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8320 memset(mConfig.inputCfg.buffer.raw,
8321 0,
8322 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8323 }
8324 start_l();
8325 mState = ACTIVE;
8326 break;
8327 case STOPPING:
8328 stop_l();
8329 mDisableWaitCnt = mMaxDisableWaitCnt;
8330 mState = STOPPED;
8331 break;
8332 case STOPPED:
8333 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8334 // turn off sequence.
8335 if (--mDisableWaitCnt == 0) {
8336 reset_l();
8337 mState = IDLE;
8338 }
8339 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008340 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008341 break;
8342 }
8343}
8344
8345void AudioFlinger::EffectModule::process()
8346{
8347 Mutex::Autolock _l(mLock);
8348
Eric Laurentec437d82011-07-26 20:54:46 -07008349 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008350 mConfig.inputCfg.buffer.raw == NULL ||
8351 mConfig.outputCfg.buffer.raw == NULL) {
8352 return;
8353 }
8354
Eric Laurent8f45bd72010-08-31 13:50:07 -07008355 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008356 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8357 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008358 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008359 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008360 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008361 }
8362
8363 // do the actual processing in the effect engine
8364 int ret = (*mEffectInterface)->process(mEffectInterface,
8365 &mConfig.inputCfg.buffer,
8366 &mConfig.outputCfg.buffer);
8367
8368 // force transition to IDLE state when engine is ready
8369 if (mState == STOPPED && ret == -ENODATA) {
8370 mDisableWaitCnt = 1;
8371 }
8372
8373 // clear auxiliary effect input buffer for next accumulation
8374 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008375 memset(mConfig.inputCfg.buffer.raw, 0,
8376 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008377 }
8378 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008379 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8380 // If an insert effect is idle and input buffer is different from output buffer,
8381 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008382 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008383 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008384 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8385 int16_t *in = mConfig.inputCfg.buffer.s16;
8386 int16_t *out = mConfig.outputCfg.buffer.s16;
8387 for (size_t i = 0; i < frameCnt; i++) {
8388 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008389 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008390 }
8391 }
8392}
8393
8394void AudioFlinger::EffectModule::reset_l()
8395{
8396 if (mEffectInterface == NULL) {
8397 return;
8398 }
8399 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8400}
8401
8402status_t AudioFlinger::EffectModule::configure()
8403{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008404 if (mEffectInterface == NULL) {
8405 return NO_INIT;
8406 }
8407
8408 sp<ThreadBase> thread = mThread.promote();
8409 if (thread == 0) {
8410 return DEAD_OBJECT;
8411 }
8412
8413 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07008414 audio_channel_mask_t channelMask = thread->channelMask();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008415
8416 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008417 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008418 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07008419 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008420 }
Glenn Kasten254af182012-07-03 14:59:05 -07008421 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07008422 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8423 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008424 mConfig.inputCfg.samplingRate = thread->sampleRate();
8425 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8426 mConfig.inputCfg.bufferProvider.cookie = NULL;
8427 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8428 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8429 mConfig.outputCfg.bufferProvider.cookie = NULL;
8430 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8431 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8432 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8433 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008434 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008435 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008436 // - in other sessions:
8437 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8438 // other effect: overwrites output buffer: input buffer == output buffer
8439 // Auxiliary effect:
8440 // accumulates in output buffer: input buffer != output buffer
8441 // Therefore: accumulate <=> input buffer != output buffer
8442 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8443 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8444 } else {
8445 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8446 }
8447 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8448 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8449 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8450 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8451
Steve Block3856b092011-10-20 11:56:00 +01008452 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008453 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8454
Mathias Agopian65ab4712010-07-14 17:59:35 -07008455 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008456 uint32_t size = sizeof(int);
8457 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008458 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008459 sizeof(effect_config_t),
8460 &mConfig,
8461 &size,
8462 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008463 if (status == 0) {
8464 status = cmdStatus;
8465 }
8466
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008467 if (status == 0 &&
8468 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8469 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8470 effect_param_t *p = (effect_param_t *)buf32;
8471
8472 p->psize = sizeof(uint32_t);
8473 p->vsize = sizeof(uint32_t);
8474 size = sizeof(int);
8475 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8476
8477 uint32_t latency = 0;
8478 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8479 if (pbt != NULL) {
8480 latency = pbt->latency_l();
8481 }
8482
8483 *((int32_t *)p->data + 1)= latency;
8484 (*mEffectInterface)->command(mEffectInterface,
8485 EFFECT_CMD_SET_PARAM,
8486 sizeof(effect_param_t) + 8,
8487 &buf32,
8488 &size,
8489 &cmdStatus);
8490 }
8491
Mathias Agopian65ab4712010-07-14 17:59:35 -07008492 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8493 (1000 * mConfig.outputCfg.buffer.frameCount);
8494
8495 return status;
8496}
8497
8498status_t AudioFlinger::EffectModule::init()
8499{
8500 Mutex::Autolock _l(mLock);
8501 if (mEffectInterface == NULL) {
8502 return NO_INIT;
8503 }
8504 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008505 uint32_t size = sizeof(status_t);
8506 status_t status = (*mEffectInterface)->command(mEffectInterface,
8507 EFFECT_CMD_INIT,
8508 0,
8509 NULL,
8510 &size,
8511 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008512 if (status == 0) {
8513 status = cmdStatus;
8514 }
8515 return status;
8516}
8517
Eric Laurentec35a142011-10-05 17:42:25 -07008518status_t AudioFlinger::EffectModule::start()
8519{
8520 Mutex::Autolock _l(mLock);
8521 return start_l();
8522}
8523
Mathias Agopian65ab4712010-07-14 17:59:35 -07008524status_t AudioFlinger::EffectModule::start_l()
8525{
8526 if (mEffectInterface == NULL) {
8527 return NO_INIT;
8528 }
8529 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008530 uint32_t size = sizeof(status_t);
8531 status_t status = (*mEffectInterface)->command(mEffectInterface,
8532 EFFECT_CMD_ENABLE,
8533 0,
8534 NULL,
8535 &size,
8536 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008537 if (status == 0) {
8538 status = cmdStatus;
8539 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008540 if (status == 0 &&
8541 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8542 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8543 sp<ThreadBase> thread = mThread.promote();
8544 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008545 audio_stream_t *stream = thread->stream();
8546 if (stream != NULL) {
8547 stream->add_audio_effect(stream, mEffectInterface);
8548 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008549 }
8550 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008551 return status;
8552}
8553
Eric Laurentec437d82011-07-26 20:54:46 -07008554status_t AudioFlinger::EffectModule::stop()
8555{
8556 Mutex::Autolock _l(mLock);
8557 return stop_l();
8558}
8559
Mathias Agopian65ab4712010-07-14 17:59:35 -07008560status_t AudioFlinger::EffectModule::stop_l()
8561{
8562 if (mEffectInterface == NULL) {
8563 return NO_INIT;
8564 }
8565 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008566 uint32_t size = sizeof(status_t);
8567 status_t status = (*mEffectInterface)->command(mEffectInterface,
8568 EFFECT_CMD_DISABLE,
8569 0,
8570 NULL,
8571 &size,
8572 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008573 if (status == 0) {
8574 status = cmdStatus;
8575 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008576 if (status == 0 &&
8577 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8578 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8579 sp<ThreadBase> thread = mThread.promote();
8580 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008581 audio_stream_t *stream = thread->stream();
8582 if (stream != NULL) {
8583 stream->remove_audio_effect(stream, mEffectInterface);
8584 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008585 }
8586 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008587 return status;
8588}
8589
Eric Laurent25f43952010-07-28 05:40:18 -07008590status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8591 uint32_t cmdSize,
8592 void *pCmdData,
8593 uint32_t *replySize,
8594 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008595{
8596 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008597// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008598
Eric Laurentec437d82011-07-26 20:54:46 -07008599 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008600 return NO_INIT;
8601 }
Eric Laurent25f43952010-07-28 05:40:18 -07008602 status_t status = (*mEffectInterface)->command(mEffectInterface,
8603 cmdCode,
8604 cmdSize,
8605 pCmdData,
8606 replySize,
8607 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008608 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008609 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008610 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008611 EffectHandle *h = mHandles[i];
8612 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008613 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8614 }
8615 }
8616 }
8617 return status;
8618}
8619
8620status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8621{
8622 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008623 return setEnabled_l(enabled);
8624}
8625
8626// must be called with EffectModule::mLock held
8627status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8628{
8629
Steve Block3856b092011-10-20 11:56:00 +01008630 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008631
8632 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008633 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8634 if (enabled && status != NO_ERROR) {
8635 return status;
8636 }
8637
Mathias Agopian65ab4712010-07-14 17:59:35 -07008638 switch (mState) {
8639 // going from disabled to enabled
8640 case IDLE:
8641 mState = STARTING;
8642 break;
8643 case STOPPED:
8644 mState = RESTART;
8645 break;
8646 case STOPPING:
8647 mState = ACTIVE;
8648 break;
8649
8650 // going from enabled to disabled
8651 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008652 mState = STOPPED;
8653 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008654 case STARTING:
8655 mState = IDLE;
8656 break;
8657 case ACTIVE:
8658 mState = STOPPING;
8659 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008660 case DESTROYED:
8661 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008662 }
8663 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008664 EffectHandle *h = mHandles[i];
8665 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008666 h->setEnabled(enabled);
8667 }
8668 }
8669 }
8670 return NO_ERROR;
8671}
8672
Glenn Kastenc59c0042012-02-02 14:06:11 -08008673bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008674{
8675 switch (mState) {
8676 case RESTART:
8677 case STARTING:
8678 case ACTIVE:
8679 return true;
8680 case IDLE:
8681 case STOPPING:
8682 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008683 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008684 default:
8685 return false;
8686 }
8687}
8688
Glenn Kastenc59c0042012-02-02 14:06:11 -08008689bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008690{
8691 switch (mState) {
8692 case RESTART:
8693 case ACTIVE:
8694 case STOPPING:
8695 case STOPPED:
8696 return true;
8697 case IDLE:
8698 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008699 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008700 default:
8701 return false;
8702 }
8703}
8704
Mathias Agopian65ab4712010-07-14 17:59:35 -07008705status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8706{
8707 Mutex::Autolock _l(mLock);
8708 status_t status = NO_ERROR;
8709
8710 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8711 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008712 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008713 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8714 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008715 status_t cmdStatus;
8716 uint32_t volume[2];
8717 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008718 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008719 volume[0] = *left;
8720 volume[1] = *right;
8721 if (controller) {
8722 pVolume = volume;
8723 }
Eric Laurent25f43952010-07-28 05:40:18 -07008724 status = (*mEffectInterface)->command(mEffectInterface,
8725 EFFECT_CMD_SET_VOLUME,
8726 size,
8727 volume,
8728 &size,
8729 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008730 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8731 *left = volume[0];
8732 *right = volume[1];
8733 }
8734 }
8735 return status;
8736}
8737
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008738status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008739{
Eric Laurentf1c04f92012-08-28 14:26:53 -07008740 if (device == AUDIO_DEVICE_NONE) {
8741 return NO_ERROR;
8742 }
8743
Mathias Agopian65ab4712010-07-14 17:59:35 -07008744 Mutex::Autolock _l(mLock);
8745 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008746 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07008747 status_t cmdStatus;
8748 uint32_t size = sizeof(status_t);
8749 uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE :
8750 EFFECT_CMD_SET_INPUT_DEVICE;
8751 status = (*mEffectInterface)->command(mEffectInterface,
8752 cmd,
8753 sizeof(uint32_t),
8754 &device,
8755 &size,
8756 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008757 }
8758 return status;
8759}
8760
Glenn Kastenf78aee72012-01-04 11:00:47 -08008761status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008762{
8763 Mutex::Autolock _l(mLock);
8764 status_t status = NO_ERROR;
8765 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008766 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008767 uint32_t size = sizeof(status_t);
8768 status = (*mEffectInterface)->command(mEffectInterface,
8769 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008770 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008771 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008772 &size,
8773 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008774 if (status == NO_ERROR) {
8775 status = cmdStatus;
8776 }
8777 }
8778 return status;
8779}
8780
Eric Laurent57b2dd12012-08-31 17:44:06 -07008781status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
8782{
8783 Mutex::Autolock _l(mLock);
8784 status_t status = NO_ERROR;
8785 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
8786 uint32_t size = 0;
8787 status = (*mEffectInterface)->command(mEffectInterface,
8788 EFFECT_CMD_SET_AUDIO_SOURCE,
8789 sizeof(audio_source_t),
8790 &source,
8791 &size,
8792 NULL);
8793 }
8794 return status;
8795}
8796
Eric Laurent59255e42011-07-27 19:49:51 -07008797void AudioFlinger::EffectModule::setSuspended(bool suspended)
8798{
8799 Mutex::Autolock _l(mLock);
8800 mSuspended = suspended;
8801}
Glenn Kastena3a85482012-01-04 11:01:11 -08008802
8803bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008804{
8805 Mutex::Autolock _l(mLock);
8806 return mSuspended;
8807}
8808
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008809bool AudioFlinger::EffectModule::purgeHandles()
8810{
8811 bool enabled = false;
8812 Mutex::Autolock _l(mLock);
8813 for (size_t i = 0; i < mHandles.size(); i++) {
8814 EffectHandle *handle = mHandles[i];
8815 if (handle != NULL && !handle->destroyed_l()) {
8816 handle->effect().clear();
8817 if (handle->hasControl()) {
8818 enabled = handle->enabled();
8819 }
8820 }
8821 }
8822 return enabled;
8823}
8824
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07008825void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008826{
8827 const size_t SIZE = 256;
8828 char buffer[SIZE];
8829 String8 result;
8830
8831 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8832 result.append(buffer);
8833
8834 bool locked = tryLock(mLock);
8835 // failed to lock - AudioFlinger is probably deadlocked
8836 if (!locked) {
8837 result.append("\t\tCould not lock Fx mutex:\n");
8838 }
8839
8840 result.append("\t\tSession Status State Engine:\n");
8841 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8842 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8843 result.append(buffer);
8844
8845 result.append("\t\tDescriptor:\n");
8846 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8847 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8848 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8849 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8850 result.append(buffer);
8851 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8852 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8853 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8854 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8855 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008856 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008857 mDescriptor.apiVersion,
8858 mDescriptor.flags);
8859 result.append(buffer);
8860 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8861 mDescriptor.name);
8862 result.append(buffer);
8863 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8864 mDescriptor.implementor);
8865 result.append(buffer);
8866
8867 result.append("\t\t- Input configuration:\n");
8868 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8869 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8870 (uint32_t)mConfig.inputCfg.buffer.raw,
8871 mConfig.inputCfg.buffer.frameCount,
8872 mConfig.inputCfg.samplingRate,
8873 mConfig.inputCfg.channels,
8874 mConfig.inputCfg.format);
8875 result.append(buffer);
8876
8877 result.append("\t\t- Output configuration:\n");
8878 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8879 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8880 (uint32_t)mConfig.outputCfg.buffer.raw,
8881 mConfig.outputCfg.buffer.frameCount,
8882 mConfig.outputCfg.samplingRate,
8883 mConfig.outputCfg.channels,
8884 mConfig.outputCfg.format);
8885 result.append(buffer);
8886
8887 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8888 result.append(buffer);
8889 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8890 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008891 EffectHandle *handle = mHandles[i];
8892 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008893 handle->dump(buffer, SIZE);
8894 result.append(buffer);
8895 }
8896 }
8897
8898 result.append("\n");
8899
8900 write(fd, result.string(), result.length());
8901
8902 if (locked) {
8903 mLock.unlock();
8904 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008905}
8906
8907// ----------------------------------------------------------------------------
8908// EffectHandle implementation
8909// ----------------------------------------------------------------------------
8910
8911#undef LOG_TAG
8912#define LOG_TAG "AudioFlinger::EffectHandle"
8913
8914AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8915 const sp<AudioFlinger::Client>& client,
8916 const sp<IEffectClient>& effectClient,
8917 int32_t priority)
8918 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008919 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008920 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008921{
Steve Block3856b092011-10-20 11:56:00 +01008922 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008923
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008924 if (client == 0) {
8925 return;
8926 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008927 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8928 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8929 if (mCblkMemory != 0) {
8930 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8931
Glenn Kastena0d68332012-01-27 16:47:15 -08008932 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008933 new(mCblk) effect_param_cblk_t();
8934 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008935 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008936 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008937 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008938 return;
8939 }
8940}
8941
8942AudioFlinger::EffectHandle::~EffectHandle()
8943{
Steve Block3856b092011-10-20 11:56:00 +01008944 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008945
8946 if (mEffect == 0) {
8947 mDestroyed = true;
8948 return;
8949 }
8950 mEffect->lock();
8951 mDestroyed = true;
8952 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008953 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008954}
8955
8956status_t AudioFlinger::EffectHandle::enable()
8957{
Steve Block3856b092011-10-20 11:56:00 +01008958 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008959 if (!mHasControl) return INVALID_OPERATION;
8960 if (mEffect == 0) return DEAD_OBJECT;
8961
Eric Laurentdb7c0792011-08-10 10:37:50 -07008962 if (mEnabled) {
8963 return NO_ERROR;
8964 }
8965
Eric Laurent59255e42011-07-27 19:49:51 -07008966 mEnabled = true;
8967
8968 sp<ThreadBase> thread = mEffect->thread().promote();
8969 if (thread != 0) {
8970 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8971 }
8972
8973 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8974 if (mEffect->suspended()) {
8975 return NO_ERROR;
8976 }
8977
Eric Laurentdb7c0792011-08-10 10:37:50 -07008978 status_t status = mEffect->setEnabled(true);
8979 if (status != NO_ERROR) {
8980 if (thread != 0) {
8981 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8982 }
8983 mEnabled = false;
8984 }
8985 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008986}
8987
8988status_t AudioFlinger::EffectHandle::disable()
8989{
Steve Block3856b092011-10-20 11:56:00 +01008990 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008991 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008992 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008993
Eric Laurentdb7c0792011-08-10 10:37:50 -07008994 if (!mEnabled) {
8995 return NO_ERROR;
8996 }
Eric Laurent59255e42011-07-27 19:49:51 -07008997 mEnabled = false;
8998
8999 if (mEffect->suspended()) {
9000 return NO_ERROR;
9001 }
9002
9003 status_t status = mEffect->setEnabled(false);
9004
9005 sp<ThreadBase> thread = mEffect->thread().promote();
9006 if (thread != 0) {
9007 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9008 }
9009
9010 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009011}
9012
9013void AudioFlinger::EffectHandle::disconnect()
9014{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009015 disconnect(true);
9016}
9017
Glenn Kasten58123c32012-02-03 10:32:24 -08009018void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009019{
Glenn Kasten58123c32012-02-03 10:32:24 -08009020 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009021 if (mEffect == 0) {
9022 return;
9023 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009024 // restore suspended effects if the disconnected handle was enabled and the last one.
9025 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009026 sp<ThreadBase> thread = mEffect->thread().promote();
9027 if (thread != 0) {
9028 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9029 }
Eric Laurent59255e42011-07-27 19:49:51 -07009030 }
9031
Mathias Agopian65ab4712010-07-14 17:59:35 -07009032 // release sp on module => module destructor can be called now
9033 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009034 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08009035 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08009036 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009037 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
9038 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08009039 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08009040 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07009041 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
9042 mClient.clear();
9043 }
9044}
9045
Eric Laurent25f43952010-07-28 05:40:18 -07009046status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
9047 uint32_t cmdSize,
9048 void *pCmdData,
9049 uint32_t *replySize,
9050 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009051{
Steve Block3856b092011-10-20 11:56:00 +01009052// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07009053// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07009054
9055 // only get parameter command is permitted for applications not controlling the effect
9056 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
9057 return INVALID_OPERATION;
9058 }
9059 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009060 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009061
9062 // handle commands that are not forwarded transparently to effect engine
9063 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
9064 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
9065 // no risk to block the whole media server process or mixer threads is we are stuck here
9066 Mutex::Autolock _l(mCblk->lock);
9067 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
9068 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
9069 mCblk->serverIndex = 0;
9070 mCblk->clientIndex = 0;
9071 return BAD_VALUE;
9072 }
9073 status_t status = NO_ERROR;
9074 while (mCblk->serverIndex < mCblk->clientIndex) {
9075 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07009076 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009077 int *p = (int *)(mBuffer + mCblk->serverIndex);
9078 int size = *p++;
9079 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009080 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009081 break;
9082 }
9083 effect_param_t *param = (effect_param_t *)p;
9084 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009085 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009086 mCblk->serverIndex += size;
9087 continue;
9088 }
Eric Laurent25f43952010-07-28 05:40:18 -07009089 uint32_t psize = sizeof(effect_param_t) +
9090 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
9091 param->vsize;
9092 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
9093 psize,
9094 p,
9095 &rsize,
9096 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07009097 // stop at first error encountered
9098 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009099 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07009100 *(int *)pReplyData = reply;
9101 break;
9102 } else if (reply != NO_ERROR) {
9103 *(int *)pReplyData = reply;
9104 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009105 }
9106 mCblk->serverIndex += size;
9107 }
9108 mCblk->serverIndex = 0;
9109 mCblk->clientIndex = 0;
9110 return status;
9111 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009112 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009113 return enable();
9114 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009115 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009116 return disable();
9117 }
9118
9119 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9120}
9121
Eric Laurent59255e42011-07-27 19:49:51 -07009122void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009123{
Steve Block3856b092011-10-20 11:56:00 +01009124 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009125
9126 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07009127 mEnabled = enabled;
9128
Mathias Agopian65ab4712010-07-14 17:59:35 -07009129 if (signal && mEffectClient != 0) {
9130 mEffectClient->controlStatusChanged(hasControl);
9131 }
9132}
9133
Eric Laurent25f43952010-07-28 05:40:18 -07009134void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
9135 uint32_t cmdSize,
9136 void *pCmdData,
9137 uint32_t replySize,
9138 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009139{
9140 if (mEffectClient != 0) {
9141 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9142 }
9143}
9144
9145
9146
9147void AudioFlinger::EffectHandle::setEnabled(bool enabled)
9148{
9149 if (mEffectClient != 0) {
9150 mEffectClient->enableStatusChanged(enabled);
9151 }
9152}
9153
9154status_t AudioFlinger::EffectHandle::onTransact(
9155 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9156{
9157 return BnEffect::onTransact(code, data, reply, flags);
9158}
9159
9160
9161void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
9162{
Glenn Kastena0d68332012-01-27 16:47:15 -08009163 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009164
9165 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08009166 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07009167 mPriority,
9168 mHasControl,
9169 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009170 mCblk ? mCblk->clientIndex : 0,
9171 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07009172 );
9173
9174 if (locked) {
9175 mCblk->lock.unlock();
9176 }
9177}
9178
9179#undef LOG_TAG
9180#define LOG_TAG "AudioFlinger::EffectChain"
9181
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009182AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009183 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009184 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07009185 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9186 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009187{
Dima Zavinfce7a472011-04-19 22:30:36 -07009188 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009189 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009190 return;
9191 }
9192 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9193 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009194}
9195
9196AudioFlinger::EffectChain::~EffectChain()
9197{
9198 if (mOwnInBuffer) {
9199 delete mInBuffer;
9200 }
9201
9202}
9203
Eric Laurent59255e42011-07-27 19:49:51 -07009204// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009205sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009206{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009207 size_t size = mEffects.size();
9208
9209 for (size_t i = 0; i < size; i++) {
9210 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009211 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009212 }
9213 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009214 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009215}
9216
Eric Laurent59255e42011-07-27 19:49:51 -07009217// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009218sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009219{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009220 size_t size = mEffects.size();
9221
9222 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009223 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9224 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009225 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009226 }
9227 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009228 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009229}
9230
Eric Laurent59255e42011-07-27 19:49:51 -07009231// getEffectFromType_l() must be called with ThreadBase::mLock held
9232sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9233 const effect_uuid_t *type)
9234{
Eric Laurent59255e42011-07-27 19:49:51 -07009235 size_t size = mEffects.size();
9236
9237 for (size_t i = 0; i < size; i++) {
9238 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009239 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009240 }
9241 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009242 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009243}
9244
Eric Laurent91b14c42012-05-30 12:30:29 -07009245void AudioFlinger::EffectChain::clearInputBuffer()
9246{
9247 Mutex::Autolock _l(mLock);
9248 sp<ThreadBase> thread = mThread.promote();
9249 if (thread == 0) {
9250 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9251 return;
9252 }
9253 clearInputBuffer_l(thread);
9254}
9255
9256// Must be called with EffectChain::mLock locked
9257void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9258{
9259 size_t numSamples = thread->frameCount() * thread->channelCount();
9260 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9261
9262}
9263
Mathias Agopian65ab4712010-07-14 17:59:35 -07009264// Must be called with EffectChain::mLock locked
9265void AudioFlinger::EffectChain::process_l()
9266{
Eric Laurentdac69112010-09-28 14:09:57 -07009267 sp<ThreadBase> thread = mThread.promote();
9268 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009269 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009270 return;
9271 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009272 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9273 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009274 // always process effects unless no more tracks are on the session and the effect tail
9275 // has been rendered
9276 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009277 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009278 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009279
Eric Laurent544fe9b2011-11-11 15:42:52 -08009280 if (!tracksOnSession && mTailBufferCount == 0) {
9281 doProcess = false;
9282 }
9283
9284 if (activeTrackCnt() == 0) {
9285 // if no track is active and the effect tail has not been rendered,
9286 // the input buffer must be cleared here as the mixer process will not do it
9287 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009288 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009289 if (mTailBufferCount > 0) {
9290 mTailBufferCount--;
9291 }
9292 }
9293 }
Eric Laurentdac69112010-09-28 14:09:57 -07009294 }
9295
Mathias Agopian65ab4712010-07-14 17:59:35 -07009296 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009297 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009298 for (size_t i = 0; i < size; i++) {
9299 mEffects[i]->process();
9300 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009301 }
9302 for (size_t i = 0; i < size; i++) {
9303 mEffects[i]->updateState();
9304 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009305}
9306
Eric Laurentcab11242010-07-15 12:50:15 -07009307// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009308status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009309{
9310 effect_descriptor_t desc = effect->desc();
9311 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9312
9313 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009314 effect->setChain(this);
9315 sp<ThreadBase> thread = mThread.promote();
9316 if (thread == 0) {
9317 return NO_INIT;
9318 }
9319 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009320
9321 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9322 // Auxiliary effects are inserted at the beginning of mEffects vector as
9323 // they are processed first and accumulated in chain input buffer
9324 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009325
Mathias Agopian65ab4712010-07-14 17:59:35 -07009326 // the input buffer for auxiliary effect contains mono samples in
9327 // 32 bit format. This is to avoid saturation in AudoMixer
9328 // accumulation stage. Saturation is done in EffectModule::process() before
9329 // calling the process in effect engine
9330 size_t numSamples = thread->frameCount();
9331 int32_t *buffer = new int32_t[numSamples];
9332 memset(buffer, 0, numSamples * sizeof(int32_t));
9333 effect->setInBuffer((int16_t *)buffer);
9334 // auxiliary effects output samples to chain input buffer for further processing
9335 // by insert effects
9336 effect->setOutBuffer(mInBuffer);
9337 } else {
9338 // Insert effects are inserted at the end of mEffects vector as they are processed
9339 // after track and auxiliary effects.
9340 // Insert effect order as a function of indicated preference:
9341 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9342 // another effect is present
9343 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9344 // last effect claiming first position
9345 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9346 // first effect claiming last position
9347 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9348 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9349 // already present
9350
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009351 size_t size = mEffects.size();
9352 size_t idx_insert = size;
9353 ssize_t idx_insert_first = -1;
9354 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009355
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009356 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009357 effect_descriptor_t d = mEffects[i]->desc();
9358 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9359 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9360 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9361 // check invalid effect chaining combinations
9362 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9363 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009364 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009365 return INVALID_OPERATION;
9366 }
9367 // remember position of first insert effect and by default
9368 // select this as insert position for new effect
9369 if (idx_insert == size) {
9370 idx_insert = i;
9371 }
9372 // remember position of last insert effect claiming
9373 // first position
9374 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9375 idx_insert_first = i;
9376 }
9377 // remember position of first insert effect claiming
9378 // last position
9379 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9380 idx_insert_last == -1) {
9381 idx_insert_last = i;
9382 }
9383 }
9384 }
9385
9386 // modify idx_insert from first position if needed
9387 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9388 if (idx_insert_last != -1) {
9389 idx_insert = idx_insert_last;
9390 } else {
9391 idx_insert = size;
9392 }
9393 } else {
9394 if (idx_insert_first != -1) {
9395 idx_insert = idx_insert_first + 1;
9396 }
9397 }
9398
9399 // always read samples from chain input buffer
9400 effect->setInBuffer(mInBuffer);
9401
9402 // if last effect in the chain, output samples to chain
9403 // output buffer, otherwise to chain input buffer
9404 if (idx_insert == size) {
9405 if (idx_insert != 0) {
9406 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9407 mEffects[idx_insert-1]->configure();
9408 }
9409 effect->setOutBuffer(mOutBuffer);
9410 } else {
9411 effect->setOutBuffer(mInBuffer);
9412 }
9413 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009414
Steve Block3856b092011-10-20 11:56:00 +01009415 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009416 }
9417 effect->configure();
9418 return NO_ERROR;
9419}
9420
Eric Laurentcab11242010-07-15 12:50:15 -07009421// removeEffect_l() must be called with PlaybackThread::mLock held
9422size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009423{
9424 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009425 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009426 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9427
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009428 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009429 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009430 // calling stop here will remove pre-processing effect from the audio HAL.
9431 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9432 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009433 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9434 mEffects[i]->state() == EffectModule::STOPPING) {
9435 mEffects[i]->stop();
9436 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009437 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9438 delete[] effect->inBuffer();
9439 } else {
9440 if (i == size - 1 && i != 0) {
9441 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9442 mEffects[i - 1]->configure();
9443 }
9444 }
9445 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009446 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009447 break;
9448 }
9449 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009450
9451 return mEffects.size();
9452}
9453
Eric Laurentcab11242010-07-15 12:50:15 -07009454// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009455void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009456{
9457 size_t size = mEffects.size();
9458 for (size_t i = 0; i < size; i++) {
9459 mEffects[i]->setDevice(device);
9460 }
9461}
9462
Eric Laurentcab11242010-07-15 12:50:15 -07009463// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009464void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009465{
9466 size_t size = mEffects.size();
9467 for (size_t i = 0; i < size; i++) {
9468 mEffects[i]->setMode(mode);
9469 }
9470}
9471
Eric Laurent57b2dd12012-08-31 17:44:06 -07009472// setAudioSource_l() must be called with PlaybackThread::mLock held
9473void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
9474{
9475 size_t size = mEffects.size();
9476 for (size_t i = 0; i < size; i++) {
9477 mEffects[i]->setAudioSource(source);
9478 }
9479}
9480
Eric Laurentcab11242010-07-15 12:50:15 -07009481// setVolume_l() must be called with PlaybackThread::mLock held
9482bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009483{
9484 uint32_t newLeft = *left;
9485 uint32_t newRight = *right;
9486 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009487 int ctrlIdx = -1;
9488 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009489
Eric Laurentcab11242010-07-15 12:50:15 -07009490 // first update volume controller
9491 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009492 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009493 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9494 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009495 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009496 break;
9497 }
9498 }
9499
9500 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009501 if (hasControl) {
9502 *left = mNewLeftVolume;
9503 *right = mNewRightVolume;
9504 }
9505 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009506 }
9507
9508 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009509 mLeftVolume = newLeft;
9510 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009511
9512 // second get volume update from volume controller
9513 if (ctrlIdx >= 0) {
9514 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009515 mNewLeftVolume = newLeft;
9516 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009517 }
9518 // then indicate volume to all other effects in chain.
9519 // Pass altered volume to effects before volume controller
9520 // and requested volume to effects after controller
9521 uint32_t lVol = newLeft;
9522 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009523
Mathias Agopian65ab4712010-07-14 17:59:35 -07009524 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009525 if ((int)i == ctrlIdx) continue;
9526 // this also works for ctrlIdx == -1 when there is no volume controller
9527 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009528 lVol = *left;
9529 rVol = *right;
9530 }
9531 mEffects[i]->setVolume(&lVol, &rVol, false);
9532 }
9533 *left = newLeft;
9534 *right = newRight;
9535
9536 return hasControl;
9537}
9538
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009539void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009540{
9541 const size_t SIZE = 256;
9542 char buffer[SIZE];
9543 String8 result;
9544
9545 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9546 result.append(buffer);
9547
9548 bool locked = tryLock(mLock);
9549 // failed to lock - AudioFlinger is probably deadlocked
9550 if (!locked) {
9551 result.append("\tCould not lock mutex:\n");
9552 }
9553
Eric Laurentcab11242010-07-15 12:50:15 -07009554 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9555 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009556 mEffects.size(),
9557 (uint32_t)mInBuffer,
9558 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009559 mActiveTrackCnt);
9560 result.append(buffer);
9561 write(fd, result.string(), result.size());
9562
9563 for (size_t i = 0; i < mEffects.size(); ++i) {
9564 sp<EffectModule> effect = mEffects[i];
9565 if (effect != 0) {
9566 effect->dump(fd, args);
9567 }
9568 }
9569
9570 if (locked) {
9571 mLock.unlock();
9572 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009573}
9574
Eric Laurent59255e42011-07-27 19:49:51 -07009575// must be called with ThreadBase::mLock held
9576void AudioFlinger::EffectChain::setEffectSuspended_l(
9577 const effect_uuid_t *type, bool suspend)
9578{
9579 sp<SuspendedEffectDesc> desc;
9580 // use effect type UUID timelow as key as there is no real risk of identical
9581 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009582 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009583 if (suspend) {
9584 if (index >= 0) {
9585 desc = mSuspendedEffects.valueAt(index);
9586 } else {
9587 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -08009588 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07009589 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009590 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009591 }
9592 if (desc->mRefCount++ == 0) {
9593 sp<EffectModule> effect = getEffectIfEnabled(type);
9594 if (effect != 0) {
9595 desc->mEffect = effect;
9596 effect->setSuspended(true);
9597 effect->setEnabled(false);
9598 }
9599 }
9600 } else {
9601 if (index < 0) {
9602 return;
9603 }
9604 desc = mSuspendedEffects.valueAt(index);
9605 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009606 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009607 desc->mRefCount = 1;
9608 }
9609 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009610 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009611 if (desc->mEffect != 0) {
9612 sp<EffectModule> effect = desc->mEffect.promote();
9613 if (effect != 0) {
9614 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009615 effect->lock();
9616 EffectHandle *handle = effect->controlHandle_l();
9617 if (handle != NULL && !handle->destroyed_l()) {
9618 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009619 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009620 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009621 }
9622 desc->mEffect.clear();
9623 }
9624 mSuspendedEffects.removeItemsAt(index);
9625 }
9626 }
9627}
9628
9629// must be called with ThreadBase::mLock held
9630void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9631{
9632 sp<SuspendedEffectDesc> desc;
9633
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009634 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009635 if (suspend) {
9636 if (index >= 0) {
9637 desc = mSuspendedEffects.valueAt(index);
9638 } else {
9639 desc = new SuspendedEffectDesc();
9640 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009641 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009642 }
9643 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009644 Vector< sp<EffectModule> > effects;
9645 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009646 for (size_t i = 0; i < effects.size(); i++) {
9647 setEffectSuspended_l(&effects[i]->desc().type, true);
9648 }
9649 }
9650 } else {
9651 if (index < 0) {
9652 return;
9653 }
9654 desc = mSuspendedEffects.valueAt(index);
9655 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009656 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009657 desc->mRefCount = 1;
9658 }
9659 if (--desc->mRefCount == 0) {
9660 Vector<const effect_uuid_t *> types;
9661 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9662 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9663 continue;
9664 }
9665 types.add(&mSuspendedEffects.valueAt(i)->mType);
9666 }
9667 for (size_t i = 0; i < types.size(); i++) {
9668 setEffectSuspended_l(types[i], false);
9669 }
Steve Block3856b092011-10-20 11:56:00 +01009670 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009671 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9672 }
9673 }
9674}
9675
Eric Laurent6bffdb82011-09-23 08:40:41 -07009676
9677// The volume effect is used for automated tests only
9678#ifndef OPENSL_ES_H_
9679static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9680 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9681const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9682#endif //OPENSL_ES_H_
9683
Eric Laurentdb7c0792011-08-10 10:37:50 -07009684bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9685{
9686 // auxiliary effects and visualizer are never suspended on output mix
9687 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9688 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009689 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9690 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009691 return false;
9692 }
9693 return true;
9694}
9695
Glenn Kastend0539712012-01-30 12:56:03 -08009696void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009697{
Glenn Kastend0539712012-01-30 12:56:03 -08009698 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009699 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009700 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9701 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009702 }
Eric Laurent59255e42011-07-27 19:49:51 -07009703 }
Eric Laurent59255e42011-07-27 19:49:51 -07009704}
9705
9706sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9707 const effect_uuid_t *type)
9708{
Glenn Kasten090f0192012-01-30 13:00:02 -08009709 sp<EffectModule> effect = getEffectFromType_l(type);
9710 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009711}
9712
9713void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9714 bool enabled)
9715{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009716 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009717 if (enabled) {
9718 if (index < 0) {
9719 // if the effect is not suspend check if all effects are suspended
9720 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9721 if (index < 0) {
9722 return;
9723 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009724 if (!isEffectEligibleForSuspend(effect->desc())) {
9725 return;
9726 }
Eric Laurent59255e42011-07-27 19:49:51 -07009727 setEffectSuspended_l(&effect->desc().type, enabled);
9728 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009729 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009730 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009731 return;
9732 }
Eric Laurent59255e42011-07-27 19:49:51 -07009733 }
Steve Block3856b092011-10-20 11:56:00 +01009734 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009735 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009736 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9737 // if effect is requested to suspended but was not yet enabled, supend it now.
9738 if (desc->mEffect == 0) {
9739 desc->mEffect = effect;
9740 effect->setEnabled(false);
9741 effect->setSuspended(true);
9742 }
9743 } else {
9744 if (index < 0) {
9745 return;
9746 }
Steve Block3856b092011-10-20 11:56:00 +01009747 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009748 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009749 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9750 desc->mEffect.clear();
9751 effect->setSuspended(false);
9752 }
9753}
9754
Mathias Agopian65ab4712010-07-14 17:59:35 -07009755#undef LOG_TAG
9756#define LOG_TAG "AudioFlinger"
9757
9758// ----------------------------------------------------------------------------
9759
9760status_t AudioFlinger::onTransact(
9761 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9762{
9763 return BnAudioFlinger::onTransact(code, data, reply, flags);
9764}
9765
Mathias Agopian65ab4712010-07-14 17:59:35 -07009766}; // namespace android