blob: 9689654d44f84b46e76e094a7557996afe1d769b [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");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001167 // This lock prevents the following race in thread (uniprocessor for illustration):
1168 // if (!exitPending()) {
1169 // // context switch from here to exit()
1170 // // exit() calls requestExit(), what exitPending() observes
1171 // // exit() calls signal(), which is dropped since no waiters
1172 // // context switch back from exit() to here
1173 // mWaitWorkCV.wait(...);
1174 // // now thread is hung
1175 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001176 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001177 requestExit();
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07001178 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001179 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001180 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1181 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001182 requestExitAndWait();
1183}
1184
Mathias Agopian65ab4712010-07-14 17:59:35 -07001185status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1186{
1187 status_t status;
1188
Steve Block3856b092011-10-20 11:56:00 +01001189 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001190 Mutex::Autolock _l(mLock);
1191
1192 mNewParameters.add(keyValuePairs);
1193 mWaitWorkCV.signal();
1194 // wait condition with timeout in case the thread loop has exited
1195 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001196 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001197 status = mParamStatus;
1198 mWaitWorkCV.signal();
1199 } else {
1200 status = TIMED_OUT;
1201 }
1202 return status;
1203}
1204
Eric Laurent896adcd2012-09-13 11:18:23 -07001205void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001206{
1207 Mutex::Autolock _l(mLock);
Eric Laurent896adcd2012-09-13 11:18:23 -07001208 sendIoConfigEvent_l(event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001209}
1210
Eric Laurent896adcd2012-09-13 11:18:23 -07001211// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
1212void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001213{
Eric Laurent896adcd2012-09-13 11:18:23 -07001214 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
1215 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
1216 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1217 mWaitWorkCV.signal();
1218}
1219
1220// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
1221void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
1222{
1223 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
1224 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
1225 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
1226 mConfigEvents.size(), pid, tid, prio);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001227 mWaitWorkCV.signal();
1228}
1229
1230void AudioFlinger::ThreadBase::processConfigEvents()
1231{
1232 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001233 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001234 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Eric Laurent896adcd2012-09-13 11:18:23 -07001235 ConfigEvent *event = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001236 mConfigEvents.removeAt(0);
1237 // release mLock before locking AudioFlinger mLock: lock order is always
1238 // AudioFlinger then ThreadBase to avoid cross deadlock
1239 mLock.unlock();
Eric Laurent896adcd2012-09-13 11:18:23 -07001240 switch(event->type()) {
1241 case CFG_EVENT_PRIO: {
1242 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
1243 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio());
1244 if (err != 0) {
1245 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1246 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
1247 }
1248 } break;
1249 case CFG_EVENT_IO: {
1250 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
1251 mAudioFlinger->mLock.lock();
1252 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
1253 mAudioFlinger->mLock.unlock();
1254 } break;
1255 default:
1256 ALOGE("processConfigEvents() unknown event type %d", event->type());
1257 break;
1258 }
1259 delete event;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001260 mLock.lock();
1261 }
1262 mLock.unlock();
1263}
1264
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001265void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001266{
1267 const size_t SIZE = 256;
1268 char buffer[SIZE];
1269 String8 result;
1270
1271 bool locked = tryLock(mLock);
1272 if (!locked) {
1273 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1274 write(fd, buffer, strlen(buffer));
1275 }
1276
Eric Laurent612bbb52012-03-14 15:03:26 -07001277 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1278 result.append(buffer);
1279 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1280 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001281 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1282 result.append(buffer);
1283 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1284 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001285 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1286 result.append(buffer);
1287 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001288 result.append(buffer);
1289 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1290 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001291 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1292 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001293 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1294 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001295 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001296 result.append(buffer);
1297
1298 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1299 result.append(buffer);
1300 result.append(" Index Command");
1301 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1302 snprintf(buffer, SIZE, "\n %02d ", i);
1303 result.append(buffer);
1304 result.append(mNewParameters[i]);
1305 }
1306
1307 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1308 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001309 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001310 mConfigEvents[i]->dump(buffer, SIZE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001311 result.append(buffer);
1312 }
1313 result.append("\n");
1314
1315 write(fd, result.string(), result.size());
1316
1317 if (locked) {
1318 mLock.unlock();
1319 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001320}
1321
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001322void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001323{
1324 const size_t SIZE = 256;
1325 char buffer[SIZE];
1326 String8 result;
1327
1328 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1329 write(fd, buffer, strlen(buffer));
1330
1331 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1332 sp<EffectChain> chain = mEffectChains[i];
1333 if (chain != 0) {
1334 chain->dump(fd, args);
1335 }
1336 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001337}
1338
Eric Laurentfeb0db62011-07-22 09:04:31 -07001339void AudioFlinger::ThreadBase::acquireWakeLock()
1340{
1341 Mutex::Autolock _l(mLock);
1342 acquireWakeLock_l();
1343}
1344
1345void AudioFlinger::ThreadBase::acquireWakeLock_l()
1346{
1347 if (mPowerManager == 0) {
1348 // use checkService() to avoid blocking if power service is not up yet
1349 sp<IBinder> binder =
1350 defaultServiceManager()->checkService(String16("power"));
1351 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001352 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001353 } else {
1354 mPowerManager = interface_cast<IPowerManager>(binder);
1355 binder->linkToDeath(mDeathRecipient);
1356 }
1357 }
1358 if (mPowerManager != 0) {
1359 sp<IBinder> binder = new BBinder();
1360 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1361 binder,
1362 String16(mName));
1363 if (status == NO_ERROR) {
1364 mWakeLockToken = binder;
1365 }
Steve Block3856b092011-10-20 11:56:00 +01001366 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001367 }
1368}
1369
1370void AudioFlinger::ThreadBase::releaseWakeLock()
1371{
1372 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001373 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001374}
1375
1376void AudioFlinger::ThreadBase::releaseWakeLock_l()
1377{
1378 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001379 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001380 if (mPowerManager != 0) {
1381 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1382 }
1383 mWakeLockToken.clear();
1384 }
1385}
1386
1387void AudioFlinger::ThreadBase::clearPowerManager()
1388{
1389 Mutex::Autolock _l(mLock);
1390 releaseWakeLock_l();
1391 mPowerManager.clear();
1392}
1393
1394void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1395{
1396 sp<ThreadBase> thread = mThread.promote();
1397 if (thread != 0) {
1398 thread->clearPowerManager();
1399 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001400 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001401}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001402
Eric Laurent59255e42011-07-27 19:49:51 -07001403void AudioFlinger::ThreadBase::setEffectSuspended(
1404 const effect_uuid_t *type, bool suspend, int sessionId)
1405{
1406 Mutex::Autolock _l(mLock);
1407 setEffectSuspended_l(type, suspend, sessionId);
1408}
1409
1410void AudioFlinger::ThreadBase::setEffectSuspended_l(
1411 const effect_uuid_t *type, bool suspend, int sessionId)
1412{
Glenn Kasten090f0192012-01-30 13:00:02 -08001413 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001414 if (chain != 0) {
1415 if (type != NULL) {
1416 chain->setEffectSuspended_l(type, suspend);
1417 } else {
1418 chain->setEffectSuspendedAll_l(suspend);
1419 }
1420 }
1421
1422 updateSuspendedSessions_l(type, suspend, sessionId);
1423}
1424
1425void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1426{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001427 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001428 if (index < 0) {
1429 return;
1430 }
1431
Glenn Kasten0a7af182012-07-09 16:09:19 -07001432 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1433 mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001434
1435 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001436 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001437 for (int j = 0; j < desc->mRefCount; j++) {
1438 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1439 chain->setEffectSuspendedAll_l(true);
1440 } else {
Steve Block3856b092011-10-20 11:56:00 +01001441 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001442 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001443 chain->setEffectSuspended_l(&desc->mType, true);
1444 }
1445 }
1446 }
1447}
1448
Eric Laurent59255e42011-07-27 19:49:51 -07001449void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1450 bool suspend,
1451 int sessionId)
1452{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001453 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001454
1455 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1456
1457 if (suspend) {
1458 if (index >= 0) {
Glenn Kasten0a7af182012-07-09 16:09:19 -07001459 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001460 } else {
1461 mSuspendedSessions.add(sessionId, sessionEffects);
1462 }
1463 } else {
1464 if (index < 0) {
1465 return;
1466 }
Glenn Kasten0a7af182012-07-09 16:09:19 -07001467 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001468 }
1469
1470
1471 int key = EffectChain::kKeyForSuspendAll;
1472 if (type != NULL) {
1473 key = type->timeLow;
1474 }
1475 index = sessionEffects.indexOfKey(key);
1476
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001477 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001478 if (suspend) {
1479 if (index >= 0) {
1480 desc = sessionEffects.valueAt(index);
1481 } else {
1482 desc = new SuspendedSessionDesc();
1483 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001484 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001485 }
1486 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001487 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001488 }
1489 desc->mRefCount++;
1490 } else {
1491 if (index < 0) {
1492 return;
1493 }
1494 desc = sessionEffects.valueAt(index);
1495 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001496 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001497 sessionEffects.removeItemsAt(index);
1498 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001499 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001500 sessionId);
1501 mSuspendedSessions.removeItem(sessionId);
1502 }
1503 }
1504 }
1505 if (!sessionEffects.isEmpty()) {
1506 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1507 }
1508}
1509
1510void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1511 bool enabled,
1512 int sessionId)
1513{
1514 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001515 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1516}
Eric Laurent59255e42011-07-27 19:49:51 -07001517
Eric Laurenta85a74a2011-10-19 11:44:54 -07001518void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1519 bool enabled,
1520 int sessionId)
1521{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001522 if (mType != RECORD) {
1523 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1524 // another session. This gives the priority to well behaved effect control panels
1525 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001526 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1527 // global effects
1528 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001529 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1530 }
1531 }
Eric Laurent59255e42011-07-27 19:49:51 -07001532
1533 sp<EffectChain> chain = getEffectChain_l(sessionId);
1534 if (chain != 0) {
1535 chain->checkSuspendOnEffectEnabled(effect, enabled);
1536 }
1537}
1538
Mathias Agopian65ab4712010-07-14 17:59:35 -07001539// ----------------------------------------------------------------------------
1540
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001541AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1542 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001543 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001544 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001545 type_t type)
Eric Laurentf1c04f92012-08-28 14:26:53 -07001546 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001547 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001548 // mStreamTypes[] initialized in constructor body
1549 mOutput(output),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001550 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001551 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001552 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001553 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001554 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001555 // index 0 is reserved for normal mixer's submix
1556 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001557{
Glenn Kasten480b4682012-02-28 12:30:08 -08001558 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001559
John Grossmanee578c02012-07-23 17:05:46 -07001560 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1561 // it would be safer to explicitly pass initial masterVolume/masterMute as
1562 // parameter.
1563 //
1564 // If the HAL we are using has support for master volume or master mute,
1565 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1566 // and the mute set to false).
1567 mMasterVolume = audioFlinger->masterVolume_l();
1568 mMasterMute = audioFlinger->masterMute_l();
1569 if (mOutput && mOutput->audioHwDev) {
1570 if (mOutput->audioHwDev->canSetMasterVolume()) {
1571 mMasterVolume = 1.0;
1572 }
1573
1574 if (mOutput->audioHwDev->canSetMasterMute()) {
1575 mMasterMute = false;
1576 }
1577 }
1578
Mathias Agopian65ab4712010-07-14 17:59:35 -07001579 readOutputParameters();
1580
Glenn Kasten263709e2012-01-06 08:40:01 -08001581 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001582 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1583 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1584 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001585 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1586 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001588 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1589 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001590}
1591
1592AudioFlinger::PlaybackThread::~PlaybackThread()
1593{
1594 delete [] mMixBuffer;
1595}
1596
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001597void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598{
1599 dumpInternals(fd, args);
1600 dumpTracks(fd, args);
1601 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001602}
1603
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001604void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001605{
1606 const size_t SIZE = 256;
1607 char buffer[SIZE];
1608 String8 result;
1609
Glenn Kasten58912562012-04-03 10:45:00 -07001610 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1611 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1612 const stream_type_t *st = &mStreamTypes[i];
1613 if (i > 0) {
1614 result.appendFormat(", ");
1615 }
1616 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1617 if (st->mute) {
1618 result.append("M");
1619 }
1620 }
1621 result.append("\n");
1622 write(fd, result.string(), result.length());
1623 result.clear();
1624
Mathias Agopian65ab4712010-07-14 17:59:35 -07001625 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1626 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001627 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001628 for (size_t i = 0; i < mTracks.size(); ++i) {
1629 sp<Track> track = mTracks[i];
1630 if (track != 0) {
1631 track->dump(buffer, SIZE);
1632 result.append(buffer);
1633 }
1634 }
1635
1636 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1637 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001638 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001639 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001640 sp<Track> track = mActiveTracks[i].promote();
1641 if (track != 0) {
1642 track->dump(buffer, SIZE);
1643 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001644 }
1645 }
1646 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001647
1648 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1649 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1650 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1651 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001652}
1653
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001654void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001655{
1656 const size_t SIZE = 256;
1657 char buffer[SIZE];
1658 String8 result;
1659
1660 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1661 result.append(buffer);
1662 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1663 result.append(buffer);
1664 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1665 result.append(buffer);
1666 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1667 result.append(buffer);
1668 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1669 result.append(buffer);
1670 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1671 result.append(buffer);
1672 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1673 result.append(buffer);
1674 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001675 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001676
1677 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001678}
1679
1680// Thread virtuals
1681status_t AudioFlinger::PlaybackThread::readyToRun()
1682{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001683 status_t status = initCheck();
1684 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001685 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001686 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001687 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001688 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001689 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001690}
1691
1692void AudioFlinger::PlaybackThread::onFirstRef()
1693{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001694 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695}
1696
1697// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001698sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001699 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001700 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001701 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001702 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001703 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001704 int frameCount,
1705 const sp<IMemory>& sharedBuffer,
1706 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001707 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001708 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001709 status_t *status)
1710{
1711 sp<Track> track;
1712 status_t lStatus;
1713
Glenn Kasten73d22752012-03-19 13:38:30 -07001714 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1715
1716 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001717 if (flags & IAudioFlinger::TRACK_FAST) {
1718 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001719 // not timed
1720 (!isTimed) &&
1721 // either of these use cases:
1722 (
1723 // use case 1: shared buffer with any frame count
1724 (
1725 (sharedBuffer != 0)
1726 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001727 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001728 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001729 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001730 ((frameCount == 0) ||
Glenn Kasten3ed29202012-08-07 15:24:44 -07001731 (frameCount >= (int) (mFrameCount * kFastTrackMultiplier)))
Glenn Kasten73d22752012-03-19 13:38:30 -07001732 )
1733 ) &&
1734 // PCM data
1735 audio_is_linear_pcm(format) &&
1736 // mono or stereo
1737 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1738 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001739#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001740 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001741 (sampleRate == mSampleRate) &&
1742#endif
1743 // normal mixer has an associated fast mixer
1744 hasFastMixer() &&
1745 // there are sufficient fast track slots available
1746 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001747 // FIXME test that MixerThread for this fast track has a capable output HAL
1748 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001749 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001750 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1751 if (frameCount == 0) {
Glenn Kasten3ed29202012-08-07 15:24:44 -07001752 frameCount = mFrameCount * kFastTrackMultiplier;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001753 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001754 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001755 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001756 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001757 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07001758 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001759 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1760 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1761 audio_is_linear_pcm(format),
1762 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001763 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001764 // For compatibility with AudioTrack calculation, buffer depth is forced
1765 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1766 // This is probably too conservative, but legacy application code may depend on it.
1767 // If you change this calculation, also review the start threshold which is related.
1768 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1769 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1770 if (minBufCount < 2) {
1771 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001772 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001773 int minFrameCount = mNormalFrameCount * minBufCount;
1774 if (frameCount < minFrameCount) {
1775 frameCount = minFrameCount;
1776 }
1777 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001778 }
1779
Mathias Agopian65ab4712010-07-14 17:59:35 -07001780 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001781 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1782 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001783 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001784 "for output %p with format %d",
1785 sampleRate, format, channelMask, mOutput, mFormat);
1786 lStatus = BAD_VALUE;
1787 goto Exit;
1788 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001789 }
1790 } else {
1791 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1792 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001793 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001794 lStatus = BAD_VALUE;
1795 goto Exit;
1796 }
1797 }
1798
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001799 lStatus = initCheck();
1800 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001801 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001802 goto Exit;
1803 }
1804
1805 { // scope for mLock
1806 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001807
1808 // all tracks in same audio session must share the same routing strategy otherwise
1809 // conflicts will happen when tracks are moved from one output to another by audio policy
1810 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001811 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001812 for (size_t i = 0; i < mTracks.size(); ++i) {
1813 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001814 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001815 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001816 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001817 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001818 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001819 lStatus = BAD_VALUE;
1820 goto Exit;
1821 }
1822 }
1823 }
1824
John Grossman4ff14ba2012-02-08 16:37:41 -08001825 if (!isTimed) {
1826 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001827 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001828 } else {
1829 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1830 channelMask, frameCount, sharedBuffer, sessionId);
1831 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001832 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833 lStatus = NO_MEMORY;
1834 goto Exit;
1835 }
1836 mTracks.add(track);
1837
1838 sp<EffectChain> chain = getEffectChain_l(sessionId);
1839 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001840 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001841 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001842 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001843 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001844 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001845
Eric Laurent896adcd2012-09-13 11:18:23 -07001846 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1847 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1848 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1849 // so ask activity manager to do this on our behalf
1850 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001851 }
1852 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001853
Mathias Agopian65ab4712010-07-14 17:59:35 -07001854 lStatus = NO_ERROR;
1855
1856Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001857 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001858 *status = lStatus;
1859 }
1860 return track;
1861}
1862
Eric Laurente737cda2012-05-22 18:55:44 -07001863uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1864{
1865 if (mFastMixer != NULL) {
1866 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1867 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1868 }
1869 return latency;
1870}
1871
1872uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1873{
1874 return latency;
1875}
1876
Mathias Agopian65ab4712010-07-14 17:59:35 -07001877uint32_t AudioFlinger::PlaybackThread::latency() const
1878{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001879 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001880 return latency_l();
1881}
1882uint32_t AudioFlinger::PlaybackThread::latency_l() const
1883{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001884 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001885 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001886 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001887 return 0;
1888 }
1889}
1890
Glenn Kasten6637baa2012-01-09 09:40:36 -08001891void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001892{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001893 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001894 // Don't apply master volume in SW if our HAL can do it for us.
1895 if (mOutput && mOutput->audioHwDev &&
1896 mOutput->audioHwDev->canSetMasterVolume()) {
1897 mMasterVolume = 1.0;
1898 } else {
1899 mMasterVolume = value;
1900 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001901}
1902
Glenn Kasten6637baa2012-01-09 09:40:36 -08001903void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001904{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001905 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001906 // Don't apply master mute in SW if our HAL can do it for us.
1907 if (mOutput && mOutput->audioHwDev &&
1908 mOutput->audioHwDev->canSetMasterMute()) {
1909 mMasterMute = false;
1910 } else {
1911 mMasterMute = muted;
1912 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001913}
1914
Glenn Kasten6637baa2012-01-09 09:40:36 -08001915void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001917 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001919}
1920
Glenn Kasten6637baa2012-01-09 09:40:36 -08001921void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001922{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001923 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001924 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001925}
1926
Glenn Kastenfff6d712012-01-12 16:38:12 -08001927float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001928{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001929 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001930 return mStreamTypes[stream].volume;
1931}
1932
Mathias Agopian65ab4712010-07-14 17:59:35 -07001933// addTrack_l() must be called with ThreadBase::mLock held
1934status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1935{
1936 status_t status = ALREADY_EXISTS;
1937
1938 // set retry count for buffer fill
1939 track->mRetryCount = kMaxTrackStartupRetries;
1940 if (mActiveTracks.indexOf(track) < 0) {
1941 // the track is newly added, make sure it fills up all its
1942 // buffers before playing. This is to ensure the client will
1943 // effectively get the latency it requested.
1944 track->mFillingUpStatus = Track::FS_FILLING;
1945 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001946 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001947 mActiveTracks.add(track);
1948 if (track->mainBuffer() != mMixBuffer) {
1949 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1950 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001951 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001952 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001953 }
1954 }
1955
1956 status = NO_ERROR;
1957 }
1958
Steve Block3856b092011-10-20 11:56:00 +01001959 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001960 mWaitWorkCV.broadcast();
1961
1962 return status;
1963}
1964
1965// destroyTrack_l() must be called with ThreadBase::mLock held
1966void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1967{
1968 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001969 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001971 removeTrack_l(track);
1972 }
1973}
1974
1975void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1976{
Eric Laurent29864602012-05-08 18:57:51 -07001977 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001978 mTracks.remove(track);
1979 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001980 // redundant as track is about to be destroyed, for dumpsys only
1981 track->mName = -1;
1982 if (track->isFastTrack()) {
1983 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001984 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001985 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1986 mFastTrackAvailMask |= 1 << index;
1987 // redundant as track is about to be destroyed, for dumpsys only
1988 track->mFastIndex = -1;
1989 }
Eric Laurentb469b942011-05-09 12:09:06 -07001990 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1991 if (chain != 0) {
1992 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001993 }
1994}
1995
1996String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1997{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001998 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001999 char *s;
2000
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002001 Mutex::Autolock _l(mLock);
2002 if (initCheck() != NO_ERROR) {
2003 return out_s8;
2004 }
2005
Dima Zavin799a70e2011-04-18 16:57:27 -07002006 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07002007 out_s8 = String8(s);
2008 free(s);
2009 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002010}
2011
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002012// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002013void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
2014 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08002015 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002016
Steve Block3856b092011-10-20 11:56:00 +01002017 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002018
2019 switch (event) {
2020 case AudioSystem::OUTPUT_OPENED:
2021 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002022 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002023 desc.samplingRate = mSampleRate;
2024 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07002025 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002026 desc.latency = latency();
2027 param2 = &desc;
2028 break;
2029
2030 case AudioSystem::STREAM_CONFIG_CHANGED:
2031 param2 = &param;
2032 case AudioSystem::OUTPUT_CLOSED:
2033 default:
2034 break;
2035 }
2036 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2037}
2038
2039void AudioFlinger::PlaybackThread::readOutputParameters()
2040{
Dima Zavin799a70e2011-04-18 16:57:27 -07002041 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002042 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2043 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07002044 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002045 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002046 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002047 if (mFrameCount & 15) {
2048 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2049 mFrameCount);
2050 }
2051
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002052 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002053 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002054 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002055 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002056 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2057 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2058 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2059 maxNormalFrameCount = maxNormalFrameCount & ~15;
2060 if (maxNormalFrameCount < minNormalFrameCount) {
2061 maxNormalFrameCount = minNormalFrameCount;
2062 }
2063 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2064 if (multiplier <= 1.0) {
2065 multiplier = 1.0;
2066 } else if (multiplier <= 2.0) {
2067 if (2 * mFrameCount <= maxNormalFrameCount) {
2068 multiplier = 2.0;
2069 } else {
2070 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2071 }
2072 } else {
2073 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2074 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2075 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2076 // FIXME this rounding up should not be done if no HAL SRC
2077 uint32_t truncMult = (uint32_t) multiplier;
2078 if ((truncMult & 1)) {
2079 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2080 ++truncMult;
2081 }
2082 }
2083 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002084 }
Glenn Kasten58912562012-04-03 10:45:00 -07002085 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002086 mNormalFrameCount = multiplier * mFrameCount;
2087 // round up to nearest 16 frames to satisfy AudioMixer
2088 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002089 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002090
Glenn Kastene9dd0172012-01-27 18:08:45 -08002091 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002092 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2093 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002094
Eric Laurentde070132010-07-13 04:45:46 -07002095 // force reconfiguration of effect chains and engines to take new buffer size and audio
2096 // parameters into account
2097 // Note that mLock is not held when readOutputParameters() is called from the constructor
2098 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2099 // matter.
2100 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2101 Vector< sp<EffectChain> > effectChains = mEffectChains;
2102 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002103 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002104 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105}
2106
Eric Laurente737cda2012-05-22 18:55:44 -07002107
Mathias Agopian65ab4712010-07-14 17:59:35 -07002108status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2109{
Glenn Kastena0d68332012-01-27 16:47:15 -08002110 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002111 return BAD_VALUE;
2112 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002113 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002114 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002115 return INVALID_OPERATION;
2116 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002117 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002118
Eric Laurent1afc26d2012-09-23 15:20:50 -07002119 if (isSuspended()) {
2120 // return an estimation of rendered frames when the output is suspended
2121 int32_t frames = mBytesWritten - latency_l();
2122 if (frames < 0) {
2123 frames = 0;
2124 }
2125 *dspFrames = (uint32_t)frames;
2126 return NO_ERROR;
2127 } else {
2128 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
2129 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002130}
2131
Glenn Kasten106e8a42012-08-02 13:37:12 -07002132uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002133{
2134 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002135 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002136 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002137 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002138 }
2139
2140 for (size_t i = 0; i < mTracks.size(); ++i) {
2141 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002142 if (sessionId == track->sessionId() &&
2143 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002144 result |= TRACK_SESSION;
2145 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002146 }
2147 }
2148
Eric Laurent39e94f82010-07-28 01:32:47 -07002149 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002150}
2151
Eric Laurentde070132010-07-13 04:45:46 -07002152uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2153{
Dima Zavinfce7a472011-04-19 22:30:36 -07002154 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002155 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002156 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2157 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002158 }
2159 for (size_t i = 0; i < mTracks.size(); i++) {
2160 sp<Track> track = mTracks[i];
2161 if (sessionId == track->sessionId() &&
2162 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002163 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002164 }
2165 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002166 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002167}
2168
Mathias Agopian65ab4712010-07-14 17:59:35 -07002169
Glenn Kastenaed850d2012-01-26 09:46:34 -08002170AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002171{
2172 Mutex::Autolock _l(mLock);
2173 return mOutput;
2174}
2175
2176AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2177{
2178 Mutex::Autolock _l(mLock);
2179 AudioStreamOut *output = mOutput;
2180 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002181 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2182 // must push a NULL and wait for ack
2183 mOutputSink.clear();
2184 mPipeSink.clear();
2185 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002186 return output;
2187}
2188
2189// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002190audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002191{
2192 if (mOutput == NULL) {
2193 return NULL;
2194 }
2195 return &mOutput->stream->common;
2196}
2197
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002198uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002199{
Eric Laurentab9071b2012-06-04 13:45:29 -07002200 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002201}
2202
Eric Laurenta011e352012-03-29 15:51:43 -07002203status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2204{
2205 if (!isValidSyncEvent(event)) {
2206 return BAD_VALUE;
2207 }
2208
2209 Mutex::Autolock _l(mLock);
2210
2211 for (size_t i = 0; i < mTracks.size(); ++i) {
2212 sp<Track> track = mTracks[i];
2213 if (event->triggerSession() == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07002214 (void) track->setSyncEvent(event);
Eric Laurenta011e352012-03-29 15:51:43 -07002215 return NO_ERROR;
2216 }
2217 }
2218
2219 return NAME_NOT_FOUND;
2220}
2221
Glenn Kasten106e8a42012-08-02 13:37:12 -07002222bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07002223{
Glenn Kasten0dbb3562012-08-02 16:36:50 -07002224 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
Eric Laurenta011e352012-03-29 15:51:43 -07002225}
2226
Eric Laurent44a957f2012-05-15 15:26:05 -07002227void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2228{
2229 size_t count = tracksToRemove.size();
2230 if (CC_UNLIKELY(count)) {
2231 for (size_t i = 0 ; i < count ; i++) {
2232 const sp<Track>& track = tracksToRemove.itemAt(i);
2233 if ((track->sharedBuffer() != 0) &&
2234 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2235 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2236 }
2237 }
2238 }
2239
2240}
2241
Mathias Agopian65ab4712010-07-14 17:59:35 -07002242// ----------------------------------------------------------------------------
2243
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002244AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002245 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002246 : PlaybackThread(audioFlinger, output, id, device, type),
2247 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002248 // mFastMixer below
2249 mFastMixerFutex(0)
2250 // mOutputSink below
2251 // mPipeSink below
2252 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002253{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002254 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002255 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002256 "mFrameCount=%d, mNormalFrameCount=%d",
2257 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2258 mNormalFrameCount);
2259 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2260
Mathias Agopian65ab4712010-07-14 17:59:35 -07002261 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002262 if (mChannelCount != FCC_2) {
2263 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002264 }
Glenn Kasten58912562012-04-03 10:45:00 -07002265
2266 // create an NBAIO sink for the HAL output stream, and negotiate
2267 mOutputSink = new AudioStreamOutSink(output->stream);
2268 size_t numCounterOffers = 0;
2269 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2270 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2271 ALOG_ASSERT(index == 0);
2272
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002273 // initialize fast mixer depending on configuration
2274 bool initFastMixer;
2275 switch (kUseFastMixer) {
2276 case FastMixer_Never:
2277 initFastMixer = false;
2278 break;
2279 case FastMixer_Always:
2280 initFastMixer = true;
2281 break;
2282 case FastMixer_Static:
2283 case FastMixer_Dynamic:
2284 initFastMixer = mFrameCount < mNormalFrameCount;
2285 break;
2286 }
2287 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002288
2289 // create a MonoPipe to connect our submix to FastMixer
2290 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002291 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2292 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2293 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2294 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002295 const NBAIO_Format offers[1] = {format};
2296 size_t numCounterOffers = 0;
2297 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2298 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002299 monoPipe->setAvgFrames((mScreenState & 1) ?
2300 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002301 mPipeSink = monoPipe;
2302
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002303#ifdef TEE_SINK_FRAMES
2304 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2305 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2306 numCounterOffers = 0;
2307 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2308 ALOG_ASSERT(index == 0);
2309 mTeeSink = teeSink;
2310 PipeReader *teeSource = new PipeReader(*teeSink);
2311 numCounterOffers = 0;
2312 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2313 ALOG_ASSERT(index == 0);
2314 mTeeSource = teeSource;
2315#endif
2316
Glenn Kasten58912562012-04-03 10:45:00 -07002317 // create fast mixer and configure it initially with just one fast track for our submix
2318 mFastMixer = new FastMixer();
2319 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002320#ifdef STATE_QUEUE_DUMP
2321 sq->setObserverDump(&mStateQueueObserverDump);
2322 sq->setMutatorDump(&mStateQueueMutatorDump);
2323#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002324 FastMixerState *state = sq->begin();
2325 FastTrack *fastTrack = &state->mFastTracks[0];
2326 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2327 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2328 fastTrack->mVolumeProvider = NULL;
2329 fastTrack->mGeneration++;
2330 state->mFastTracksGen++;
2331 state->mTrackMask = 1;
2332 // fast mixer will use the HAL output sink
2333 state->mOutputSink = mOutputSink.get();
2334 state->mOutputSinkGen++;
2335 state->mFrameCount = mFrameCount;
2336 state->mCommand = FastMixerState::COLD_IDLE;
2337 // already done in constructor initialization list
2338 //mFastMixerFutex = 0;
2339 state->mColdFutexAddr = &mFastMixerFutex;
2340 state->mColdGen++;
2341 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002342 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002343 sq->end();
2344 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2345
2346 // start the fast mixer
2347 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002348 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002349 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002350 if (err != 0) {
2351 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002352 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002353 }
Glenn Kasten58912562012-04-03 10:45:00 -07002354
Glenn Kastenc15d6652012-05-30 14:52:57 -07002355#ifdef AUDIO_WATCHDOG
2356 // create and start the watchdog
2357 mAudioWatchdog = new AudioWatchdog();
2358 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2359 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2360 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002361 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002362 if (err != 0) {
2363 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002364 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002365 }
2366#endif
2367
Glenn Kasten58912562012-04-03 10:45:00 -07002368 } else {
2369 mFastMixer = NULL;
2370 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002371
2372 switch (kUseFastMixer) {
2373 case FastMixer_Never:
2374 case FastMixer_Dynamic:
2375 mNormalSink = mOutputSink;
2376 break;
2377 case FastMixer_Always:
2378 mNormalSink = mPipeSink;
2379 break;
2380 case FastMixer_Static:
2381 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2382 break;
2383 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002384}
2385
2386AudioFlinger::MixerThread::~MixerThread()
2387{
Glenn Kasten58912562012-04-03 10:45:00 -07002388 if (mFastMixer != NULL) {
2389 FastMixerStateQueue *sq = mFastMixer->sq();
2390 FastMixerState *state = sq->begin();
2391 if (state->mCommand == FastMixerState::COLD_IDLE) {
2392 int32_t old = android_atomic_inc(&mFastMixerFutex);
2393 if (old == -1) {
2394 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2395 }
2396 }
2397 state->mCommand = FastMixerState::EXIT;
2398 sq->end();
2399 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2400 mFastMixer->join();
2401 // Though the fast mixer thread has exited, it's state queue is still valid.
2402 // We'll use that extract the final state which contains one remaining fast track
2403 // corresponding to our sub-mix.
2404 state = sq->begin();
2405 ALOG_ASSERT(state->mTrackMask == 1);
2406 FastTrack *fastTrack = &state->mFastTracks[0];
2407 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2408 delete fastTrack->mBufferProvider;
2409 sq->end(false /*didModify*/);
2410 delete mFastMixer;
Glenn Kastenc15d6652012-05-30 14:52:57 -07002411 if (mAudioWatchdog != 0) {
2412 mAudioWatchdog->requestExit();
2413 mAudioWatchdog->requestExitAndWait();
2414 mAudioWatchdog.clear();
2415 }
Glenn Kasten58912562012-04-03 10:45:00 -07002416 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002417 delete mAudioMixer;
2418}
2419
Glenn Kasten83efdd02012-02-24 07:21:32 -08002420class CpuStats {
2421public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002422 CpuStats();
2423 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002424#ifdef DEBUG_CPU_USAGE
2425private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002426 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2427 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2428
2429 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2430
2431 int mCpuNum; // thread's current CPU number
2432 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002433#endif
2434};
2435
Glenn Kasten190a46f2012-03-06 11:27:10 -08002436CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002437#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002438 : mCpuNum(-1), mCpukHz(-1)
2439#endif
2440{
2441}
2442
2443void CpuStats::sample(const String8 &title) {
2444#ifdef DEBUG_CPU_USAGE
2445 // get current thread's delta CPU time in wall clock ns
2446 double wcNs;
2447 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2448
2449 // record sample for wall clock statistics
2450 if (valid) {
2451 mWcStats.sample(wcNs);
2452 }
2453
2454 // get the current CPU number
2455 int cpuNum = sched_getcpu();
2456
2457 // get the current CPU frequency in kHz
2458 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2459
2460 // check if either CPU number or frequency changed
2461 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2462 mCpuNum = cpuNum;
2463 mCpukHz = cpukHz;
2464 // ignore sample for purposes of cycles
2465 valid = false;
2466 }
2467
2468 // if no change in CPU number or frequency, then record sample for cycle statistics
2469 if (valid && mCpukHz > 0) {
2470 double cycles = wcNs * cpukHz * 0.000001;
2471 mHzStats.sample(cycles);
2472 }
2473
2474 unsigned n = mWcStats.n();
2475 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002476 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002477 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002478 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2479 double perLoop = elapsed / (double) n;
2480 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002481 double perLoop1k = perLoop * 0.001;
2482 double mean = mWcStats.mean();
2483 double stddev = mWcStats.stddev();
2484 double minimum = mWcStats.minimum();
2485 double maximum = mWcStats.maximum();
2486 double meanCycles = mHzStats.mean();
2487 double stddevCycles = mHzStats.stddev();
2488 double minCycles = mHzStats.minimum();
2489 double maxCycles = mHzStats.maximum();
2490 mCpuUsage.resetElapsed();
2491 mWcStats.reset();
2492 mHzStats.reset();
2493 ALOGD("CPU usage for %s over past %.1f secs\n"
2494 " (%u mixer loops at %.1f mean ms per loop):\n"
2495 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2496 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2497 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2498 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002499 elapsed * .000000001, n, perLoop * .000001,
2500 mean * .001,
2501 stddev * .001,
2502 minimum * .001,
2503 maximum * .001,
2504 mean / perLoop100,
2505 stddev / perLoop100,
2506 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002507 maximum / perLoop100,
2508 meanCycles / perLoop1k,
2509 stddevCycles / perLoop1k,
2510 minCycles / perLoop1k,
2511 maxCycles / perLoop1k);
2512
Glenn Kasten83efdd02012-02-24 07:21:32 -08002513 }
2514 }
2515#endif
2516};
2517
Glenn Kasten37d825e2012-02-24 07:21:48 -08002518void AudioFlinger::PlaybackThread::checkSilentMode_l()
2519{
2520 if (!mMasterMute) {
2521 char value[PROPERTY_VALUE_MAX];
2522 if (property_get("ro.audio.silent", value, "0") > 0) {
2523 char *endptr;
2524 unsigned long ul = strtoul(value, &endptr, 0);
2525 if (*endptr == '\0' && ul != 0) {
2526 ALOGD("Silence is golden");
2527 // The setprop command will not allow a property to be changed after
2528 // the first time it is set, so we don't have to worry about un-muting.
2529 setMasterMute_l(true);
2530 }
2531 }
2532 }
2533}
2534
Glenn Kasten000f0e32012-03-01 17:10:56 -08002535bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002536{
2537 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002538
Glenn Kasten000f0e32012-03-01 17:10:56 -08002539 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002540
2541 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002542 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002543
Glenn Kasten000f0e32012-03-01 17:10:56 -08002544 // DUPLICATING
2545 // FIXME could this be made local to while loop?
2546 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002547
Glenn Kasten66fcab92012-02-24 14:59:21 -08002548 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002549 sleepTime = idleSleepTime;
2550
Glenn Kasten9f34a362012-03-20 16:46:41 -07002551 if (mType == MIXER) {
2552 sleepTimeShift = 0;
2553 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002554
Glenn Kasten83efdd02012-02-24 07:21:32 -08002555 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002556 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002557
Eric Laurentfeb0db62011-07-22 09:04:31 -07002558 acquireWakeLock();
2559
Mathias Agopian65ab4712010-07-14 17:59:35 -07002560 while (!exitPending())
2561 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002562 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002563
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002564 Vector< sp<EffectChain> > effectChains;
2565
Mathias Agopian65ab4712010-07-14 17:59:35 -07002566 processConfigEvents();
2567
Mathias Agopian65ab4712010-07-14 17:59:35 -07002568 { // scope for mLock
2569
2570 Mutex::Autolock _l(mLock);
2571
2572 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002573 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002574 }
2575
Glenn Kastenfa26a852012-03-06 11:28:04 -08002576 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002577
Mathias Agopian65ab4712010-07-14 17:59:35 -07002578 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002579 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002580 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002582
2583 threadLoop_standby();
2584
Mathias Agopian65ab4712010-07-14 17:59:35 -07002585 mStandby = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002586 }
2587
Glenn Kasten3e074702012-02-28 18:40:35 -08002588 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002589 // we're about to wait, flush the binder command buffer
2590 IPCThreadState::self()->flushCommands();
2591
Glenn Kastenfa26a852012-03-06 11:28:04 -08002592 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002593
Mathias Agopian65ab4712010-07-14 17:59:35 -07002594 if (exitPending()) break;
2595
Eric Laurentfeb0db62011-07-22 09:04:31 -07002596 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002597 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002598 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002599 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002600 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002601 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002602
Eric Laurentda747442012-04-25 18:53:13 -07002603 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002604 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Eric Laurent1afc26d2012-09-23 15:20:50 -07002605 mBytesWritten = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002606
Glenn Kasten37d825e2012-02-24 07:21:48 -08002607 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002608
Glenn Kasten000f0e32012-03-01 17:10:56 -08002609 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002610 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002611 if (mType == MIXER) {
2612 sleepTimeShift = 0;
2613 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002614
Mathias Agopian65ab4712010-07-14 17:59:35 -07002615 continue;
2616 }
2617 }
2618
Glenn Kasten81028042012-04-30 18:15:12 -07002619 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002620 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621
2622 // prevent any changes in effect chain list and in each effect chain
2623 // during mixing and effect process as the audio buffers could be deleted
2624 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002625 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002626 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002627
Glenn Kastenfec279f2012-03-08 07:47:15 -08002628 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002629 threadLoop_mix();
2630 } else {
2631 threadLoop_sleepTime();
2632 }
2633
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002634 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002635 sleepTime = suspendSleepTimeUs();
Eric Laurent1afc26d2012-09-23 15:20:50 -07002636 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002637 }
2638
2639 // only process effects if we're going to write
2640 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002641 for (size_t i = 0; i < effectChains.size(); i ++) {
2642 effectChains[i]->process_l();
2643 }
2644 }
2645
2646 // enable changes in effect chain
2647 unlockEffectChains(effectChains);
2648
2649 // sleepTime == 0 means we must write to audio hardware
2650 if (sleepTime == 0) {
2651
2652 threadLoop_write();
2653
2654if (mType == MIXER) {
2655 // write blocked detection
2656 nsecs_t now = systemTime();
2657 nsecs_t delta = now - mLastWriteTime;
2658 if (!mStandby && delta > maxPeriod) {
2659 mNumDelayedWrites++;
2660 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002661#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002662 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002663#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002664 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2665 ns2ms(delta), mNumDelayedWrites, this);
2666 lastWarning = now;
2667 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002668 }
2669}
2670
2671 mStandby = false;
2672 } else {
2673 usleep(sleepTime);
2674 }
2675
Glenn Kasten58912562012-04-03 10:45:00 -07002676 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002677 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002678 // same lock. This will also mutate and push a new fast mixer state.
2679 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002680 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002681
Glenn Kastenfa26a852012-03-06 11:28:04 -08002682 // FIXME I don't understand the need for this here;
2683 // it was in the original code but maybe the
2684 // assignment in saveOutputTracks() makes this unnecessary?
2685 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002686
2687 // Effect chains will be actually deleted here if they were removed from
2688 // mEffectChains list during mixing or effects processing
2689 effectChains.clear();
2690
2691 // FIXME Note that the above .clear() is no longer necessary since effectChains
2692 // is now local to this block, but will keep it for now (at least until merge done).
2693 }
2694
Glenn Kasten9f34a362012-03-20 16:46:41 -07002695 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2696 if (mType == MIXER || mType == DIRECT) {
2697 // put output stream into standby mode
2698 if (!mStandby) {
2699 mOutput->stream->common.standby(&mOutput->stream->common);
2700 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002701 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002702
2703 releaseWakeLock();
2704
2705 ALOGV("Thread %p type %d exiting", this, mType);
2706 return false;
2707}
2708
Glenn Kasten58912562012-04-03 10:45:00 -07002709void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2710{
Glenn Kasten58912562012-04-03 10:45:00 -07002711 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2712}
2713
2714void AudioFlinger::MixerThread::threadLoop_write()
2715{
2716 // FIXME we should only do one push per cycle; confirm this is true
2717 // Start the fast mixer if it's not already running
2718 if (mFastMixer != NULL) {
2719 FastMixerStateQueue *sq = mFastMixer->sq();
2720 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002721 if (state->mCommand != FastMixerState::MIX_WRITE &&
2722 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002723 if (state->mCommand == FastMixerState::COLD_IDLE) {
2724 int32_t old = android_atomic_inc(&mFastMixerFutex);
2725 if (old == -1) {
2726 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2727 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002728 if (mAudioWatchdog != 0) {
2729 mAudioWatchdog->resume();
2730 }
Glenn Kasten58912562012-04-03 10:45:00 -07002731 }
2732 state->mCommand = FastMixerState::MIX_WRITE;
2733 sq->end();
2734 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002735 if (kUseFastMixer == FastMixer_Dynamic) {
2736 mNormalSink = mPipeSink;
2737 }
Glenn Kasten58912562012-04-03 10:45:00 -07002738 } else {
2739 sq->end(false /*didModify*/);
2740 }
2741 }
2742 PlaybackThread::threadLoop_write();
2743}
2744
Glenn Kasten000f0e32012-03-01 17:10:56 -08002745// shared by MIXER and DIRECT, overridden by DUPLICATING
2746void AudioFlinger::PlaybackThread::threadLoop_write()
2747{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002748 // FIXME rewrite to reduce number of system calls
2749 mLastWriteTime = systemTime();
2750 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002751 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002752
Eric Laurent67c0a582012-05-01 19:31:12 -07002753 // If an NBAIO sink is present, use it to write the normal mixer's submix
2754 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002755#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002756 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002757#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002758 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002759#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002760 // update the setpoint when gScreenState changes
2761 uint32_t screenState = gScreenState;
2762 if (screenState != mScreenState) {
2763 mScreenState = screenState;
2764 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2765 if (pipe != NULL) {
2766 pipe->setAvgFrames((mScreenState & 1) ?
2767 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2768 }
2769 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002770 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002771#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002772 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002773#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002774 if (framesWritten > 0) {
2775 bytesWritten = framesWritten << mBitShift;
2776 } else {
2777 bytesWritten = framesWritten;
2778 }
2779 // otherwise use the HAL / AudioStreamOut directly
2780 } else {
2781 // Direct output thread.
2782 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002783 }
2784
Eric Laurent67c0a582012-05-01 19:31:12 -07002785 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002786 mNumWrites++;
2787 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002788}
2789
Glenn Kasten58912562012-04-03 10:45:00 -07002790void AudioFlinger::MixerThread::threadLoop_standby()
2791{
2792 // Idle the fast mixer if it's currently running
2793 if (mFastMixer != NULL) {
2794 FastMixerStateQueue *sq = mFastMixer->sq();
2795 FastMixerState *state = sq->begin();
2796 if (!(state->mCommand & FastMixerState::IDLE)) {
2797 state->mCommand = FastMixerState::COLD_IDLE;
2798 state->mColdFutexAddr = &mFastMixerFutex;
2799 state->mColdGen++;
2800 mFastMixerFutex = 0;
2801 sq->end();
2802 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2803 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002804 if (kUseFastMixer == FastMixer_Dynamic) {
2805 mNormalSink = mOutputSink;
2806 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002807 if (mAudioWatchdog != 0) {
2808 mAudioWatchdog->pause();
2809 }
Glenn Kasten58912562012-04-03 10:45:00 -07002810 } else {
2811 sq->end(false /*didModify*/);
2812 }
2813 }
2814 PlaybackThread::threadLoop_standby();
2815}
2816
Glenn Kasten000f0e32012-03-01 17:10:56 -08002817// shared by MIXER and DIRECT, overridden by DUPLICATING
2818void AudioFlinger::PlaybackThread::threadLoop_standby()
2819{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002820 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002821 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002822}
2823
2824void AudioFlinger::MixerThread::threadLoop_mix()
2825{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002826 // obtain the presentation timestamp of the next output buffer
2827 int64_t pts;
2828 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002829
John Grossman2c3b2da2012-08-02 17:08:54 -07002830 if (mNormalSink != 0) {
2831 status = mNormalSink->getNextWriteTimestamp(&pts);
2832 } else {
2833 status = mOutputSink->getNextWriteTimestamp(&pts);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002834 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002835
Glenn Kasten952eeb22012-03-06 11:30:57 -08002836 if (status != NO_ERROR) {
2837 pts = AudioBufferProvider::kInvalidPTS;
2838 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002839
Glenn Kasten952eeb22012-03-06 11:30:57 -08002840 // mix buffers...
2841 mAudioMixer->process(pts);
2842 // increase sleep time progressively when application underrun condition clears.
2843 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2844 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2845 // such that we would underrun the audio HAL.
2846 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2847 sleepTimeShift--;
2848 }
2849 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002850 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002851 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002852}
2853
2854void AudioFlinger::MixerThread::threadLoop_sleepTime()
2855{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002856 // If no tracks are ready, sleep once for the duration of an output
2857 // buffer size, then write 0s to the output
2858 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002859 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002860 sleepTime = activeSleepTime >> sleepTimeShift;
2861 if (sleepTime < kMinThreadSleepTimeUs) {
2862 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002863 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002864 // reduce sleep time in case of consecutive application underruns to avoid
2865 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2866 // duration we would end up writing less data than needed by the audio HAL if
2867 // the condition persists.
2868 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2869 sleepTimeShift++;
2870 }
2871 } else {
2872 sleepTime = idleSleepTime;
2873 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002874 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002875 memset (mMixBuffer, 0, mixBufferSize);
2876 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002877 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002878 }
2879 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002880}
2881
2882// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002883AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002884 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002885{
2886
Glenn Kasten29c23c32012-01-26 13:37:52 -08002887 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002888 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002889 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002890 size_t mixedTracks = 0;
2891 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002892 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002893 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002894 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002895
2896 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002897 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002898
Eric Laurent571d49c2010-08-11 05:20:11 -07002899 if (masterMute) {
2900 masterVolume = 0;
2901 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002902 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002903 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002904 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002905 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002906 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002907 masterVolume = (float)((v + (1 << 23)) >> 24);
2908 chain.clear();
2909 }
2910
Glenn Kasten288ed212012-04-25 17:52:27 -07002911 // prepare a new state to push
2912 FastMixerStateQueue *sq = NULL;
2913 FastMixerState *state = NULL;
2914 bool didModify = false;
2915 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2916 if (mFastMixer != NULL) {
2917 sq = mFastMixer->sq();
2918 state = sq->begin();
2919 }
2920
Mathias Agopian65ab4712010-07-14 17:59:35 -07002921 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002922 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923 if (t == 0) continue;
2924
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002925 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002926 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002927
Glenn Kasten288ed212012-04-25 17:52:27 -07002928 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002929 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002930
2931 // It's theoretically possible (though unlikely) for a fast track to be created
2932 // and then removed within the same normal mix cycle. This is not a problem, as
2933 // the track never becomes active so it's fast mixer slot is never touched.
2934 // The converse, of removing an (active) track and then creating a new track
2935 // at the identical fast mixer slot within the same normal mix cycle,
2936 // is impossible because the slot isn't marked available until the end of each cycle.
2937 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002938 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2939 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002940 FastTrack *fastTrack = &state->mFastTracks[j];
2941
2942 // Determine whether the track is currently in underrun condition,
2943 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002944 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2945 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002946 uint32_t recentFull = (underruns.mBitFields.mFull -
2947 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2948 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2949 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2950 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2951 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2952 uint32_t recentUnderruns = recentPartial + recentEmpty;
2953 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002954 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002955 // or stopped which can occur when flush() is called while active
2956 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002957 track->mUnderrunCount += recentUnderruns;
2958 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002959
Glenn Kastend08f48c2012-05-01 18:14:02 -07002960 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002961 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002962 bool isActive = true;
2963 switch (track->mState) {
2964 case TrackBase::STOPPING_1:
2965 // track stays active in STOPPING_1 state until first underrun
2966 if (recentUnderruns > 0) {
2967 track->mState = TrackBase::STOPPING_2;
2968 }
2969 break;
2970 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002971 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002972 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002973 break;
2974 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002975 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002976 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002977 break;
2978 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002979 if (recentFull > 0 || recentPartial > 0) {
2980 // track has provided at least some frames recently: reset retry count
2981 track->mRetryCount = kMaxTrackRetries;
2982 }
2983 if (recentUnderruns == 0) {
2984 // no recent underruns: stay active
2985 break;
2986 }
2987 // there has recently been an underrun of some kind
2988 if (track->sharedBuffer() == 0) {
2989 // were any of the recent underruns "empty" (no frames available)?
2990 if (recentEmpty == 0) {
2991 // no, then ignore the partial underruns as they are allowed indefinitely
2992 break;
2993 }
2994 // there has recently been an "empty" underrun: decrement the retry counter
2995 if (--(track->mRetryCount) > 0) {
2996 break;
2997 }
2998 // indicate to client process that the track was disabled because of underrun;
2999 // it will then automatically call start() when data is available
3000 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
3001 // remove from active list, but state remains ACTIVE [confusing but true]
3002 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003003 break;
3004 }
3005 // fall through
3006 case TrackBase::STOPPING_2:
3007 case TrackBase::PAUSED:
3008 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07003009 case TrackBase::STOPPED:
3010 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07003011 // Check for presentation complete if track is inactive
3012 // We have consumed all the buffers of this track.
3013 // This would be incomplete if we auto-paused on underrun
3014 {
3015 size_t audioHALFrames =
3016 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3017 size_t framesWritten =
3018 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3019 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
3020 // track stays in active list until presentation is complete
3021 break;
3022 }
3023 }
3024 if (track->isStopping_2()) {
3025 track->mState = TrackBase::STOPPED;
3026 }
3027 if (track->isStopped()) {
3028 // Can't reset directly, as fast mixer is still polling this track
3029 // track->reset();
3030 // So instead mark this track as needing to be reset after push with ack
3031 resetMask |= 1 << i;
3032 }
3033 isActive = false;
3034 break;
3035 case TrackBase::IDLE:
3036 default:
3037 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003038 }
3039
3040 if (isActive) {
3041 // was it previously inactive?
3042 if (!(state->mTrackMask & (1 << j))) {
3043 ExtendedAudioBufferProvider *eabp = track;
3044 VolumeProvider *vp = track;
3045 fastTrack->mBufferProvider = eabp;
3046 fastTrack->mVolumeProvider = vp;
3047 fastTrack->mSampleRate = track->mSampleRate;
3048 fastTrack->mChannelMask = track->mChannelMask;
3049 fastTrack->mGeneration++;
3050 state->mTrackMask |= 1 << j;
3051 didModify = true;
3052 // no acknowledgement required for newly active tracks
3053 }
3054 // cache the combined master volume and stream type volume for fast mixer; this
3055 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3056 track->mCachedVolume = track->isMuted() ?
3057 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3058 ++fastTracks;
3059 } else {
3060 // was it previously active?
3061 if (state->mTrackMask & (1 << j)) {
3062 fastTrack->mBufferProvider = NULL;
3063 fastTrack->mGeneration++;
3064 state->mTrackMask &= ~(1 << j);
3065 didModify = true;
3066 // If any fast tracks were removed, we must wait for acknowledgement
3067 // because we're about to decrement the last sp<> on those tracks.
3068 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003069 } else {
3070 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003071 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003072 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003073 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003074 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003075 }
3076 continue;
3077 }
3078
3079 { // local variable scope to avoid goto warning
3080
Mathias Agopian65ab4712010-07-14 17:59:35 -07003081 audio_track_cblk_t* cblk = track->cblk();
3082
3083 // The first time a track is added we wait
3084 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003085 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003086 // make sure that we have enough frames to mix one full buffer.
3087 // enforce this condition only once to enable draining the buffer in case the client
3088 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003089 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003090 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003091 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003092 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003093 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003094 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003095 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003096 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003097 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003098 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003099 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003100 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003101 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3102 // the minimum track buffer size is normally twice the number of frames necessary
3103 // to fill one buffer and the resampler should not leave more than one buffer worth
3104 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003105 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003106 }
3107 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003108 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003109 !track->isPaused() && !track->isTerminated())
3110 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003111 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003112
3113 mixedTracks++;
3114
3115 // track->mainBuffer() != mMixBuffer means there is an effect chain
3116 // connected to the track
3117 chain.clear();
3118 if (track->mainBuffer() != mMixBuffer) {
3119 chain = getEffectChain_l(track->sessionId());
3120 // Delegate volume control to effect in track effect chain if needed
3121 if (chain != 0) {
3122 tracksWithEffect++;
3123 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003124 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003125 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003126 }
3127 }
3128
3129
3130 int param = AudioMixer::VOLUME;
3131 if (track->mFillingUpStatus == Track::FS_FILLED) {
3132 // no ramp for the first volume setting
3133 track->mFillingUpStatus = Track::FS_ACTIVE;
3134 if (track->mState == TrackBase::RESUMING) {
3135 track->mState = TrackBase::ACTIVE;
3136 param = AudioMixer::RAMP_VOLUME;
3137 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003138 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003139 } else if (cblk->server != 0) {
3140 // If the track is stopped before the first frame was mixed,
3141 // do not apply ramp
3142 param = AudioMixer::RAMP_VOLUME;
3143 }
3144
3145 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003146 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003147 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003148 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003149 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003150 if (track->isPausing()) {
3151 track->setPaused();
3152 }
3153 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003154
Mathias Agopian65ab4712010-07-14 17:59:35 -07003155 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003156 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003157 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003158 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003159 vl = vlr & 0xFFFF;
3160 vr = vlr >> 16;
3161 // track volumes come from shared memory, so can't be trusted and must be clamped
3162 if (vl > MAX_GAIN_INT) {
3163 ALOGV("Track left volume out of range: %04X", vl);
3164 vl = MAX_GAIN_INT;
3165 }
3166 if (vr > MAX_GAIN_INT) {
3167 ALOGV("Track right volume out of range: %04X", vr);
3168 vr = MAX_GAIN_INT;
3169 }
3170 // now apply the master volume and stream type volume
3171 vl = (uint32_t)(v * vl) << 12;
3172 vr = (uint32_t)(v * vr) << 12;
3173 // assuming master volume and stream type volume each go up to 1.0,
3174 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003175
Glenn Kasten05632a52012-01-03 14:22:33 -08003176 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3177 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003178 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003179 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003180 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003181 }
3182 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003183 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003184 // Delegate volume control to effect in track effect chain if needed
3185 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3186 // Do not ramp volume if volume is controlled by effect
3187 param = AudioMixer::VOLUME;
3188 track->mHasVolumeController = true;
3189 } else {
3190 // force no volume ramp when volume controller was just disabled or removed
3191 // from effect chain to avoid volume spike
3192 if (track->mHasVolumeController) {
3193 param = AudioMixer::VOLUME;
3194 }
3195 track->mHasVolumeController = false;
3196 }
3197
3198 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003199 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003200 vl = (vl + (1 << 11)) >> 12;
3201 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3202 vr = (vr + (1 << 11)) >> 12;
3203 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003204
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003205 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 -07003206
Mathias Agopian65ab4712010-07-14 17:59:35 -07003207 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003208 mAudioMixer->setBufferProvider(name, track);
3209 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003210
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003211 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3212 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3213 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003214 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003215 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003216 AudioMixer::TRACK,
3217 AudioMixer::FORMAT, (void *)track->format());
3218 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003219 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003221 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003222 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003223 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003224 AudioMixer::RESAMPLE,
3225 AudioMixer::SAMPLE_RATE,
3226 (void *)(cblk->sampleRate));
3227 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003228 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003229 AudioMixer::TRACK,
3230 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3231 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003232 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003233 AudioMixer::TRACK,
3234 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3235
3236 // reset retry count
3237 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003238
Eric Laurent27741442012-01-17 19:20:12 -08003239 // If one track is ready, set the mixer ready if:
3240 // - the mixer was not ready during previous round OR
3241 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003242 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003243 mixerStatus != MIXER_TRACKS_ENABLED) {
3244 mixerStatus = MIXER_TRACKS_READY;
3245 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003246 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003247 // clear effect chain input buffer if an active track underruns to avoid sending
3248 // previous audio buffer again to effects
3249 chain = getEffectChain_l(track->sessionId());
3250 if (chain != 0) {
3251 chain->clearInputBuffer();
3252 }
3253
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003254 //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 -07003255 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent83faee02012-04-27 18:24:29 -07003256 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003257 // We have consumed all the buffers of this track.
3258 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003259 // TODO: use actual buffer filling status instead of latency when available from
3260 // audio HAL
3261 size_t audioHALFrames =
3262 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3263 size_t framesWritten =
3264 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3265 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003266 if (track->isStopped()) {
3267 track->reset();
3268 }
Eric Laurenta011e352012-03-29 15:51:43 -07003269 tracksToRemove->add(track);
3270 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003271 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003272 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003273 // No buffers for this track. Give it a few chances to
3274 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07003275 if (--(track->mRetryCount) <= 0) {
3276 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003277 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003278 // indicate to client process that the track was disabled because of underrun;
3279 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003280 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003281 // If one track is not ready, mark the mixer also not ready if:
3282 // - the mixer was ready during previous round OR
3283 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003284 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003285 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003286 mixerStatus = MIXER_TRACKS_ENABLED;
3287 }
3288 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003289 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003290 }
Glenn Kasten58912562012-04-03 10:45:00 -07003291
3292 } // local variable scope to avoid goto warning
3293track_is_ready: ;
3294
Mathias Agopian65ab4712010-07-14 17:59:35 -07003295 }
3296
Glenn Kasten288ed212012-04-25 17:52:27 -07003297 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003298 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003299 if (didModify) {
3300 state->mFastTracksGen++;
3301 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3302 if (kUseFastMixer == FastMixer_Dynamic &&
3303 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3304 state->mCommand = FastMixerState::COLD_IDLE;
3305 state->mColdFutexAddr = &mFastMixerFutex;
3306 state->mColdGen++;
3307 mFastMixerFutex = 0;
3308 if (kUseFastMixer == FastMixer_Dynamic) {
3309 mNormalSink = mOutputSink;
3310 }
3311 // If we go into cold idle, need to wait for acknowledgement
3312 // so that fast mixer stops doing I/O.
3313 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003314 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003315 }
3316 sq->end();
3317 }
3318 if (sq != NULL) {
3319 sq->end(didModify);
3320 sq->push(block);
3321 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07003322 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3323 mAudioWatchdog->pause();
3324 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003325
3326 // Now perform the deferred reset on fast tracks that have stopped
3327 while (resetMask != 0) {
3328 size_t i = __builtin_ctz(resetMask);
3329 ALOG_ASSERT(i < count);
3330 resetMask &= ~(1 << i);
3331 sp<Track> t = mActiveTracks[i].promote();
3332 if (t == 0) continue;
3333 Track* track = t.get();
3334 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3335 track->reset();
3336 }
Glenn Kasten58912562012-04-03 10:45:00 -07003337
Mathias Agopian65ab4712010-07-14 17:59:35 -07003338 // remove all the tracks that need to be...
3339 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003340 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003341 for (size_t i=0 ; i<count ; i++) {
3342 const sp<Track>& track = tracksToRemove->itemAt(i);
3343 mActiveTracks.remove(track);
3344 if (track->mainBuffer() != mMixBuffer) {
3345 chain = getEffectChain_l(track->sessionId());
3346 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003347 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003348 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003349 }
3350 }
3351 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003352 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003353 }
3354 }
3355 }
3356
3357 // mix buffer must be cleared if all tracks are connected to an
3358 // effect chain as in this case the mixer will not write to
3359 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003360 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3361 // FIXME as a performance optimization, should remember previous zero status
3362 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003363 }
3364
Glenn Kasten58912562012-04-03 10:45:00 -07003365 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003366 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003367 if (fastTracks > 0) {
3368 mixerStatus = MIXER_TRACKS_READY;
3369 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003370 return mixerStatus;
3371}
3372
Glenn Kasten66fcab92012-02-24 14:59:21 -08003373/*
3374The derived values that are cached:
3375 - mixBufferSize from frame count * frame size
3376 - activeSleepTime from activeSleepTimeUs()
3377 - idleSleepTime from idleSleepTimeUs()
3378 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3379 - maxPeriod from frame count and sample rate (MIXER only)
3380
3381The parameters that affect these derived values are:
3382 - frame count
3383 - frame size
3384 - sample rate
3385 - device type: A2DP or not
3386 - device latency
3387 - format: PCM or not
3388 - active sleep time
3389 - idle sleep time
3390*/
3391
3392void AudioFlinger::PlaybackThread::cacheParameters_l()
3393{
Glenn Kasten58912562012-04-03 10:45:00 -07003394 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003395 activeSleepTime = activeSleepTimeUs();
3396 idleSleepTime = idleSleepTimeUs();
3397}
3398
Eric Laurent22167852012-06-20 12:26:32 -07003399void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003400{
Steve Block3856b092011-10-20 11:56:00 +01003401 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003402 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003403 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003404
Mathias Agopian65ab4712010-07-14 17:59:35 -07003405 size_t size = mTracks.size();
3406 for (size_t i = 0; i < size; i++) {
3407 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003408 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003409 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003410 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003411 }
3412 }
3413}
3414
Mathias Agopian65ab4712010-07-14 17:59:35 -07003415// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003416int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003417{
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003418 return mAudioMixer->getTrackName(channelMask, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003419}
3420
3421// deleteTrackName_l() must be called with ThreadBase::mLock held
3422void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3423{
Steve Block3856b092011-10-20 11:56:00 +01003424 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003425 mAudioMixer->deleteTrackName(name);
3426}
3427
3428// checkForNewParameters_l() must be called with ThreadBase::mLock held
3429bool AudioFlinger::MixerThread::checkForNewParameters_l()
3430{
Glenn Kasten58912562012-04-03 10:45:00 -07003431 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3432 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003433 bool reconfig = false;
3434
3435 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003436
3437 if (mFastMixer != NULL) {
3438 FastMixerStateQueue *sq = mFastMixer->sq();
3439 FastMixerState *state = sq->begin();
3440 if (!(state->mCommand & FastMixerState::IDLE)) {
3441 previousCommand = state->mCommand;
3442 state->mCommand = FastMixerState::HOT_IDLE;
3443 sq->end();
3444 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3445 } else {
3446 sq->end(false /*didModify*/);
3447 }
3448 }
3449
Mathias Agopian65ab4712010-07-14 17:59:35 -07003450 status_t status = NO_ERROR;
3451 String8 keyValuePair = mNewParameters[0];
3452 AudioParameter param = AudioParameter(keyValuePair);
3453 int value;
3454
3455 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3456 reconfig = true;
3457 }
3458 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003459 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003460 status = BAD_VALUE;
3461 } else {
3462 reconfig = true;
3463 }
3464 }
3465 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003466 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003467 status = BAD_VALUE;
3468 } else {
3469 reconfig = true;
3470 }
3471 }
3472 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3473 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003474 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003475 // if frame count is changed after track creation
3476 if (!mTracks.isEmpty()) {
3477 status = INVALID_OPERATION;
3478 } else {
3479 reconfig = true;
3480 }
3481 }
3482 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003483#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003484 // when changing the audio output device, call addBatteryData to notify
3485 // the change
Eric Laurentf1c04f92012-08-28 14:26:53 -07003486 if (mOutDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003487 uint32_t params = 0;
3488 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003489 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003490 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3491 }
3492
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003493 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003494 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003495 // check if any other device (except speaker) is on
3496 if (value & deviceWithoutSpeaker ) {
3497 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3498 }
3499
3500 if (params != 0) {
3501 addBatteryData(params);
3502 }
3503 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003504#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003505
Mathias Agopian65ab4712010-07-14 17:59:35 -07003506 // forward device change to effects that have requested to be
3507 // aware of attached audio device.
Eric Laurentf1c04f92012-08-28 14:26:53 -07003508 mOutDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003509 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07003510 mEffectChains[i]->setDevice_l(mOutDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003511 }
3512 }
3513
3514 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003515 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003516 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003517 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003518 mOutput->stream->common.standby(&mOutput->stream->common);
3519 mStandby = true;
3520 mBytesWritten = 0;
3521 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003522 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003523 }
3524 if (status == NO_ERROR && reconfig) {
3525 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003526 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3527 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003528 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003529 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003530 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003531 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003532 if (name < 0) break;
3533 mTracks[i]->mName = name;
3534 // limit track sample rate to 2 x new output sample rate
3535 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3536 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3537 }
3538 }
Eric Laurent896adcd2012-09-13 11:18:23 -07003539 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003540 }
3541 }
3542
3543 mNewParameters.removeAt(0);
3544
3545 mParamStatus = status;
3546 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003547 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3548 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003549 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003550 }
Glenn Kasten58912562012-04-03 10:45:00 -07003551
3552 if (!(previousCommand & FastMixerState::IDLE)) {
3553 ALOG_ASSERT(mFastMixer != NULL);
3554 FastMixerStateQueue *sq = mFastMixer->sq();
3555 FastMixerState *state = sq->begin();
3556 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3557 state->mCommand = previousCommand;
3558 sq->end();
3559 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3560 }
3561
Mathias Agopian65ab4712010-07-14 17:59:35 -07003562 return reconfig;
3563}
3564
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07003565void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003566{
3567 const size_t SIZE = 256;
3568 char buffer[SIZE];
3569 String8 result;
3570
3571 PlaybackThread::dumpInternals(fd, args);
3572
3573 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3574 result.append(buffer);
3575 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003576
3577 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3578 FastMixerDumpState copy = mFastMixerDumpState;
3579 copy.dump(fd);
3580
Glenn Kasten39993082012-05-31 13:40:27 -07003581#ifdef STATE_QUEUE_DUMP
3582 // Similar for state queue
3583 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3584 observerCopy.dump(fd);
3585 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3586 mutatorCopy.dump(fd);
3587#endif
3588
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003589 // Write the tee output to a .wav file
3590 NBAIO_Source *teeSource = mTeeSource.get();
3591 if (teeSource != NULL) {
3592 char teePath[64];
3593 struct timeval tv;
3594 gettimeofday(&tv, NULL);
3595 struct tm tm;
3596 localtime_r(&tv.tv_sec, &tm);
3597 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3598 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3599 if (teeFd >= 0) {
3600 char wavHeader[44];
3601 memcpy(wavHeader,
3602 "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",
3603 sizeof(wavHeader));
3604 NBAIO_Format format = teeSource->format();
3605 unsigned channelCount = Format_channelCount(format);
3606 ALOG_ASSERT(channelCount <= FCC_2);
3607 unsigned sampleRate = Format_sampleRate(format);
3608 wavHeader[22] = channelCount; // number of channels
3609 wavHeader[24] = sampleRate; // sample rate
3610 wavHeader[25] = sampleRate >> 8;
3611 wavHeader[32] = channelCount * 2; // block alignment
3612 write(teeFd, wavHeader, sizeof(wavHeader));
3613 size_t total = 0;
3614 bool firstRead = true;
3615 for (;;) {
3616#define TEE_SINK_READ 1024
3617 short buffer[TEE_SINK_READ * FCC_2];
3618 size_t count = TEE_SINK_READ;
John Grossman2c3b2da2012-08-02 17:08:54 -07003619 ssize_t actual = teeSource->read(buffer, count,
3620 AudioBufferProvider::kInvalidPTS);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003621 bool wasFirstRead = firstRead;
3622 firstRead = false;
3623 if (actual <= 0) {
3624 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3625 continue;
3626 }
3627 break;
3628 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003629 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003630 write(teeFd, buffer, actual * channelCount * sizeof(short));
3631 total += actual;
3632 }
3633 lseek(teeFd, (off_t) 4, SEEK_SET);
3634 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3635 write(teeFd, &temp, sizeof(temp));
3636 lseek(teeFd, (off_t) 40, SEEK_SET);
3637 temp = total * channelCount * sizeof(short);
3638 write(teeFd, &temp, sizeof(temp));
3639 close(teeFd);
3640 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3641 } else {
3642 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3643 }
3644 }
3645
Glenn Kastenc15d6652012-05-30 14:52:57 -07003646 if (mAudioWatchdog != 0) {
3647 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3648 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3649 wdCopy.dump(fd);
3650 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003651}
3652
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003653uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003654{
Glenn Kasten58912562012-04-03 10:45:00 -07003655 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003656}
3657
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003658uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003659{
Glenn Kasten58912562012-04-03 10:45:00 -07003660 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003661}
3662
Glenn Kasten66fcab92012-02-24 14:59:21 -08003663void AudioFlinger::MixerThread::cacheParameters_l()
3664{
3665 PlaybackThread::cacheParameters_l();
3666
3667 // FIXME: Relaxed timing because of a certain device that can't meet latency
3668 // Should be reduced to 2x after the vendor fixes the driver issue
3669 // increase threshold again due to low power audio mode. The way this warning
3670 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003671 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003672}
3673
Mathias Agopian65ab4712010-07-14 17:59:35 -07003674// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003675AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003676 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003677 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003678 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003679{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003680}
3681
3682AudioFlinger::DirectOutputThread::~DirectOutputThread()
3683{
3684}
3685
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003686AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3687 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003688)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003689{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003690 sp<Track> trackToRemove;
3691
Glenn Kastenfec279f2012-03-08 07:47:15 -08003692 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003693
Glenn Kasten952eeb22012-03-06 11:30:57 -08003694 // find out which tracks need to be processed
3695 if (mActiveTracks.size() != 0) {
3696 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003697 // The track died recently
3698 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003699
Glenn Kasten952eeb22012-03-06 11:30:57 -08003700 Track* const track = t.get();
3701 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003702
Glenn Kasten952eeb22012-03-06 11:30:57 -08003703 // The first time a track is added we wait
3704 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003705 uint32_t minFrames;
3706 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3707 minFrames = mNormalFrameCount;
3708 } else {
3709 minFrames = 1;
3710 }
3711 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003712 !track->isPaused() && !track->isTerminated())
3713 {
3714 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003715
Glenn Kasten952eeb22012-03-06 11:30:57 -08003716 if (track->mFillingUpStatus == Track::FS_FILLED) {
3717 track->mFillingUpStatus = Track::FS_ACTIVE;
3718 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003719 if (track->mState == TrackBase::RESUMING) {
3720 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003721 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003722 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003723
Glenn Kasten952eeb22012-03-06 11:30:57 -08003724 // compute volume for this track
3725 float left, right;
3726 if (track->isMuted() || mMasterMute || track->isPausing() ||
3727 mStreamTypes[track->streamType()].mute) {
3728 left = right = 0;
3729 if (track->isPausing()) {
3730 track->setPaused();
3731 }
3732 } else {
3733 float typeVolume = mStreamTypes[track->streamType()].volume;
3734 float v = mMasterVolume * typeVolume;
3735 uint32_t vlr = cblk->getVolumeLR();
3736 float v_clamped = v * (vlr & 0xFFFF);
3737 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3738 left = v_clamped/MAX_GAIN;
3739 v_clamped = v * (vlr >> 16);
3740 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3741 right = v_clamped/MAX_GAIN;
3742 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003743
Glenn Kasten952eeb22012-03-06 11:30:57 -08003744 if (left != mLeftVolFloat || right != mRightVolFloat) {
3745 mLeftVolFloat = left;
3746 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003747
Glenn Kasten952eeb22012-03-06 11:30:57 -08003748 // Convert volumes from float to 8.24
3749 uint32_t vl = (uint32_t)(left * (1 << 24));
3750 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003751
Glenn Kasten952eeb22012-03-06 11:30:57 -08003752 // Delegate volume control to effect in track effect chain if needed
3753 // only one effect chain can be present on DirectOutputThread, so if
3754 // there is one, the track is connected to it
3755 if (!mEffectChains.isEmpty()) {
3756 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003757 mEffectChains[0]->setVolume_l(&vl, &vr);
3758 left = (float)vl / (1 << 24);
3759 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003760 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003761 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003762 }
3763
3764 // reset retry count
3765 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003766 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003767 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003768 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003769 // clear effect chain input buffer if an active track underruns to avoid sending
3770 // previous audio buffer again to effects
3771 if (!mEffectChains.isEmpty()) {
3772 mEffectChains[0]->clearInputBuffer();
3773 }
3774
Glenn Kasten952eeb22012-03-06 11:30:57 -08003775 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten842c5d92012-09-26 08:34:10 -07003776 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent67c0a582012-05-01 19:31:12 -07003777 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003778 // We have consumed all the buffers of this track.
3779 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003780 // TODO: implement behavior for compressed audio
3781 size_t audioHALFrames =
3782 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3783 size_t framesWritten =
3784 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3785 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003786 if (track->isStopped()) {
3787 track->reset();
3788 }
Eric Laurenta011e352012-03-29 15:51:43 -07003789 trackToRemove = track;
3790 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003791 } else {
3792 // No buffers for this track. Give it a few chances to
3793 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07003794 if (--(track->mRetryCount) <= 0) {
3795 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Glenn Kasten952eeb22012-03-06 11:30:57 -08003796 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003797 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003798 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003799 }
3800 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003801 }
3802 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003803
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003804 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003805 // remove all the tracks that need to be...
3806 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003807 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003808 mActiveTracks.remove(trackToRemove);
3809 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003810 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003811 trackToRemove->sessionId());
3812 mEffectChains[0]->decActiveTrackCnt();
3813 }
3814 if (trackToRemove->isTerminated()) {
3815 removeTrack_l(trackToRemove);
3816 }
3817 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003818
Glenn Kastenfec279f2012-03-08 07:47:15 -08003819 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003820}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003821
Glenn Kasten000f0e32012-03-01 17:10:56 -08003822void AudioFlinger::DirectOutputThread::threadLoop_mix()
3823{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003824 AudioBufferProvider::Buffer buffer;
3825 size_t frameCount = mFrameCount;
3826 int8_t *curBuf = (int8_t *)mMixBuffer;
3827 // output audio to hardware
3828 while (frameCount) {
3829 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003830 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003831 if (CC_UNLIKELY(buffer.raw == NULL)) {
3832 memset(curBuf, 0, frameCount * mFrameSize);
3833 break;
3834 }
3835 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3836 frameCount -= buffer.frameCount;
3837 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003838 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003839 }
3840 sleepTime = 0;
3841 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003842 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003843
Glenn Kasten000f0e32012-03-01 17:10:56 -08003844}
3845
3846void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3847{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003848 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003849 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003850 sleepTime = activeSleepTime;
3851 } else {
3852 sleepTime = idleSleepTime;
3853 }
3854 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003855 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003856 sleepTime = 0;
3857 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003858}
3859
3860// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003861int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3862 int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003863{
3864 return 0;
3865}
3866
3867// deleteTrackName_l() must be called with ThreadBase::mLock held
3868void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3869{
3870}
3871
3872// checkForNewParameters_l() must be called with ThreadBase::mLock held
3873bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3874{
3875 bool reconfig = false;
3876
3877 while (!mNewParameters.isEmpty()) {
3878 status_t status = NO_ERROR;
3879 String8 keyValuePair = mNewParameters[0];
3880 AudioParameter param = AudioParameter(keyValuePair);
3881 int value;
3882
3883 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3884 // do not accept frame count changes if tracks are open as the track buffer
3885 // size depends on frame count and correct behavior would not be garantied
3886 // if frame count is changed after track creation
3887 if (!mTracks.isEmpty()) {
3888 status = INVALID_OPERATION;
3889 } else {
3890 reconfig = true;
3891 }
3892 }
3893 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003894 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003895 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003896 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003897 mOutput->stream->common.standby(&mOutput->stream->common);
3898 mStandby = true;
3899 mBytesWritten = 0;
3900 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003901 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003902 }
3903 if (status == NO_ERROR && reconfig) {
3904 readOutputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07003905 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003906 }
3907 }
3908
3909 mNewParameters.removeAt(0);
3910
3911 mParamStatus = status;
3912 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003913 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3914 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003915 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003916 }
3917 return reconfig;
3918}
3919
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003920uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003921{
3922 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003923 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003924 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003925 } else {
3926 time = 10000;
3927 }
3928 return time;
3929}
3930
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003931uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003932{
3933 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003934 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003935 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003936 } else {
3937 time = 10000;
3938 }
3939 return time;
3940}
3941
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003942uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003943{
3944 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003945 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003946 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3947 } else {
3948 time = 10000;
3949 }
3950 return time;
3951}
3952
Glenn Kasten66fcab92012-02-24 14:59:21 -08003953void AudioFlinger::DirectOutputThread::cacheParameters_l()
3954{
3955 PlaybackThread::cacheParameters_l();
3956
3957 // use shorter standby delay as on normal output to release
3958 // hardware resources as soon as possible
3959 standbyDelay = microseconds(activeSleepTime*2);
3960}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003961
Mathias Agopian65ab4712010-07-14 17:59:35 -07003962// ----------------------------------------------------------------------------
3963
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003964AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003965 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Eric Laurentf1c04f92012-08-28 14:26:53 -07003966 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), DUPLICATING),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003967 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003968{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003969 addOutputTrack(mainThread);
3970}
3971
3972AudioFlinger::DuplicatingThread::~DuplicatingThread()
3973{
3974 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3975 mOutputTracks[i]->destroy();
3976 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003977}
3978
Glenn Kasten000f0e32012-03-01 17:10:56 -08003979void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003980{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003981 // mix buffers...
3982 if (outputsReady(outputTracks)) {
3983 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3984 } else {
3985 memset(mMixBuffer, 0, mixBufferSize);
3986 }
3987 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003988 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003989 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003990}
3991
3992void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3993{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003994 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003995 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003996 sleepTime = activeSleepTime;
3997 } else {
3998 sleepTime = idleSleepTime;
3999 }
4000 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004001 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4002 writeFrames = mNormalFrameCount;
4003 memset(mMixBuffer, 0, mixBufferSize);
4004 } else {
4005 // flush remaining overflow buffers in output tracks
4006 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004007 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004008 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004009 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08004010}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004011
Glenn Kasten000f0e32012-03-01 17:10:56 -08004012void AudioFlinger::DuplicatingThread::threadLoop_write()
4013{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004014 for (size_t i = 0; i < outputTracks.size(); i++) {
4015 outputTracks[i]->write(mMixBuffer, writeFrames);
4016 }
4017 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004018}
Glenn Kasten688a6402012-02-29 07:57:06 -08004019
Glenn Kasten000f0e32012-03-01 17:10:56 -08004020void AudioFlinger::DuplicatingThread::threadLoop_standby()
4021{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004022 // DuplicatingThread implements standby by stopping all tracks
4023 for (size_t i = 0; i < outputTracks.size(); i++) {
4024 outputTracks[i]->stop();
4025 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004026}
4027
Glenn Kastenfa26a852012-03-06 11:28:04 -08004028void AudioFlinger::DuplicatingThread::saveOutputTracks()
4029{
4030 outputTracks = mOutputTracks;
4031}
4032
4033void AudioFlinger::DuplicatingThread::clearOutputTracks()
4034{
4035 outputTracks.clear();
4036}
4037
Mathias Agopian65ab4712010-07-14 17:59:35 -07004038void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4039{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004040 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004041 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004042 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004043 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004044 this,
4045 mSampleRate,
4046 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004047 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004048 frameCount);
4049 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004050 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004051 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004052 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004053 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004054 }
4055}
4056
4057void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4058{
4059 Mutex::Autolock _l(mLock);
4060 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004061 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004062 mOutputTracks[i]->destroy();
4063 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004064 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004065 return;
4066 }
4067 }
Steve Block3856b092011-10-20 11:56:00 +01004068 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004069}
4070
Glenn Kasten438b0362012-03-06 11:24:48 -08004071// caller must hold mLock
4072void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004073{
4074 mWaitTimeMs = UINT_MAX;
4075 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4076 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004077 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004078 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4079 if (waitTimeMs < mWaitTimeMs) {
4080 mWaitTimeMs = waitTimeMs;
4081 }
4082 }
4083 }
4084}
4085
4086
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004087bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004088{
4089 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004090 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004091 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004092 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004093 return false;
4094 }
4095 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004096 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004097 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004098 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004099 return false;
4100 }
4101 }
4102 return true;
4103}
4104
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004105uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004106{
4107 return (mWaitTimeMs * 1000) / 2;
4108}
4109
Glenn Kasten66fcab92012-02-24 14:59:21 -08004110void AudioFlinger::DuplicatingThread::cacheParameters_l()
4111{
4112 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4113 updateWaitTime_l();
4114
4115 MixerThread::cacheParameters_l();
4116}
4117
Mathias Agopian65ab4712010-07-14 17:59:35 -07004118// ----------------------------------------------------------------------------
4119
4120// TrackBase constructor must be called with AudioFlinger::mLock held
4121AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004122 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004123 const sp<Client>& client,
4124 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004125 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004126 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004127 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004128 const sp<IMemory>& sharedBuffer,
4129 int sessionId)
4130 : RefBase(),
4131 mThread(thread),
4132 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004133 mCblk(NULL),
4134 // mBuffer
4135 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004136 mFrameCount(0),
4137 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004138 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004139 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004140 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004141 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004142 // mChannelCount
4143 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004144{
Steve Block3856b092011-10-20 11:56:00 +01004145 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004146
Steve Blockb8a80522011-12-20 16:23:08 +00004147 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004148 size_t size = sizeof(audio_track_cblk_t);
4149 uint8_t channelCount = popcount(channelMask);
4150 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4151 if (sharedBuffer == 0) {
4152 size += bufferSize;
4153 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004154
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004155 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004156 mCblkMemory = client->heap()->allocate(size);
4157 if (mCblkMemory != 0) {
4158 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004159 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004160 new(mCblk) audio_track_cblk_t();
4161 // clear all buffers
4162 mCblk->frameCount = frameCount;
4163 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004164// uncomment the following lines to quickly test 32-bit wraparound
4165// mCblk->user = 0xffff0000;
4166// mCblk->server = 0xffff0000;
4167// mCblk->userBase = 0xffff0000;
4168// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004169 mChannelCount = channelCount;
4170 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004171 if (sharedBuffer == 0) {
4172 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4173 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4174 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004175 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004176 mCblk->flags = CBLK_UNDERRUN_ON;
4177 } else {
4178 mBuffer = sharedBuffer->pointer();
4179 }
4180 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4181 }
4182 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004183 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004184 client->heap()->dump("AudioTrack");
4185 return;
4186 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004187 } else {
4188 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004189 // construct the shared structure in-place.
4190 new(mCblk) audio_track_cblk_t();
4191 // clear all buffers
4192 mCblk->frameCount = frameCount;
4193 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004194// uncomment the following lines to quickly test 32-bit wraparound
4195// mCblk->user = 0xffff0000;
4196// mCblk->server = 0xffff0000;
4197// mCblk->userBase = 0xffff0000;
4198// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004199 mChannelCount = channelCount;
4200 mChannelMask = channelMask;
4201 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4202 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4203 // Force underrun condition to avoid false underrun callback until first data is
4204 // written to buffer (other flags are cleared)
4205 mCblk->flags = CBLK_UNDERRUN_ON;
4206 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004207 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004208}
4209
4210AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4211{
Glenn Kastena0d68332012-01-27 16:47:15 -08004212 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004213 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004214 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004215 } else {
4216 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004217 }
4218 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004219 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004220 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004221 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004222 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004223 // If the client's reference count drops to zero, the associated destructor
4224 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4225 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004226 mClient.clear();
4227 }
4228}
4229
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004230// AudioBufferProvider interface
4231// getNextBuffer() = 0;
4232// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004233void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4234{
Glenn Kastene0feee32011-12-13 11:53:26 -08004235 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004236 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004237 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004238 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004239 buffer->frameCount = 0;
4240}
4241
4242bool AudioFlinger::ThreadBase::TrackBase::step() {
4243 bool result;
4244 audio_track_cblk_t* cblk = this->cblk();
4245
4246 result = cblk->stepServer(mFrameCount);
4247 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004248 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004249 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004250 }
4251 return result;
4252}
4253
4254void AudioFlinger::ThreadBase::TrackBase::reset() {
4255 audio_track_cblk_t* cblk = this->cblk();
4256
4257 cblk->user = 0;
4258 cblk->server = 0;
4259 cblk->userBase = 0;
4260 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004261 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004262 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004263}
4264
Mathias Agopian65ab4712010-07-14 17:59:35 -07004265int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4266 return (int)mCblk->sampleRate;
4267}
4268
Mathias Agopian65ab4712010-07-14 17:59:35 -07004269void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4270 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004271 size_t frameSize = cblk->frameSize;
4272 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4273 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004274
4275 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004276 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4277 "TrackBase::getBuffer buffer out of range:\n"
4278 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4279 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004280 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004281 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004282
4283 return bufferStart;
4284}
4285
Eric Laurenta011e352012-03-29 15:51:43 -07004286status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4287{
4288 mSyncEvents.add(event);
4289 return NO_ERROR;
4290}
4291
Mathias Agopian65ab4712010-07-14 17:59:35 -07004292// ----------------------------------------------------------------------------
4293
4294// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4295AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004296 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004297 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004298 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004299 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004300 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004301 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004302 int frameCount,
4303 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004304 int sessionId,
4305 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004306 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004307 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004308 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004309 // mRetryCount initialized later when needed
4310 mSharedBuffer(sharedBuffer),
4311 mStreamType(streamType),
4312 mName(-1), // see note below
4313 mMainBuffer(thread->mixBuffer()),
4314 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004315 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004316 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004317 mFlags(flags),
4318 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004319 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004320 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004321{
4322 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004323 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4324 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004325 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004326 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07004327 mName = thread->getTrackName_l(channelMask, sessionId);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004328 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004329 if (mName < 0) {
4330 ALOGE("no more track names available");
4331 return;
4332 }
4333 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004334 if (flags & IAudioFlinger::TRACK_FAST) {
4335 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4336 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4337 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004338 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004339 // FIXME This is too eager. We allocate a fast track index before the
4340 // fast track becomes active. Since fast tracks are a scarce resource,
4341 // this means we are potentially denying other more important fast tracks from
4342 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004343 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004344 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004345 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004346 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004347 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004348 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004349 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004350 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004351}
4352
4353AudioFlinger::PlaybackThread::Track::~Track()
4354{
Steve Block3856b092011-10-20 11:56:00 +01004355 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004356}
4357
4358void AudioFlinger::PlaybackThread::Track::destroy()
4359{
4360 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4361 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004362 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004363 // we must acquire a strong reference on this Track before locking mLock
4364 // here so that the destructor is called only when exiting this function.
4365 // On the other hand, as long as Track::destroy() is only called by
4366 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4367 // this Track with its member mTrack.
4368 sp<Track> keep(this);
4369 { // scope for mLock
4370 sp<ThreadBase> thread = mThread.promote();
4371 if (thread != 0) {
4372 if (!isOutputTrack()) {
4373 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004374 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004375
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004376#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004377 // to track the speaker usage
4378 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004379#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004380 }
4381 AudioSystem::releaseOutput(thread->id());
4382 }
4383 Mutex::Autolock _l(thread->mLock);
4384 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4385 playbackThread->destroyTrack_l(this);
4386 }
4387 }
4388}
4389
Glenn Kasten288ed212012-04-25 17:52:27 -07004390/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4391{
Glenn Kastene213c862012-04-25 13:46:15 -07004392 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 -07004393 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004394}
4395
Mathias Agopian65ab4712010-07-14 17:59:35 -07004396void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4397{
Glenn Kasten83d86532012-01-17 14:39:34 -08004398 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004399 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004400 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004401 } else {
4402 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4403 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004404 track_state state = mState;
4405 char stateChar;
4406 switch (state) {
4407 case IDLE:
4408 stateChar = 'I';
4409 break;
4410 case TERMINATED:
4411 stateChar = 'T';
4412 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004413 case STOPPING_1:
4414 stateChar = 's';
4415 break;
4416 case STOPPING_2:
4417 stateChar = '5';
4418 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004419 case STOPPED:
4420 stateChar = 'S';
4421 break;
4422 case RESUMING:
4423 stateChar = 'R';
4424 break;
4425 case ACTIVE:
4426 stateChar = 'A';
4427 break;
4428 case PAUSING:
4429 stateChar = 'p';
4430 break;
4431 case PAUSED:
4432 stateChar = 'P';
4433 break;
Eric Laurent29864602012-05-08 18:57:51 -07004434 case FLUSHED:
4435 stateChar = 'F';
4436 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004437 default:
4438 stateChar = '?';
4439 break;
4440 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004441 char nowInUnderrun;
4442 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4443 case UNDERRUN_FULL:
4444 nowInUnderrun = ' ';
4445 break;
4446 case UNDERRUN_PARTIAL:
4447 nowInUnderrun = '<';
4448 break;
4449 case UNDERRUN_EMPTY:
4450 nowInUnderrun = '*';
4451 break;
4452 default:
4453 nowInUnderrun = '?';
4454 break;
4455 }
Glenn Kastene213c862012-04-25 13:46:15 -07004456 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4457 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004458 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004459 mStreamType,
4460 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004461 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004462 mSessionId,
4463 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004464 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004465 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004466 mMute,
4467 mFillingUpStatus,
4468 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004469 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4470 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004471 mCblk->server,
4472 mCblk->user,
4473 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004474 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004475 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004476 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004477 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004478}
4479
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004480// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004481status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004482 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004483{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004484 audio_track_cblk_t* cblk = this->cblk();
4485 uint32_t framesReady;
4486 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004487
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004488 // Check if last stepServer failed, try to step now
4489 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004490 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4491 // Since the fast mixer is higher priority than client callback thread,
4492 // it does not result in priority inversion for client.
4493 // But a non-blocking solution would be preferable to avoid
4494 // fast mixer being unable to tryLock(), and
4495 // to avoid the extra context switches if the client wakes up,
4496 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004497 if (!step()) goto getNextBuffer_exit;
4498 ALOGV("stepServer recovered");
4499 mStepServerFailed = false;
4500 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004501
Glenn Kasten288ed212012-04-25 17:52:27 -07004502 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004503 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004504
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004505 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004506 uint32_t s = cblk->server;
4507 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4508
4509 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4510 if (framesReq > framesReady) {
4511 framesReq = framesReady;
4512 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004513 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004514 framesReq = bufferEnd - s;
4515 }
4516
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004517 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004518 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004519 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004520 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004521
4522getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004523 buffer->raw = NULL;
4524 buffer->frameCount = 0;
4525 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4526 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004527}
4528
Glenn Kasten288ed212012-04-25 17:52:27 -07004529// Note that framesReady() takes a mutex on the control block using tryLock().
4530// This could result in priority inversion if framesReady() is called by the normal mixer,
4531// as the normal mixer thread runs at lower
4532// priority than the client's callback thread: there is a short window within framesReady()
4533// during which the normal mixer could be preempted, and the client callback would block.
4534// Another problem can occur if framesReady() is called by the fast mixer:
4535// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4536// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4537size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004538 return mCblk->framesReady();
4539}
4540
Glenn Kasten288ed212012-04-25 17:52:27 -07004541// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004542bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004543 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004544
John Grossman4ff14ba2012-02-08 16:37:41 -08004545 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004546 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4547 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004548 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004549 return true;
4550 }
4551 return false;
4552}
4553
Glenn Kasten3acbd052012-02-28 10:39:56 -08004554status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004555 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004556{
4557 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004558 ALOGV("start(%d), calling pid %d session %d",
4559 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004560
Mathias Agopian65ab4712010-07-14 17:59:35 -07004561 sp<ThreadBase> thread = mThread.promote();
4562 if (thread != 0) {
4563 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004564 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004565 // here the track could be either new, or restarted
4566 // in both cases "unstop" the track
4567 if (mState == PAUSED) {
4568 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004569 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004570 } else {
4571 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004572 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004573 }
4574
4575 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4576 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004577 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004578 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004579
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004580#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004581 // to track the speaker usage
4582 if (status == NO_ERROR) {
4583 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4584 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004585#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004586 }
4587 if (status == NO_ERROR) {
4588 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4589 playbackThread->addTrack_l(this);
4590 } else {
4591 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004592 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004593 }
4594 } else {
4595 status = BAD_VALUE;
4596 }
4597 return status;
4598}
4599
4600void AudioFlinger::PlaybackThread::Track::stop()
4601{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004602 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004603 sp<ThreadBase> thread = mThread.promote();
4604 if (thread != 0) {
4605 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004606 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004607 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004608 // If the track is not active (PAUSED and buffers full), flush buffers
4609 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4610 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4611 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004612 mState = STOPPED;
4613 } else if (!isFastTrack()) {
4614 mState = STOPPED;
4615 } else {
4616 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4617 // and then to STOPPED and reset() when presentation is complete
4618 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004619 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004620 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004621 }
4622 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4623 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004624 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004625 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004626
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004627#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004628 // to track the speaker usage
4629 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004630#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004631 }
4632 }
4633}
4634
4635void AudioFlinger::PlaybackThread::Track::pause()
4636{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004637 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004638 sp<ThreadBase> thread = mThread.promote();
4639 if (thread != 0) {
4640 Mutex::Autolock _l(thread->mLock);
4641 if (mState == ACTIVE || mState == RESUMING) {
4642 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004643 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004644 if (!isOutputTrack()) {
4645 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004646 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004647 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004648
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004649#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004650 // to track the speaker usage
4651 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004652#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004653 }
4654 }
4655 }
4656}
4657
4658void AudioFlinger::PlaybackThread::Track::flush()
4659{
Steve Block3856b092011-10-20 11:56:00 +01004660 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004661 sp<ThreadBase> thread = mThread.promote();
4662 if (thread != 0) {
4663 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004664 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4665 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004666 return;
4667 }
4668 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004669 // FLUSHED state
4670 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004671 // do not reset the track if it is still in the process of being stopped or paused.
4672 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004673 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004674 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004675 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4676 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4677 reset();
4678 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004679 }
4680}
4681
4682void AudioFlinger::PlaybackThread::Track::reset()
4683{
4684 // Do not reset twice to avoid discarding data written just after a flush and before
4685 // the audioflinger thread detects the track is stopped.
4686 if (!mResetDone) {
4687 TrackBase::reset();
4688 // Force underrun condition to avoid false underrun callback until first data is
4689 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004690 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4691 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004692 mFillingUpStatus = FS_FILLING;
4693 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004694 if (mState == FLUSHED) {
4695 mState = IDLE;
4696 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004697 }
4698}
4699
4700void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4701{
4702 mMute = muted;
4703}
4704
Mathias Agopian65ab4712010-07-14 17:59:35 -07004705status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4706{
4707 status_t status = DEAD_OBJECT;
4708 sp<ThreadBase> thread = mThread.promote();
4709 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004710 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004711 sp<AudioFlinger> af = mClient->audioFlinger();
4712
4713 Mutex::Autolock _l(af->mLock);
4714
4715 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004716
Eric Laurent109347d2012-07-02 12:31:03 -07004717 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004718 Mutex::Autolock _dl(playbackThread->mLock);
4719 Mutex::Autolock _sl(srcThread->mLock);
4720 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4721 if (chain == 0) {
4722 return INVALID_OPERATION;
4723 }
4724
4725 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4726 if (effect == 0) {
4727 return INVALID_OPERATION;
4728 }
4729 srcThread->removeEffect_l(effect);
4730 playbackThread->addEffect_l(effect);
4731 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4732 if (effect->state() == EffectModule::ACTIVE ||
4733 effect->state() == EffectModule::STOPPING) {
4734 effect->start();
4735 }
4736
4737 sp<EffectChain> dstChain = effect->chain().promote();
4738 if (dstChain == 0) {
4739 srcThread->addEffect_l(effect);
4740 return INVALID_OPERATION;
4741 }
4742 AudioSystem::unregisterEffect(effect->id());
4743 AudioSystem::registerEffect(&effect->desc(),
4744 srcThread->id(),
4745 dstChain->strategy(),
4746 AUDIO_SESSION_OUTPUT_MIX,
4747 effect->id());
4748 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004749 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004750 }
4751 return status;
4752}
4753
4754void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4755{
4756 mAuxEffectId = EffectId;
4757 mAuxBuffer = buffer;
4758}
4759
Eric Laurenta011e352012-03-29 15:51:43 -07004760bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4761 size_t audioHalFrames)
4762{
4763 // a track is considered presented when the total number of frames written to audio HAL
4764 // corresponds to the number of frames written when presentationComplete() is called for the
4765 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4766 if (mPresentationCompleteFrames == 0) {
4767 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4768 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4769 mPresentationCompleteFrames, audioHalFrames);
4770 }
4771 if (framesWritten >= mPresentationCompleteFrames) {
4772 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4773 mSessionId, framesWritten);
4774 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004775 return true;
4776 }
4777 return false;
4778}
4779
4780void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4781{
4782 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4783 if (mSyncEvents[i]->type() == type) {
4784 mSyncEvents[i]->trigger();
4785 mSyncEvents.removeAt(i);
4786 i--;
4787 }
4788 }
4789}
4790
Glenn Kasten58912562012-04-03 10:45:00 -07004791// implement VolumeBufferProvider interface
4792
4793uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4794{
4795 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4796 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4797 uint32_t vlr = mCblk->getVolumeLR();
4798 uint32_t vl = vlr & 0xFFFF;
4799 uint32_t vr = vlr >> 16;
4800 // track volumes come from shared memory, so can't be trusted and must be clamped
4801 if (vl > MAX_GAIN_INT) {
4802 vl = MAX_GAIN_INT;
4803 }
4804 if (vr > MAX_GAIN_INT) {
4805 vr = MAX_GAIN_INT;
4806 }
4807 // now apply the cached master volume and stream type volume;
4808 // this is trusted but lacks any synchronization or barrier so may be stale
4809 float v = mCachedVolume;
4810 vl *= v;
4811 vr *= v;
4812 // re-combine into U4.16
4813 vlr = (vr << 16) | (vl & 0xFFFF);
4814 // FIXME look at mute, pause, and stop flags
4815 return vlr;
4816}
Eric Laurenta011e352012-03-29 15:51:43 -07004817
Eric Laurent29864602012-05-08 18:57:51 -07004818status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4819{
4820 if (mState == TERMINATED || mState == PAUSED ||
4821 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4822 (mState == STOPPED)))) {
4823 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4824 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4825 event->cancel();
4826 return INVALID_OPERATION;
4827 }
Glenn Kastend23eedc2012-08-02 13:35:47 -07004828 (void) TrackBase::setSyncEvent(event);
Eric Laurent29864602012-05-08 18:57:51 -07004829 return NO_ERROR;
4830}
4831
John Grossman4ff14ba2012-02-08 16:37:41 -08004832// timed audio tracks
4833
4834sp<AudioFlinger::PlaybackThread::TimedTrack>
4835AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004836 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004837 const sp<Client>& client,
4838 audio_stream_type_t streamType,
4839 uint32_t sampleRate,
4840 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004841 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004842 int frameCount,
4843 const sp<IMemory>& sharedBuffer,
4844 int sessionId) {
4845 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004846 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004847
Glenn Kastena0356762012-03-19 10:38:51 -07004848 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004849 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4850 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004851}
4852
4853AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004854 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004855 const sp<Client>& client,
4856 audio_stream_type_t streamType,
4857 uint32_t sampleRate,
4858 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004859 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004860 int frameCount,
4861 const sp<IMemory>& sharedBuffer,
4862 int sessionId)
4863 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004864 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004865 mQueueHeadInFlight(false),
4866 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004867 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004868 mTimedSilenceBuffer(NULL),
4869 mTimedSilenceBufferSize(0),
4870 mTimedAudioOutputOnTime(false),
4871 mMediaTimeTransformValid(false)
4872{
4873 LocalClock lc;
4874 mLocalTimeFreq = lc.getLocalFreq();
4875
4876 mLocalTimeToSampleTransform.a_zero = 0;
4877 mLocalTimeToSampleTransform.b_zero = 0;
4878 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4879 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4880 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4881 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004882
4883 mMediaTimeToSampleTransform.a_zero = 0;
4884 mMediaTimeToSampleTransform.b_zero = 0;
4885 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4886 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4887 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4888 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004889}
4890
4891AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4892 mClient->releaseTimedTrack();
4893 delete [] mTimedSilenceBuffer;
4894}
4895
4896status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4897 size_t size, sp<IMemory>* buffer) {
4898
4899 Mutex::Autolock _l(mTimedBufferQueueLock);
4900
4901 trimTimedBufferQueue_l();
4902
4903 // lazily initialize the shared memory heap for timed buffers
4904 if (mTimedMemoryDealer == NULL) {
4905 const int kTimedBufferHeapSize = 512 << 10;
4906
4907 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4908 "AudioFlingerTimed");
4909 if (mTimedMemoryDealer == NULL)
4910 return NO_MEMORY;
4911 }
4912
4913 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4914 if (newBuffer == NULL) {
4915 newBuffer = mTimedMemoryDealer->allocate(size);
4916 if (newBuffer == NULL)
4917 return NO_MEMORY;
4918 }
4919
4920 *buffer = newBuffer;
4921 return NO_ERROR;
4922}
4923
4924// caller must hold mTimedBufferQueueLock
4925void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4926 int64_t mediaTimeNow;
4927 {
4928 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4929 if (!mMediaTimeTransformValid)
4930 return;
4931
4932 int64_t targetTimeNow;
4933 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4934 ? mCCHelper.getCommonTime(&targetTimeNow)
4935 : mCCHelper.getLocalTime(&targetTimeNow);
4936
4937 if (OK != res)
4938 return;
4939
4940 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4941 &mediaTimeNow)) {
4942 return;
4943 }
4944 }
4945
John Grossman1c345192012-03-27 14:00:17 -07004946 size_t trimEnd;
4947 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004948 int64_t bufEnd;
4949
John Grossmanc95cfbb2012-04-12 11:53:11 -07004950 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4951 // We have a next buffer. Just use its PTS as the PTS of the frame
4952 // following the last frame in this buffer. If the stream is sparse
4953 // (ie, there are deliberate gaps left in the stream which should be
4954 // filled with silence by the TimedAudioTrack), then this can result
4955 // in one extra buffer being left un-trimmed when it could have
4956 // been. In general, this is not typical, and we would rather
4957 // optimized away the TS calculation below for the more common case
4958 // where PTSes are contiguous.
4959 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4960 } else {
4961 // We have no next buffer. Compute the PTS of the frame following
4962 // the last frame in this buffer by computing the duration of of
4963 // this frame in media time units and adding it to the PTS of the
4964 // buffer.
4965 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4966 / mCblk->frameSize;
4967
4968 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4969 &bufEnd)) {
4970 ALOGE("Failed to convert frame count of %lld to media time"
4971 " duration" " (scale factor %d/%u) in %s",
4972 frameCount,
4973 mMediaTimeToSampleTransform.a_to_b_numer,
4974 mMediaTimeToSampleTransform.a_to_b_denom,
4975 __PRETTY_FUNCTION__);
4976 break;
4977 }
4978 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004979 }
John Grossman9fbdee12012-03-26 17:51:46 -07004980
4981 if (bufEnd > mediaTimeNow)
4982 break;
4983
4984 // Is the buffer we want to use in the middle of a mix operation right
4985 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4986 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004987 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004988 mTrimQueueHeadOnRelease = true;
4989 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004990 }
4991
John Grossman9fbdee12012-03-26 17:51:46 -07004992 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004993 if (trimStart < trimEnd) {
4994 // Update the bookkeeping for framesReady()
4995 for (size_t i = trimStart; i < trimEnd; ++i) {
4996 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4997 }
4998
4999 // Now actually remove the buffers from the queue.
5000 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08005001 }
5002}
5003
John Grossman1c345192012-03-27 14:00:17 -07005004void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
5005 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07005006 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
5007 "%s called (reason \"%s\"), but timed buffer queue has no"
5008 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005009
5010 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
5011 mTimedBufferQueue.removeAt(0);
5012}
5013
5014void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
5015 const TimedBuffer& buf,
5016 const char* logTag) {
5017 uint32_t bufBytes = buf.buffer()->size();
5018 uint32_t consumedAlready = buf.position();
5019
Eric Laurentb388e532012-04-14 13:32:48 -07005020 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07005021 "Bad bookkeeping while updating frames pending. Timed buffer is"
5022 " only %u bytes long, but claims to have consumed %u"
5023 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07005024 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005025
5026 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07005027 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5028 "Bad bookkeeping while updating frames pending. Should have at"
5029 " least %u queued frames, but we think we have only %u. (update"
5030 " reason: \"%s\")",
5031 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005032
5033 mFramesPendingInQueue -= bufFrames;
5034}
5035
John Grossman4ff14ba2012-02-08 16:37:41 -08005036status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5037 const sp<IMemory>& buffer, int64_t pts) {
5038
5039 {
5040 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5041 if (!mMediaTimeTransformValid)
5042 return INVALID_OPERATION;
5043 }
5044
5045 Mutex::Autolock _l(mTimedBufferQueueLock);
5046
John Grossman1c345192012-03-27 14:00:17 -07005047 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5048 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005049 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5050
5051 return NO_ERROR;
5052}
5053
5054status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5055 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5056
John Grossman1c345192012-03-27 14:00:17 -07005057 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5058 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5059 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005060
5061 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5062 target == TimedAudioTrack::COMMON_TIME)) {
5063 return BAD_VALUE;
5064 }
5065
5066 Mutex::Autolock lock(mMediaTimeTransformLock);
5067 mMediaTimeTransform = xform;
5068 mMediaTimeTransformTarget = target;
5069 mMediaTimeTransformValid = true;
5070
5071 return NO_ERROR;
5072}
5073
5074#define min(a, b) ((a) < (b) ? (a) : (b))
5075
5076// implementation of getNextBuffer for tracks whose buffers have timestamps
5077status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5078 AudioBufferProvider::Buffer* buffer, int64_t pts)
5079{
5080 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005081 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005082 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005083 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005084 return INVALID_OPERATION;
5085 }
5086
John Grossman4ff14ba2012-02-08 16:37:41 -08005087 Mutex::Autolock _l(mTimedBufferQueueLock);
5088
John Grossman9fbdee12012-03-26 17:51:46 -07005089 ALOG_ASSERT(!mQueueHeadInFlight,
5090 "getNextBuffer called without releaseBuffer!");
5091
John Grossman4ff14ba2012-02-08 16:37:41 -08005092 while (true) {
5093
5094 // if we have no timed buffers, then fail
5095 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005096 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005097 buffer->frameCount = 0;
5098 return NOT_ENOUGH_DATA;
5099 }
5100
5101 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5102
5103 // calculate the PTS of the head of the timed buffer queue expressed in
5104 // local time
5105 int64_t headLocalPTS;
5106 {
5107 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5108
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005109 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005110
5111 if (mMediaTimeTransform.a_to_b_denom == 0) {
5112 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005113 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005114 return NO_ERROR;
5115 }
5116
5117 int64_t transformedPTS;
5118 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5119 &transformedPTS)) {
5120 // the transform failed. this shouldn't happen, but if it does
5121 // then just drop this buffer
5122 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005123 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005124 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005125 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005126 return NO_ERROR;
5127 }
5128
5129 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5130 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5131 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005132 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005133 buffer->frameCount = 0;
5134 return INVALID_OPERATION;
5135 }
5136 } else {
5137 headLocalPTS = transformedPTS;
5138 }
5139 }
5140
5141 // adjust the head buffer's PTS to reflect the portion of the head buffer
5142 // that has already been consumed
5143 int64_t effectivePTS = headLocalPTS +
5144 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5145
5146 // Calculate the delta in samples between the head of the input buffer
5147 // queue and the start of the next output buffer that will be written.
5148 // If the transformation fails because of over or underflow, it means
5149 // that the sample's position in the output stream is so far out of
5150 // whack that it should just be dropped.
5151 int64_t sampleDelta;
5152 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5153 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005154 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5155 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005156 continue;
5157 }
5158 if (!mLocalTimeToSampleTransform.doForwardTransform(
5159 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005160 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005161 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005162 continue;
5163 }
5164
John Grossman1c345192012-03-27 14:00:17 -07005165 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5166 " sampleDelta=[%d.%08x]",
5167 head.pts(), head.position(), pts,
5168 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5169 + (sampleDelta >> 32)),
5170 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005171
5172 // if the delta between the ideal placement for the next input sample and
5173 // the current output position is within this threshold, then we will
5174 // concatenate the next input samples to the previous output
5175 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005176 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005177
5178 // if this is the first buffer of audio that we're emitting from this track
5179 // then it should be almost exactly on time.
5180 const int64_t kSampleStartupThreshold = 1LL << 32;
5181
5182 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005183 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005184 // the next input is close enough to being on time, so concatenate it
5185 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005186 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005187
John Grossman1c345192012-03-27 14:00:17 -07005188 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5189 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005190 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005191 }
5192
5193 // Looks like our output is not on time. Reset our on timed status.
5194 // Next time we mix samples from our input queue, then should be within
5195 // the StartupThreshold.
5196 mTimedAudioOutputOnTime = false;
5197 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005198 // the gap between the current output position and the proper start of
5199 // the next input sample is too big, so fill it with silence
5200 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5201
John Grossman9fbdee12012-03-26 17:51:46 -07005202 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005203 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5204 return NO_ERROR;
5205 } else {
5206 // the next input sample is late
5207 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5208 size_t onTimeSamplePosition =
5209 head.position() + lateFrames * mCblk->frameSize;
5210
5211 if (onTimeSamplePosition > head.buffer()->size()) {
5212 // all the remaining samples in the head are too late, so
5213 // drop it and move on
5214 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005215 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005216 continue;
5217 } else {
5218 // skip over the late samples
5219 head.setPosition(onTimeSamplePosition);
5220
5221 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005222 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005223
5224 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5225 return NO_ERROR;
5226 }
5227 }
5228 }
5229}
5230
5231// Yield samples from the timed buffer queue head up to the given output
5232// buffer's capacity.
5233//
5234// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005235void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005236 AudioBufferProvider::Buffer* buffer) {
5237
5238 const TimedBuffer& head = mTimedBufferQueue[0];
5239
5240 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5241 head.position());
5242
5243 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5244 mCblk->frameSize);
5245 size_t framesRequested = buffer->frameCount;
5246 buffer->frameCount = min(framesLeftInHead, framesRequested);
5247
John Grossman9fbdee12012-03-26 17:51:46 -07005248 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005249 mTimedAudioOutputOnTime = true;
5250}
5251
5252// Yield samples of silence up to the given output buffer's capacity
5253//
5254// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005255void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005256 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5257
5258 // lazily allocate a buffer filled with silence
5259 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5260 delete [] mTimedSilenceBuffer;
5261 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5262 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5263 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5264 }
5265
5266 buffer->raw = mTimedSilenceBuffer;
5267 size_t framesRequested = buffer->frameCount;
5268 buffer->frameCount = min(numFrames, framesRequested);
5269
5270 mTimedAudioOutputOnTime = false;
5271}
5272
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005273// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005274void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5275 AudioBufferProvider::Buffer* buffer) {
5276
5277 Mutex::Autolock _l(mTimedBufferQueueLock);
5278
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005279 // If the buffer which was just released is part of the buffer at the head
5280 // of the queue, be sure to update the amt of the buffer which has been
5281 // consumed. If the buffer being returned is not part of the head of the
5282 // queue, its either because the buffer is part of the silence buffer, or
5283 // because the head of the timed queue was trimmed after the mixer called
5284 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005285 if (buffer->raw == mTimedSilenceBuffer) {
5286 ALOG_ASSERT(!mQueueHeadInFlight,
5287 "Queue head in flight during release of silence buffer!");
5288 goto done;
5289 }
5290
5291 ALOG_ASSERT(mQueueHeadInFlight,
5292 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5293 " head in flight.");
5294
5295 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005296 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005297
5298 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005299 void* end = reinterpret_cast<void*>(
5300 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5301 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005302
John Grossman9fbdee12012-03-26 17:51:46 -07005303 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5304 "released buffer not within the head of the timed buffer"
5305 " queue; qHead = [%p, %p], released buffer = %p",
5306 start, end, buffer->raw);
5307
5308 head.setPosition(head.position() +
5309 (buffer->frameCount * mCblk->frameSize));
5310 mQueueHeadInFlight = false;
5311
John Grossman1c345192012-03-27 14:00:17 -07005312 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5313 "Bad bookkeeping during releaseBuffer! Should have at"
5314 " least %u queued frames, but we think we have only %u",
5315 buffer->frameCount, mFramesPendingInQueue);
5316
5317 mFramesPendingInQueue -= buffer->frameCount;
5318
John Grossman9fbdee12012-03-26 17:51:46 -07005319 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5320 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005321 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005322 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005323 }
John Grossman9fbdee12012-03-26 17:51:46 -07005324 } else {
5325 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5326 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005327 }
5328
John Grossman9fbdee12012-03-26 17:51:46 -07005329done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005330 buffer->raw = 0;
5331 buffer->frameCount = 0;
5332}
5333
Glenn Kasten288ed212012-04-25 17:52:27 -07005334size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005335 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005336 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005337}
5338
5339AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5340 : mPTS(0), mPosition(0) {}
5341
5342AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5343 const sp<IMemory>& buffer, int64_t pts)
5344 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5345
Mathias Agopian65ab4712010-07-14 17:59:35 -07005346// ----------------------------------------------------------------------------
5347
5348// RecordTrack constructor must be called with AudioFlinger::mLock held
5349AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005350 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005351 const sp<Client>& client,
5352 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005353 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005354 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005355 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005356 int sessionId)
5357 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005358 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005359 mOverflow(false)
5360{
5361 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005362 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5363 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5364 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5365 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5366 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5367 } else {
5368 mCblk->frameSize = sizeof(int8_t);
5369 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005370 }
5371}
5372
5373AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5374{
Glenn Kasten510a3d62012-07-16 14:24:34 -07005375 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005376}
5377
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005378// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005379status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005380{
5381 audio_track_cblk_t* cblk = this->cblk();
5382 uint32_t framesAvail;
5383 uint32_t framesReq = buffer->frameCount;
5384
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005385 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005386 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005387 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005388 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005389 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005390 }
5391
5392 framesAvail = cblk->framesAvailable_l();
5393
Glenn Kastenf6b16782011-12-15 09:51:17 -08005394 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005395 uint32_t s = cblk->server;
5396 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5397
5398 if (framesReq > framesAvail) {
5399 framesReq = framesAvail;
5400 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005401 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005402 framesReq = bufferEnd - s;
5403 }
5404
5405 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005406 buffer->frameCount = framesReq;
5407 return NO_ERROR;
5408 }
5409
5410getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005411 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005412 buffer->frameCount = 0;
5413 return NOT_ENOUGH_DATA;
5414}
5415
Glenn Kasten3acbd052012-02-28 10:39:56 -08005416status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005417 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005418{
5419 sp<ThreadBase> thread = mThread.promote();
5420 if (thread != 0) {
5421 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005422 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005423 } else {
5424 return BAD_VALUE;
5425 }
5426}
5427
5428void AudioFlinger::RecordThread::RecordTrack::stop()
5429{
5430 sp<ThreadBase> thread = mThread.promote();
5431 if (thread != 0) {
5432 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005433 recordThread->mLock.lock();
5434 bool doStop = recordThread->stop_l(this);
5435 if (doStop) {
5436 TrackBase::reset();
5437 // Force overrun condition to avoid false overrun callback until first data is
5438 // read from buffer
5439 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5440 }
5441 recordThread->mLock.unlock();
5442 if (doStop) {
5443 AudioSystem::stopInput(recordThread->id());
5444 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005445 }
5446}
5447
Glenn Kasten510a3d62012-07-16 14:24:34 -07005448/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
5449{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005450 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User FrameCount\n");
Glenn Kasten510a3d62012-07-16 14:24:34 -07005451}
5452
Mathias Agopian65ab4712010-07-14 17:59:35 -07005453void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5454{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005455 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x %05d\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005456 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005457 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005458 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005459 mSessionId,
5460 mFrameCount,
5461 mState,
5462 mCblk->sampleRate,
5463 mCblk->server,
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005464 mCblk->user,
5465 mCblk->frameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005466}
5467
5468
5469// ----------------------------------------------------------------------------
5470
5471AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005472 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005473 DuplicatingThread *sourceThread,
5474 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005475 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005476 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005477 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005478 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5479 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005480 mActive(false), mSourceThread(sourceThread)
5481{
5482
Mathias Agopian65ab4712010-07-14 17:59:35 -07005483 if (mCblk != NULL) {
5484 mCblk->flags |= CBLK_DIRECTION_OUT;
5485 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005486 mOutBuffer.frameCount = 0;
5487 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005488 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005489 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5490 mCblk, mBuffer, mCblk->buffers,
5491 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005492 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005493 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005494 }
5495}
5496
5497AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5498{
5499 clearBufferQueue();
5500}
5501
Glenn Kasten3acbd052012-02-28 10:39:56 -08005502status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005503 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005504{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005505 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005506 if (status != NO_ERROR) {
5507 return status;
5508 }
5509
5510 mActive = true;
5511 mRetryCount = 127;
5512 return status;
5513}
5514
5515void AudioFlinger::PlaybackThread::OutputTrack::stop()
5516{
5517 Track::stop();
5518 clearBufferQueue();
5519 mOutBuffer.frameCount = 0;
5520 mActive = false;
5521}
5522
5523bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5524{
5525 Buffer *pInBuffer;
5526 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005527 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005528 bool outputBufferFull = false;
5529 inBuffer.frameCount = frames;
5530 inBuffer.i16 = data;
5531
5532 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5533
5534 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005535 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005536 sp<ThreadBase> thread = mThread.promote();
5537 if (thread != 0) {
5538 MixerThread *mixerThread = (MixerThread *)thread.get();
5539 if (mCblk->frameCount > frames){
5540 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5541 uint32_t startFrames = (mCblk->frameCount - frames);
5542 pInBuffer = new Buffer;
5543 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5544 pInBuffer->frameCount = startFrames;
5545 pInBuffer->i16 = pInBuffer->mBuffer;
5546 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5547 mBufferQueue.add(pInBuffer);
5548 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005549 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005550 }
5551 }
5552 }
5553 }
5554
5555 while (waitTimeLeftMs) {
5556 // First write pending buffers, then new data
5557 if (mBufferQueue.size()) {
5558 pInBuffer = mBufferQueue.itemAt(0);
5559 } else {
5560 pInBuffer = &inBuffer;
5561 }
5562
5563 if (pInBuffer->frameCount == 0) {
5564 break;
5565 }
5566
5567 if (mOutBuffer.frameCount == 0) {
5568 mOutBuffer.frameCount = pInBuffer->frameCount;
5569 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005570 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005571 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005572 outputBufferFull = true;
5573 break;
5574 }
5575 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5576 if (waitTimeLeftMs >= waitTimeMs) {
5577 waitTimeLeftMs -= waitTimeMs;
5578 } else {
5579 waitTimeLeftMs = 0;
5580 }
5581 }
5582
5583 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5584 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5585 mCblk->stepUser(outFrames);
5586 pInBuffer->frameCount -= outFrames;
5587 pInBuffer->i16 += outFrames * channelCount;
5588 mOutBuffer.frameCount -= outFrames;
5589 mOutBuffer.i16 += outFrames * channelCount;
5590
5591 if (pInBuffer->frameCount == 0) {
5592 if (mBufferQueue.size()) {
5593 mBufferQueue.removeAt(0);
5594 delete [] pInBuffer->mBuffer;
5595 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005596 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005597 } else {
5598 break;
5599 }
5600 }
5601 }
5602
5603 // If we could not write all frames, allocate a buffer and queue it for next time.
5604 if (inBuffer.frameCount) {
5605 sp<ThreadBase> thread = mThread.promote();
5606 if (thread != 0 && !thread->standby()) {
5607 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5608 pInBuffer = new Buffer;
5609 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5610 pInBuffer->frameCount = inBuffer.frameCount;
5611 pInBuffer->i16 = pInBuffer->mBuffer;
5612 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5613 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005614 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005615 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005616 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005617 }
5618 }
5619 }
5620
5621 // Calling write() with a 0 length buffer, means that no more data will be written:
5622 // If no more buffers are pending, fill output track buffer to make sure it is started
5623 // by output mixer.
5624 if (frames == 0 && mBufferQueue.size() == 0) {
5625 if (mCblk->user < mCblk->frameCount) {
5626 frames = mCblk->frameCount - mCblk->user;
5627 pInBuffer = new Buffer;
5628 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5629 pInBuffer->frameCount = frames;
5630 pInBuffer->i16 = pInBuffer->mBuffer;
5631 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5632 mBufferQueue.add(pInBuffer);
5633 } else if (mActive) {
5634 stop();
5635 }
5636 }
5637
5638 return outputBufferFull;
5639}
5640
5641status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5642{
5643 int active;
5644 status_t result;
5645 audio_track_cblk_t* cblk = mCblk;
5646 uint32_t framesReq = buffer->frameCount;
5647
Steve Block3856b092011-10-20 11:56:00 +01005648// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005649 buffer->frameCount = 0;
5650
5651 uint32_t framesAvail = cblk->framesAvailable();
5652
5653
5654 if (framesAvail == 0) {
5655 Mutex::Autolock _l(cblk->lock);
5656 goto start_loop_here;
5657 while (framesAvail == 0) {
5658 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005659 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005660 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005661 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005662 }
5663 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5664 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005665 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005666 }
5667 // read the server count again
5668 start_loop_here:
5669 framesAvail = cblk->framesAvailable_l();
5670 }
5671 }
5672
5673// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005674// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005675// }
5676
5677 if (framesReq > framesAvail) {
5678 framesReq = framesAvail;
5679 }
5680
5681 uint32_t u = cblk->user;
5682 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5683
Marco Nelissena1472d92012-03-30 14:36:54 -07005684 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005685 framesReq = bufferEnd - u;
5686 }
5687
5688 buffer->frameCount = framesReq;
5689 buffer->raw = (void *)cblk->buffer(u);
5690 return NO_ERROR;
5691}
5692
5693
5694void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5695{
5696 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005697
5698 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005699 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005700 delete [] pBuffer->mBuffer;
5701 delete pBuffer;
5702 }
5703 mBufferQueue.clear();
5704}
5705
5706// ----------------------------------------------------------------------------
5707
5708AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5709 : RefBase(),
5710 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005711 // 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 -07005712 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005713 mPid(pid),
5714 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005715{
5716 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5717}
5718
5719// Client destructor must be called with AudioFlinger::mLock held
5720AudioFlinger::Client::~Client()
5721{
5722 mAudioFlinger->removeClient_l(mPid);
5723}
5724
Glenn Kasten435dbe62012-01-30 10:15:48 -08005725sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005726{
5727 return mMemoryDealer;
5728}
5729
John Grossman4ff14ba2012-02-08 16:37:41 -08005730// Reserve one of the limited slots for a timed audio track associated
5731// with this client
5732bool AudioFlinger::Client::reserveTimedTrack()
5733{
5734 const int kMaxTimedTracksPerClient = 4;
5735
5736 Mutex::Autolock _l(mTimedTrackLock);
5737
5738 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5739 ALOGW("can not create timed track - pid %d has exceeded the limit",
5740 mPid);
5741 return false;
5742 }
5743
5744 mTimedTrackCount++;
5745 return true;
5746}
5747
5748// Release a slot for a timed audio track
5749void AudioFlinger::Client::releaseTimedTrack()
5750{
5751 Mutex::Autolock _l(mTimedTrackLock);
5752 mTimedTrackCount--;
5753}
5754
Mathias Agopian65ab4712010-07-14 17:59:35 -07005755// ----------------------------------------------------------------------------
5756
5757AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5758 const sp<IAudioFlingerClient>& client,
5759 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005760 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005761{
5762}
5763
5764AudioFlinger::NotificationClient::~NotificationClient()
5765{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005766}
5767
5768void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5769{
5770 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005771 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005772}
5773
5774// ----------------------------------------------------------------------------
5775
5776AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5777 : BnAudioTrack(),
5778 mTrack(track)
5779{
5780}
5781
5782AudioFlinger::TrackHandle::~TrackHandle() {
5783 // just stop the track on deletion, associated resources
5784 // will be freed from the main thread once all pending buffers have
5785 // been played. Unless it's not in the active track list, in which
5786 // case we free everything now...
5787 mTrack->destroy();
5788}
5789
Glenn Kasten90716c52012-01-26 13:40:12 -08005790sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5791 return mTrack->getCblk();
5792}
5793
Glenn Kasten3acbd052012-02-28 10:39:56 -08005794status_t AudioFlinger::TrackHandle::start() {
5795 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005796}
5797
5798void AudioFlinger::TrackHandle::stop() {
5799 mTrack->stop();
5800}
5801
5802void AudioFlinger::TrackHandle::flush() {
5803 mTrack->flush();
5804}
5805
5806void AudioFlinger::TrackHandle::mute(bool e) {
5807 mTrack->mute(e);
5808}
5809
5810void AudioFlinger::TrackHandle::pause() {
5811 mTrack->pause();
5812}
5813
Mathias Agopian65ab4712010-07-14 17:59:35 -07005814status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5815{
5816 return mTrack->attachAuxEffect(EffectId);
5817}
5818
John Grossman4ff14ba2012-02-08 16:37:41 -08005819status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5820 sp<IMemory>* buffer) {
5821 if (!mTrack->isTimedTrack())
5822 return INVALID_OPERATION;
5823
5824 PlaybackThread::TimedTrack* tt =
5825 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5826 return tt->allocateTimedBuffer(size, buffer);
5827}
5828
5829status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5830 int64_t pts) {
5831 if (!mTrack->isTimedTrack())
5832 return INVALID_OPERATION;
5833
5834 PlaybackThread::TimedTrack* tt =
5835 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5836 return tt->queueTimedBuffer(buffer, pts);
5837}
5838
5839status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5840 const LinearTransform& xform, int target) {
5841
5842 if (!mTrack->isTimedTrack())
5843 return INVALID_OPERATION;
5844
5845 PlaybackThread::TimedTrack* tt =
5846 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5847 return tt->setMediaTimeTransform(
5848 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5849}
5850
Mathias Agopian65ab4712010-07-14 17:59:35 -07005851status_t AudioFlinger::TrackHandle::onTransact(
5852 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5853{
5854 return BnAudioTrack::onTransact(code, data, reply, flags);
5855}
5856
5857// ----------------------------------------------------------------------------
5858
5859sp<IAudioRecord> AudioFlinger::openRecord(
5860 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005861 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005862 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005863 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005864 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005865 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005866 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07005867 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005868 int *sessionId,
5869 status_t *status)
5870{
5871 sp<RecordThread::RecordTrack> recordTrack;
5872 sp<RecordHandle> recordHandle;
5873 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005874 status_t lStatus;
5875 RecordThread *thread;
5876 size_t inFrameCount;
5877 int lSessionId;
5878
5879 // check calling permissions
5880 if (!recordingAllowed()) {
5881 lStatus = PERMISSION_DENIED;
5882 goto Exit;
5883 }
5884
5885 // add client to list
5886 { // scope for mLock
5887 Mutex::Autolock _l(mLock);
5888 thread = checkRecordThread_l(input);
5889 if (thread == NULL) {
5890 lStatus = BAD_VALUE;
5891 goto Exit;
5892 }
5893
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005894 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005895
5896 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005897 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005898 lSessionId = *sessionId;
5899 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005900 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005901 if (sessionId != NULL) {
5902 *sessionId = lSessionId;
5903 }
5904 }
5905 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07005906 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5907 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005908 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005909 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005910 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5911 // destructor is called by the TrackBase destructor with mLock held
5912 client.clear();
5913 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005914 goto Exit;
5915 }
5916
5917 // return to handle to client
5918 recordHandle = new RecordHandle(recordTrack);
5919 lStatus = NO_ERROR;
5920
5921Exit:
5922 if (status) {
5923 *status = lStatus;
5924 }
5925 return recordHandle;
5926}
5927
5928// ----------------------------------------------------------------------------
5929
5930AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5931 : BnAudioRecord(),
5932 mRecordTrack(recordTrack)
5933{
5934}
5935
5936AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005937 stop_nonvirtual();
Glenn Kasten510a3d62012-07-16 14:24:34 -07005938 mRecordTrack->destroy();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005939}
5940
Glenn Kasten90716c52012-01-26 13:40:12 -08005941sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5942 return mRecordTrack->getCblk();
5943}
5944
Glenn Kasten0ec23ce2012-07-10 12:56:08 -07005945status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005946 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005947 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005948}
5949
5950void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005951 stop_nonvirtual();
5952}
5953
5954void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01005955 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005956 mRecordTrack->stop();
5957}
5958
Mathias Agopian65ab4712010-07-14 17:59:35 -07005959status_t AudioFlinger::RecordHandle::onTransact(
5960 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5961{
5962 return BnAudioRecord::onTransact(code, data, reply, flags);
5963}
5964
5965// ----------------------------------------------------------------------------
5966
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005967AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5968 AudioStreamIn *input,
5969 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07005970 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005971 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07005972 audio_devices_t device) :
Eric Laurentf1c04f92012-08-28 14:26:53 -07005973 ThreadBase(audioFlinger, id, AUDIO_DEVICE_NONE, device, RECORD),
Glenn Kasten510a3d62012-07-16 14:24:34 -07005974 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005975 // mRsmpInIndex and mInputBytes set by readInputParameters()
Glenn Kasten254af182012-07-03 14:59:05 -07005976 mReqChannelCount(popcount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005977 mReqSampleRate(sampleRate)
5978 // mBytesRead is only meaningful while active, and so is cleared in start()
5979 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005980{
Glenn Kasten480b4682012-02-28 12:30:08 -08005981 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005982
Mathias Agopian65ab4712010-07-14 17:59:35 -07005983 readInputParameters();
5984}
5985
5986
5987AudioFlinger::RecordThread::~RecordThread()
5988{
5989 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005990 delete mResampler;
5991 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005992}
5993
5994void AudioFlinger::RecordThread::onFirstRef()
5995{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005996 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005997}
5998
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005999status_t AudioFlinger::RecordThread::readyToRun()
6000{
6001 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00006002 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006003 return status;
6004}
6005
Mathias Agopian65ab4712010-07-14 17:59:35 -07006006bool AudioFlinger::RecordThread::threadLoop()
6007{
6008 AudioBufferProvider::Buffer buffer;
6009 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006010 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006011
Eric Laurent44d98482010-09-30 16:12:31 -07006012 nsecs_t lastWarning = 0;
6013
Glenn Kastene4e2a372012-07-23 12:55:09 -07006014 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07006015 acquireWakeLock();
6016
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07006017 // used to verify we've read at least once before evaluating how many bytes were read
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006018 bool readOnce = false;
6019
Mathias Agopian65ab4712010-07-14 17:59:35 -07006020 // start recording
6021 while (!exitPending()) {
6022
6023 processConfigEvents();
6024
6025 { // scope for mLock
6026 Mutex::Autolock _l(mLock);
6027 checkForNewParameters_l();
6028 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006029 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006030
6031 if (exitPending()) break;
6032
Eric Laurentfeb0db62011-07-22 09:04:31 -07006033 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01006034 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006035 // go to sleep
6036 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006037 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006038 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006039 continue;
6040 }
6041 if (mActiveTrack != 0) {
6042 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006043 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006044 mActiveTrack.clear();
6045 mStartStopCond.broadcast();
6046 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6047 if (mReqChannelCount != mActiveTrack->channelCount()) {
6048 mActiveTrack.clear();
6049 mStartStopCond.broadcast();
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006050 } else if (readOnce) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006051 // record start succeeds only if first read from audio input
6052 // succeeds
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006053 if (mBytesRead >= 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006054 mActiveTrack->mState = TrackBase::ACTIVE;
6055 } else {
6056 mActiveTrack.clear();
6057 }
6058 mStartStopCond.broadcast();
6059 }
6060 mStandby = false;
Glenn Kasten510a3d62012-07-16 14:24:34 -07006061 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
6062 removeTrack_l(mActiveTrack);
6063 mActiveTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006064 }
6065 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006066 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006067 }
6068
6069 if (mActiveTrack != 0) {
6070 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6071 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006072 unlockEffectChains(effectChains);
6073 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074 continue;
6075 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006076 for (size_t i = 0; i < effectChains.size(); i ++) {
6077 effectChains[i]->process_l();
6078 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006079
Mathias Agopian65ab4712010-07-14 17:59:35 -07006080 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006081 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006082 readOnce = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006083 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006084 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006085 // no resampling
6086 while (framesOut) {
6087 size_t framesIn = mFrameCount - mRsmpInIndex;
6088 if (framesIn) {
6089 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6090 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6091 if (framesIn > framesOut)
6092 framesIn = framesOut;
6093 mRsmpInIndex += framesIn;
6094 framesOut -= framesIn;
6095 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006096 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006097 memcpy(dst, src, framesIn * mFrameSize);
6098 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006099 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006100 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6101 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006102 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006103 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6104 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006105 }
6106 }
6107 }
6108 if (framesOut && mFrameCount == mRsmpInIndex) {
6109 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006110 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006111 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006112 framesOut = 0;
6113 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006114 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006115 mRsmpInIndex = 0;
6116 }
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006117 if (mBytesRead <= 0) {
6118 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
6119 {
6120 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006121 // Force input into standby so that it tries to
6122 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006123 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006124 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006125 }
6126 mRsmpInIndex = mFrameCount;
6127 framesOut = 0;
6128 buffer.frameCount = 0;
6129 }
6130 }
6131 }
6132 } else {
6133 // resampling
6134
6135 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6136 // alter output frame count as if we were expecting stereo samples
6137 if (mChannelCount == 1 && mReqChannelCount == 1) {
6138 framesOut >>= 1;
6139 }
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07006140 mResampler->resample(mRsmpOutBuffer, framesOut, this /* AudioBufferProvider* */);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006141 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6142 // are 32 bit aligned which should be always true.
6143 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006144 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006145 // the resampler always outputs stereo samples: do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006146 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6147 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006148 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006149 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006150 }
6151
6152 }
Eric Laurenta011e352012-03-29 15:51:43 -07006153 if (mFramestoDrop == 0) {
6154 mActiveTrack->releaseBuffer(&buffer);
6155 } else {
6156 if (mFramestoDrop > 0) {
6157 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006158 if (mFramestoDrop <= 0) {
6159 clearSyncStartEvent();
6160 }
6161 } else {
6162 mFramestoDrop += buffer.frameCount;
6163 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6164 mSyncStartEvent->isCancelled()) {
6165 ALOGW("Synced record %s, session %d, trigger session %d",
6166 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6167 mActiveTrack->sessionId(),
6168 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6169 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006170 }
6171 }
6172 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006173 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006174 }
6175 // client isn't retrieving buffers fast enough
6176 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006177 if (!mActiveTrack->setOverflow()) {
6178 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006179 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006180 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006181 lastWarning = now;
6182 }
6183 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006184 // Release the processor for a while before asking for a new buffer.
6185 // This will give the application more chance to read from the buffer and
6186 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006187 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006188 }
6189 }
Eric Laurentec437d82011-07-26 20:54:46 -07006190 // enable changes in effect chain
6191 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006192 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006193 }
6194
Glenn Kastene4e2a372012-07-23 12:55:09 -07006195 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006196
Glenn Kasten33e6e352012-07-16 15:56:57 -07006197 {
6198 Mutex::Autolock _l(mLock);
6199 mActiveTrack.clear();
6200 mStartStopCond.broadcast();
6201 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006202
Eric Laurentfeb0db62011-07-22 09:04:31 -07006203 releaseWakeLock();
6204
Steve Block3856b092011-10-20 11:56:00 +01006205 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006206 return false;
6207}
6208
Glenn Kastene4e2a372012-07-23 12:55:09 -07006209void AudioFlinger::RecordThread::standby()
6210{
6211 if (!mStandby) {
6212 inputStandBy();
6213 mStandby = true;
6214 }
6215}
6216
6217void AudioFlinger::RecordThread::inputStandBy()
6218{
6219 mInput->stream->common.standby(&mInput->stream->common);
6220}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006221
6222sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6223 const sp<AudioFlinger::Client>& client,
6224 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006225 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006226 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006227 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006228 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006229 IAudioFlinger::track_flags_t flags,
6230 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006231 status_t *status)
6232{
6233 sp<RecordTrack> track;
6234 status_t lStatus;
6235
6236 lStatus = initCheck();
6237 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006238 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006239 goto Exit;
6240 }
6241
Glenn Kasten1879fff2012-07-11 15:36:59 -07006242 // FIXME use flags and tid similar to createTrack_l()
6243
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006244 { // scope for mLock
6245 Mutex::Autolock _l(mLock);
6246
6247 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006248 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006249
Glenn Kasten7378ca52012-01-20 13:44:40 -08006250 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006251 lStatus = NO_MEMORY;
6252 goto Exit;
6253 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006254 mTracks.add(track);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006255
Eric Laurent59bd0da2011-08-01 09:52:20 -07006256 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1c04f92012-08-28 14:26:53 -07006257 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006258 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006259 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6260 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006261 }
6262 lStatus = NO_ERROR;
6263
6264Exit:
6265 if (status) {
6266 *status = lStatus;
6267 }
6268 return track;
6269}
6270
Eric Laurenta011e352012-03-29 15:51:43 -07006271status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006272 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006273 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006274{
Glenn Kasten58912562012-04-03 10:45:00 -07006275 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006276 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006277 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006278
6279 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006280 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006281 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6282 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6283 triggerSession,
6284 recordTrack->sessionId(),
6285 syncStartEventCallback,
6286 this);
Eric Laurent29864602012-05-08 18:57:51 -07006287 // Sync event can be cancelled by the trigger session if the track is not in a
6288 // compatible state in which case we start record immediately
6289 if (mSyncStartEvent->isCancelled()) {
6290 clearSyncStartEvent();
6291 } else {
6292 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6293 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6294 }
Eric Laurenta011e352012-03-29 15:51:43 -07006295 }
6296
Mathias Agopian65ab4712010-07-14 17:59:35 -07006297 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006298 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006299 if (mActiveTrack != 0) {
6300 if (recordTrack != mActiveTrack.get()) {
6301 status = -EBUSY;
6302 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6303 mActiveTrack->mState = TrackBase::ACTIVE;
6304 }
6305 return status;
6306 }
6307
6308 recordTrack->mState = TrackBase::IDLE;
6309 mActiveTrack = recordTrack;
6310 mLock.unlock();
6311 status_t status = AudioSystem::startInput(mId);
6312 mLock.lock();
6313 if (status != NO_ERROR) {
6314 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006315 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006316 return status;
6317 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006318 mRsmpInIndex = mFrameCount;
6319 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006320 if (mResampler != NULL) {
6321 mResampler->reset();
6322 }
6323 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006324 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006325 ALOGV("Signal record thread");
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07006326 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006327 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006328 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006329 mActiveTrack.clear();
6330 status = INVALID_OPERATION;
6331 goto startError;
6332 }
6333 mStartStopCond.wait(mLock);
6334 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006335 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006336 status = BAD_VALUE;
6337 goto startError;
6338 }
Steve Block3856b092011-10-20 11:56:00 +01006339 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006340 return status;
6341 }
6342startError:
6343 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006344 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006345 return status;
6346}
6347
Eric Laurenta011e352012-03-29 15:51:43 -07006348void AudioFlinger::RecordThread::clearSyncStartEvent()
6349{
6350 if (mSyncStartEvent != 0) {
6351 mSyncStartEvent->cancel();
6352 }
6353 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006354 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006355}
6356
6357void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6358{
6359 sp<SyncEvent> strongEvent = event.promote();
6360
6361 if (strongEvent != 0) {
6362 RecordThread *me = (RecordThread *)strongEvent->cookie();
6363 me->handleSyncStartEvent(strongEvent);
6364 }
6365}
6366
6367void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6368{
Eric Laurent29864602012-05-08 18:57:51 -07006369 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006370 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6371 // from audio HAL
6372 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006373 }
6374}
6375
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006376bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006377 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006378 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
6379 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006380 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006381 recordTrack->mState = TrackBase::PAUSING;
6382 // do not wait for mStartStopCond if exiting
6383 if (exitPending()) {
6384 return true;
6385 }
6386 mStartStopCond.wait(mLock);
6387 // if we have been restarted, recordTrack == mActiveTrack.get() here
6388 if (exitPending() || recordTrack != mActiveTrack.get()) {
6389 ALOGV("Record stopped OK");
6390 return true;
6391 }
6392 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006393}
6394
Glenn Kasten106e8a42012-08-02 13:37:12 -07006395bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07006396{
6397 return false;
6398}
6399
6400status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6401{
Glenn Kasten7aa25592012-08-02 16:37:07 -07006402#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 -07006403 if (!isValidSyncEvent(event)) {
6404 return BAD_VALUE;
6405 }
6406
Glenn Kasten510a3d62012-07-16 14:24:34 -07006407 int eventSession = event->triggerSession();
6408 status_t ret = NAME_NOT_FOUND;
6409
Eric Laurenta011e352012-03-29 15:51:43 -07006410 Mutex::Autolock _l(mLock);
6411
Glenn Kasten510a3d62012-07-16 14:24:34 -07006412 for (size_t i = 0; i < mTracks.size(); i++) {
6413 sp<RecordTrack> track = mTracks[i];
6414 if (eventSession == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07006415 (void) track->setSyncEvent(event);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006416 ret = NO_ERROR;
6417 }
Eric Laurenta011e352012-03-29 15:51:43 -07006418 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006419 return ret;
Glenn Kasten7aa25592012-08-02 16:37:07 -07006420#else
6421 return BAD_VALUE;
6422#endif
Glenn Kasten510a3d62012-07-16 14:24:34 -07006423}
6424
6425void AudioFlinger::RecordThread::RecordTrack::destroy()
6426{
6427 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
6428 sp<RecordTrack> keep(this);
6429 {
6430 sp<ThreadBase> thread = mThread.promote();
6431 if (thread != 0) {
6432 if (mState == ACTIVE || mState == RESUMING) {
6433 AudioSystem::stopInput(thread->id());
6434 }
6435 AudioSystem::releaseInput(thread->id());
6436 Mutex::Autolock _l(thread->mLock);
6437 RecordThread *recordThread = (RecordThread *) thread.get();
6438 recordThread->destroyTrack_l(this);
6439 }
6440 }
6441}
6442
6443// destroyTrack_l() must be called with ThreadBase::mLock held
6444void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6445{
6446 track->mState = TrackBase::TERMINATED;
6447 // active tracks are removed by threadLoop()
6448 if (mActiveTrack != track) {
6449 removeTrack_l(track);
6450 }
6451}
6452
6453void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6454{
6455 mTracks.remove(track);
6456 // need anything related to effects here?
Eric Laurenta011e352012-03-29 15:51:43 -07006457}
6458
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07006459void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006460{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006461 dumpInternals(fd, args);
6462 dumpTracks(fd, args);
6463 dumpEffectChains(fd, args);
6464}
6465
6466void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6467{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006468 const size_t SIZE = 256;
6469 char buffer[SIZE];
6470 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006471
6472 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6473 result.append(buffer);
6474
6475 if (mActiveTrack != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006476 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6477 result.append(buffer);
6478 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6479 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006480 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006481 result.append(buffer);
6482 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6483 result.append(buffer);
6484 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6485 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006486 } else {
Glenn Kasten510a3d62012-07-16 14:24:34 -07006487 result.append("No active record client\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006488 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006489
Mathias Agopian65ab4712010-07-14 17:59:35 -07006490 write(fd, result.string(), result.size());
6491
6492 dumpBase(fd, args);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006493}
6494
6495void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
6496{
6497 const size_t SIZE = 256;
6498 char buffer[SIZE];
6499 String8 result;
6500
6501 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
6502 result.append(buffer);
6503 RecordTrack::appendDumpHeader(result);
6504 for (size_t i = 0; i < mTracks.size(); ++i) {
6505 sp<RecordTrack> track = mTracks[i];
6506 if (track != 0) {
6507 track->dump(buffer, SIZE);
6508 result.append(buffer);
6509 }
6510 }
6511
6512 if (mActiveTrack != 0) {
6513 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
6514 result.append(buffer);
6515 RecordTrack::appendDumpHeader(result);
6516 mActiveTrack->dump(buffer, SIZE);
6517 result.append(buffer);
6518
6519 }
6520 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006521}
6522
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006523// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006524status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006525{
6526 size_t framesReq = buffer->frameCount;
6527 size_t framesReady = mFrameCount - mRsmpInIndex;
6528 int channelCount;
6529
6530 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006531 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07006532 if (mBytesRead <= 0) {
6533 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
6534 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006535 // Force input into standby so that it tries to
6536 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006537 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006538 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006539 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006540 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006541 buffer->frameCount = 0;
6542 return NOT_ENOUGH_DATA;
6543 }
6544 mRsmpInIndex = 0;
6545 framesReady = mFrameCount;
6546 }
6547
6548 if (framesReq > framesReady) {
6549 framesReq = framesReady;
6550 }
6551
6552 if (mChannelCount == 1 && mReqChannelCount == 2) {
6553 channelCount = 1;
6554 } else {
6555 channelCount = 2;
6556 }
6557 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6558 buffer->frameCount = framesReq;
6559 return NO_ERROR;
6560}
6561
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006562// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006563void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6564{
6565 mRsmpInIndex += buffer->frameCount;
6566 buffer->frameCount = 0;
6567}
6568
6569bool AudioFlinger::RecordThread::checkForNewParameters_l()
6570{
6571 bool reconfig = false;
6572
6573 while (!mNewParameters.isEmpty()) {
6574 status_t status = NO_ERROR;
6575 String8 keyValuePair = mNewParameters[0];
6576 AudioParameter param = AudioParameter(keyValuePair);
6577 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006578 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006579 int reqSamplingRate = mReqSampleRate;
6580 int reqChannelCount = mReqChannelCount;
6581
6582 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6583 reqSamplingRate = value;
6584 reconfig = true;
6585 }
6586 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006587 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006588 reconfig = true;
6589 }
6590 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006591 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006592 reconfig = true;
6593 }
6594 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6595 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006596 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006597 // if frame count is changed after track creation
6598 if (mActiveTrack != 0) {
6599 status = INVALID_OPERATION;
6600 } else {
6601 reconfig = true;
6602 }
6603 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006604 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6605 // forward device change to effects that have requested to be
6606 // aware of attached audio device.
6607 for (size_t i = 0; i < mEffectChains.size(); i++) {
6608 mEffectChains[i]->setDevice_l(value);
6609 }
Eric Laurentf1c04f92012-08-28 14:26:53 -07006610
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006611 // store input device and output device but do not forward output device to audio HAL.
6612 // Note that status is ignored by the caller for output device
6613 // (see AudioFlinger::setParameters()
Eric Laurentf1c04f92012-08-28 14:26:53 -07006614 if (audio_is_output_devices(value)) {
6615 mOutDevice = value;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006616 status = BAD_VALUE;
6617 } else {
Eric Laurentf1c04f92012-08-28 14:26:53 -07006618 mInDevice = value;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006619 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kasten510a3d62012-07-16 14:24:34 -07006620 if (mTracks.size() > 0) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07006621 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6622 mAudioFlinger->btNrecIsOff();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006623 for (size_t i = 0; i < mTracks.size(); i++) {
6624 sp<RecordTrack> track = mTracks[i];
6625 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6626 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6627 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07006628 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006629 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006630 }
Eric Laurent57b2dd12012-08-31 17:44:06 -07006631 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6632 mAudioSource != (audio_source_t)value) {
6633 // forward device change to effects that have requested to be
6634 // aware of attached audio device.
6635 for (size_t i = 0; i < mEffectChains.size(); i++) {
6636 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
6637 }
6638 mAudioSource = (audio_source_t)value;
6639 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006640 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006641 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006642 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006643 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006644 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6645 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006646 }
6647 if (reconfig) {
6648 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006649 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006650 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006651 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006652 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6653 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006654 status = NO_ERROR;
6655 }
6656 if (status == NO_ERROR) {
6657 readInputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07006658 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006659 }
6660 }
6661 }
6662
6663 mNewParameters.removeAt(0);
6664
6665 mParamStatus = status;
6666 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006667 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6668 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006669 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006670 }
6671 return reconfig;
6672}
6673
6674String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6675{
Dima Zavinfce7a472011-04-19 22:30:36 -07006676 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006677 String8 out_s8 = String8();
6678
6679 Mutex::Autolock _l(mLock);
6680 if (initCheck() != NO_ERROR) {
6681 return out_s8;
6682 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006683
Dima Zavin799a70e2011-04-18 16:57:27 -07006684 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006685 out_s8 = String8(s);
6686 free(s);
6687 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006688}
6689
6690void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6691 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006692 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006693
6694 switch (event) {
6695 case AudioSystem::INPUT_OPENED:
6696 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006697 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006698 desc.samplingRate = mSampleRate;
6699 desc.format = mFormat;
6700 desc.frameCount = mFrameCount;
6701 desc.latency = 0;
6702 param2 = &desc;
6703 break;
6704
6705 case AudioSystem::INPUT_CLOSED:
6706 default:
6707 break;
6708 }
6709 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6710}
6711
6712void AudioFlinger::RecordThread::readInputParameters()
6713{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006714 delete mRsmpInBuffer;
6715 // mRsmpInBuffer is always assigned a new[] below
6716 delete mRsmpOutBuffer;
6717 mRsmpOutBuffer = NULL;
6718 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006719 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006720
Dima Zavin799a70e2011-04-18 16:57:27 -07006721 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006722 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6723 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006724 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006725 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006726 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006727 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006728 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006729 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6730
Glenn Kasten53d76db2012-03-08 12:32:47 -08006731 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006732 {
6733 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006734 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6735 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006736 if (mChannelCount == 1 && mReqChannelCount == 2) {
6737 channelCount = 1;
6738 } else {
6739 channelCount = 2;
6740 }
6741 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6742 mResampler->setSampleRate(mSampleRate);
6743 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6744 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6745
6746 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6747 if (mChannelCount == 1 && mReqChannelCount == 1) {
6748 mFrameCount >>= 1;
6749 }
6750
6751 }
6752 mRsmpInIndex = mFrameCount;
6753}
6754
6755unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6756{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006757 Mutex::Autolock _l(mLock);
6758 if (initCheck() != NO_ERROR) {
6759 return 0;
6760 }
6761
Dima Zavin799a70e2011-04-18 16:57:27 -07006762 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006763}
6764
Glenn Kasten106e8a42012-08-02 13:37:12 -07006765uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006766{
6767 Mutex::Autolock _l(mLock);
6768 uint32_t result = 0;
6769 if (getEffectChain_l(sessionId) != 0) {
6770 result = EFFECT_SESSION;
6771 }
6772
Glenn Kasten510a3d62012-07-16 14:24:34 -07006773 for (size_t i = 0; i < mTracks.size(); ++i) {
6774 if (sessionId == mTracks[i]->sessionId()) {
6775 result |= TRACK_SESSION;
6776 break;
6777 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006778 }
6779
6780 return result;
6781}
6782
Glenn Kasten106e8a42012-08-02 13:37:12 -07006783KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent59bd0da2011-08-01 09:52:20 -07006784{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006785 KeyedVector<int, bool> ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006786 Mutex::Autolock _l(mLock);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006787 for (size_t j = 0; j < mTracks.size(); ++j) {
6788 sp<RecordThread::RecordTrack> track = mTracks[j];
6789 int sessionId = track->sessionId();
6790 if (ids.indexOfKey(sessionId) < 0) {
6791 ids.add(sessionId, true);
6792 }
6793 }
6794 return ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006795}
6796
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006797AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6798{
6799 Mutex::Autolock _l(mLock);
6800 AudioStreamIn *input = mInput;
6801 mInput = NULL;
6802 return input;
6803}
6804
6805// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006806audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006807{
6808 if (mInput == NULL) {
6809 return NULL;
6810 }
6811 return &mInput->stream->common;
6812}
6813
6814
Mathias Agopian65ab4712010-07-14 17:59:35 -07006815// ----------------------------------------------------------------------------
6816
Eric Laurenta4c5a552012-03-29 10:12:40 -07006817audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6818{
6819 if (!settingsAllowed()) {
6820 return 0;
6821 }
6822 Mutex::Autolock _l(mLock);
6823 return loadHwModule_l(name);
6824}
6825
6826// loadHwModule_l() must be called with AudioFlinger::mLock held
6827audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6828{
6829 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6830 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6831 ALOGW("loadHwModule() module %s already loaded", name);
6832 return mAudioHwDevs.keyAt(i);
6833 }
6834 }
6835
Eric Laurenta4c5a552012-03-29 10:12:40 -07006836 audio_hw_device_t *dev;
6837
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006838 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006839 if (rc) {
6840 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6841 return 0;
6842 }
6843
6844 mHardwareStatus = AUDIO_HW_INIT;
6845 rc = dev->init_check(dev);
6846 mHardwareStatus = AUDIO_HW_IDLE;
6847 if (rc) {
6848 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6849 return 0;
6850 }
6851
John Grossmanee578c02012-07-23 17:05:46 -07006852 // Check and cache this HAL's level of support for master mute and master
6853 // volume. If this is the first HAL opened, and it supports the get
6854 // methods, use the initial values provided by the HAL as the current
6855 // master mute and volume settings.
6856
6857 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
6858 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07006859 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07006860
6861 if (0 == mAudioHwDevs.size()) {
6862 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6863 if (NULL != dev->get_master_volume) {
6864 float mv;
6865 if (OK == dev->get_master_volume(dev, &mv)) {
6866 mMasterVolume = mv;
6867 }
6868 }
6869
6870 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
6871 if (NULL != dev->get_master_mute) {
6872 bool mm;
6873 if (OK == dev->get_master_mute(dev, &mm)) {
6874 mMasterMute = mm;
6875 }
6876 }
6877 }
6878
Eric Laurenta4c5a552012-03-29 10:12:40 -07006879 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07006880 if ((NULL != dev->set_master_volume) &&
6881 (OK == dev->set_master_volume(dev, mMasterVolume))) {
6882 flags = static_cast<AudioHwDevice::Flags>(flags |
6883 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
6884 }
6885
6886 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
6887 if ((NULL != dev->set_master_mute) &&
6888 (OK == dev->set_master_mute(dev, mMasterMute))) {
6889 flags = static_cast<AudioHwDevice::Flags>(flags |
6890 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
6891 }
6892
Eric Laurenta4c5a552012-03-29 10:12:40 -07006893 mHardwareStatus = AUDIO_HW_IDLE;
6894 }
6895
6896 audio_module_handle_t handle = nextUniqueId();
John Grossmanee578c02012-07-23 17:05:46 -07006897 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07006898
6899 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006900 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006901
6902 return handle;
6903
6904}
6905
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07006906// ----------------------------------------------------------------------------
6907
6908int32_t AudioFlinger::getPrimaryOutputSamplingRate()
6909{
6910 Mutex::Autolock _l(mLock);
6911 PlaybackThread *thread = primaryPlaybackThread_l();
6912 return thread != NULL ? thread->sampleRate() : 0;
6913}
6914
6915int32_t AudioFlinger::getPrimaryOutputFrameCount()
6916{
6917 Mutex::Autolock _l(mLock);
6918 PlaybackThread *thread = primaryPlaybackThread_l();
6919 return thread != NULL ? thread->frameCountHAL() : 0;
6920}
6921
6922// ----------------------------------------------------------------------------
6923
Eric Laurenta4c5a552012-03-29 10:12:40 -07006924audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6925 audio_devices_t *pDevices,
6926 uint32_t *pSamplingRate,
6927 audio_format_t *pFormat,
6928 audio_channel_mask_t *pChannelMask,
6929 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006930 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006931{
6932 status_t status;
6933 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006934 struct audio_config config = {
6935 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6936 channel_mask: pChannelMask ? *pChannelMask : 0,
6937 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6938 };
6939 audio_stream_out_t *outStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07006940 AudioHwDevice *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006941
Eric Laurenta4c5a552012-03-29 10:12:40 -07006942 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6943 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006944 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006945 config.sample_rate,
6946 config.format,
6947 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006948 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006949
6950 if (pDevices == NULL || *pDevices == 0) {
6951 return 0;
6952 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006953
Mathias Agopian65ab4712010-07-14 17:59:35 -07006954 Mutex::Autolock _l(mLock);
6955
Eric Laurenta4c5a552012-03-29 10:12:40 -07006956 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006957 if (outHwDev == NULL)
6958 return 0;
6959
John Grossmanee578c02012-07-23 17:05:46 -07006960 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006961 audio_io_handle_t id = nextUniqueId();
6962
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006963 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006964
John Grossmanee578c02012-07-23 17:05:46 -07006965 status = hwDevHal->open_output_stream(hwDevHal,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006966 id,
6967 *pDevices,
6968 (audio_output_flags_t)flags,
6969 &config,
6970 &outStream);
6971
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006972 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006973 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006974 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006975 config.sample_rate,
6976 config.format,
6977 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006978 status);
6979
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006980 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006981 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006982
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006983 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006984 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6985 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006986 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006987 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006988 } else {
6989 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006990 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006991 }
6992 mPlaybackThreads.add(id, thread);
6993
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006994 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6995 if (pFormat != NULL) *pFormat = config.format;
6996 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006997 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006998
6999 // notify client processes of the new output creation
7000 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007001
7002 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007003 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07007004 ALOGI("Using module %d has the primary audio interface", module);
7005 mPrimaryHardwareDev = outHwDev;
7006
7007 AutoMutex lock(mHardwareLock);
7008 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -07007009 hwDevHal->set_mode(hwDevHal, mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007010 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007011 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007012 return id;
7013 }
7014
7015 return 0;
7016}
7017
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007018audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
7019 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007020{
7021 Mutex::Autolock _l(mLock);
7022 MixerThread *thread1 = checkMixerThread_l(output1);
7023 MixerThread *thread2 = checkMixerThread_l(output2);
7024
7025 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007026 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007027 return 0;
7028 }
7029
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007030 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007031 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
7032 thread->addOutputTrack(thread2);
7033 mPlaybackThreads.add(id, thread);
7034 // notify client processes of the new output creation
7035 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7036 return id;
7037}
7038
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007039status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007040{
Glenn Kastend96c5722012-04-25 13:44:49 -07007041 return closeOutput_nonvirtual(output);
7042}
7043
7044status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
7045{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007046 // keep strong reference on the playback thread so that
7047 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007048 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007049 {
7050 Mutex::Autolock _l(mLock);
7051 thread = checkPlaybackThread_l(output);
7052 if (thread == NULL) {
7053 return BAD_VALUE;
7054 }
7055
Steve Block3856b092011-10-20 11:56:00 +01007056 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007057
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007058 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007059 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007060 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007061 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
7062 dupThread->removeOutputTrack((MixerThread *)thread.get());
7063 }
7064 }
7065 }
Glenn Kastena1117922012-01-26 10:53:32 -08007066 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007067 mPlaybackThreads.removeItem(output);
7068 }
7069 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007070 // The thread entity (active unit of execution) is no longer running here,
7071 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007072
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007073 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007074 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007075 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007076 // from now on thread->mOutput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007077 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007078 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007079 }
7080 return NO_ERROR;
7081}
7082
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007083status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007084{
7085 Mutex::Autolock _l(mLock);
7086 PlaybackThread *thread = checkPlaybackThread_l(output);
7087
7088 if (thread == NULL) {
7089 return BAD_VALUE;
7090 }
7091
Steve Block3856b092011-10-20 11:56:00 +01007092 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007093 thread->suspend();
7094
7095 return NO_ERROR;
7096}
7097
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007098status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007099{
7100 Mutex::Autolock _l(mLock);
7101 PlaybackThread *thread = checkPlaybackThread_l(output);
7102
7103 if (thread == NULL) {
7104 return BAD_VALUE;
7105 }
7106
Steve Block3856b092011-10-20 11:56:00 +01007107 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007108
7109 thread->restore();
7110
7111 return NO_ERROR;
7112}
7113
Eric Laurenta4c5a552012-03-29 10:12:40 -07007114audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
7115 audio_devices_t *pDevices,
7116 uint32_t *pSamplingRate,
7117 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07007118 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007119{
7120 status_t status;
7121 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007122 struct audio_config config = {
7123 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7124 channel_mask: pChannelMask ? *pChannelMask : 0,
7125 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7126 };
7127 uint32_t reqSamplingRate = config.sample_rate;
7128 audio_format_t reqFormat = config.format;
7129 audio_channel_mask_t reqChannels = config.channel_mask;
7130 audio_stream_in_t *inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007131 AudioHwDevice *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007132
7133 if (pDevices == NULL || *pDevices == 0) {
7134 return 0;
7135 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007136
Mathias Agopian65ab4712010-07-14 17:59:35 -07007137 Mutex::Autolock _l(mLock);
7138
Eric Laurenta4c5a552012-03-29 10:12:40 -07007139 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007140 if (inHwDev == NULL)
7141 return 0;
7142
John Grossmanee578c02012-07-23 17:05:46 -07007143 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007144 audio_io_handle_t id = nextUniqueId();
7145
John Grossmanee578c02012-07-23 17:05:46 -07007146 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007147 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007148 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007149 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007150 config.sample_rate,
7151 config.format,
7152 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007153 status);
7154
7155 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7156 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7157 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007158 if (status == BAD_VALUE &&
7159 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7160 (config.sample_rate <= 2 * reqSamplingRate) &&
7161 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007162 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007163 inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007164 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007165 }
7166
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007167 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007168 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7169
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007170 // Start record thread
7171 // RecorThread require both input and output device indication to forward to audio
7172 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007173 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007174 thread = new RecordThread(this,
7175 input,
7176 reqSamplingRate,
7177 reqChannels,
7178 id,
7179 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007180 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007181 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007182 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007183 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007184 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007185
Mathias Agopian65ab4712010-07-14 17:59:35 -07007186 // notify client processes of the new input creation
7187 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7188 return id;
7189 }
7190
7191 return 0;
7192}
7193
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007194status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007195{
Glenn Kastend96c5722012-04-25 13:44:49 -07007196 return closeInput_nonvirtual(input);
7197}
7198
7199status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7200{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007201 // keep strong reference on the record thread so that
7202 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007203 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007204 {
7205 Mutex::Autolock _l(mLock);
7206 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007207 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007208 return BAD_VALUE;
7209 }
7210
Steve Block3856b092011-10-20 11:56:00 +01007211 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007212 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007213 mRecordThreads.removeItem(input);
7214 }
7215 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007216 // The thread entity (active unit of execution) is no longer running here,
7217 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007218
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007219 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007220 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007221 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007222 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007223 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007224
7225 return NO_ERROR;
7226}
7227
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007228status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007229{
7230 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007231 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007232
7233 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7234 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007235 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007236 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007237
7238 return NO_ERROR;
7239}
7240
7241
7242int AudioFlinger::newAudioSessionId()
7243{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007244 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007245}
7246
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007247void AudioFlinger::acquireAudioSessionId(int audioSession)
7248{
7249 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007250 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007251 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007252 size_t num = mAudioSessionRefs.size();
7253 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007254 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007255 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7256 ref->mCnt++;
7257 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007258 return;
7259 }
7260 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007261 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7262 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007263}
7264
7265void AudioFlinger::releaseAudioSessionId(int audioSession)
7266{
7267 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007268 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007269 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007270 size_t num = mAudioSessionRefs.size();
7271 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007272 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007273 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7274 ref->mCnt--;
7275 ALOGV(" decremented refcount to %d", ref->mCnt);
7276 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007277 mAudioSessionRefs.removeAt(i);
7278 delete ref;
7279 purgeStaleEffects_l();
7280 }
7281 return;
7282 }
7283 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007284 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007285}
7286
7287void AudioFlinger::purgeStaleEffects_l() {
7288
Steve Block3856b092011-10-20 11:56:00 +01007289 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007290
7291 Vector< sp<EffectChain> > chains;
7292
7293 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7294 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7295 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7296 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007297 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7298 chains.push(ec);
7299 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007300 }
7301 }
7302 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7303 sp<RecordThread> t = mRecordThreads.valueAt(i);
7304 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7305 sp<EffectChain> ec = t->mEffectChains[j];
7306 chains.push(ec);
7307 }
7308 }
7309
7310 for (size_t i = 0; i < chains.size(); i++) {
7311 sp<EffectChain> ec = chains[i];
7312 int sessionid = ec->sessionId();
7313 sp<ThreadBase> t = ec->mThread.promote();
7314 if (t == 0) {
7315 continue;
7316 }
7317 size_t numsessionrefs = mAudioSessionRefs.size();
7318 bool found = false;
7319 for (size_t k = 0; k < numsessionrefs; k++) {
7320 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007321 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007322 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007323 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007324 found = true;
7325 break;
7326 }
7327 }
7328 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007329 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007330 // remove all effects from the chain
7331 while (ec->mEffects.size()) {
7332 sp<EffectModule> effect = ec->mEffects[0];
7333 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007334 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007335 if (effect->purgeHandles()) {
7336 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007337 }
7338 AudioSystem::unregisterEffect(effect->id());
7339 }
7340 }
7341 }
7342 return;
7343}
7344
Mathias Agopian65ab4712010-07-14 17:59:35 -07007345// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007346AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007347{
Glenn Kastena1117922012-01-26 10:53:32 -08007348 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007349}
7350
7351// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007352AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007353{
7354 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007355 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007356}
7357
7358// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007359AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007360{
Glenn Kastena1117922012-01-26 10:53:32 -08007361 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007362}
7363
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007364uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007365{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007366 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007367}
7368
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007369AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007370{
7371 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7372 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007373 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07007374 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007375 return thread;
7376 }
7377 }
7378 return NULL;
7379}
7380
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007381audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007382{
7383 PlaybackThread *thread = primaryPlaybackThread_l();
7384
7385 if (thread == NULL) {
7386 return 0;
7387 }
7388
Eric Laurentf1c04f92012-08-28 14:26:53 -07007389 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007390}
7391
Eric Laurenta011e352012-03-29 15:51:43 -07007392sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7393 int triggerSession,
7394 int listenerSession,
7395 sync_event_callback_t callBack,
7396 void *cookie)
7397{
7398 Mutex::Autolock _l(mLock);
7399
7400 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7401 status_t playStatus = NAME_NOT_FOUND;
7402 status_t recStatus = NAME_NOT_FOUND;
7403 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7404 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7405 if (playStatus == NO_ERROR) {
7406 return event;
7407 }
7408 }
7409 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7410 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7411 if (recStatus == NO_ERROR) {
7412 return event;
7413 }
7414 }
7415 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7416 mPendingSyncEvents.add(event);
7417 } else {
7418 ALOGV("createSyncEvent() invalid event %d", event->type());
7419 event.clear();
7420 }
7421 return event;
7422}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007423
Mathias Agopian65ab4712010-07-14 17:59:35 -07007424// ----------------------------------------------------------------------------
7425// Effect management
7426// ----------------------------------------------------------------------------
7427
7428
Glenn Kastenf587ba52012-01-26 16:25:10 -08007429status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007430{
7431 Mutex::Autolock _l(mLock);
7432 return EffectQueryNumberEffects(numEffects);
7433}
7434
Glenn Kastenf587ba52012-01-26 16:25:10 -08007435status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007436{
7437 Mutex::Autolock _l(mLock);
7438 return EffectQueryEffect(index, descriptor);
7439}
7440
Glenn Kasten5e92a782012-01-30 07:40:52 -08007441status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007442 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007443{
7444 Mutex::Autolock _l(mLock);
7445 return EffectGetDescriptor(pUuid, descriptor);
7446}
7447
7448
Mathias Agopian65ab4712010-07-14 17:59:35 -07007449sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7450 effect_descriptor_t *pDesc,
7451 const sp<IEffectClient>& effectClient,
7452 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007453 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007454 int sessionId,
7455 status_t *status,
7456 int *id,
7457 int *enabled)
7458{
7459 status_t lStatus = NO_ERROR;
7460 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007461 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007462
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007463 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007464 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007465
7466 if (pDesc == NULL) {
7467 lStatus = BAD_VALUE;
7468 goto Exit;
7469 }
7470
Eric Laurent84e9a102010-09-23 16:10:16 -07007471 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007472 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007473 lStatus = PERMISSION_DENIED;
7474 goto Exit;
7475 }
7476
Dima Zavinfce7a472011-04-19 22:30:36 -07007477 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007478 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007479 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007480 lStatus = PERMISSION_DENIED;
7481 goto Exit;
7482 }
7483
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007484 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007485 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007486 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007487 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007488 lStatus = BAD_VALUE;
7489 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007490 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007491 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007492 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007493 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007494 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007495 }
7496 }
7497
Mathias Agopian65ab4712010-07-14 17:59:35 -07007498 {
7499 Mutex::Autolock _l(mLock);
7500
Mathias Agopian65ab4712010-07-14 17:59:35 -07007501
7502 if (!EffectIsNullUuid(&pDesc->uuid)) {
7503 // if uuid is specified, request effect descriptor
7504 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7505 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007506 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007507 goto Exit;
7508 }
7509 } else {
7510 // if uuid is not specified, look for an available implementation
7511 // of the required type in effect factory
7512 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007513 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007514 lStatus = BAD_VALUE;
7515 goto Exit;
7516 }
7517 uint32_t numEffects = 0;
7518 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007519 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007520 bool found = false;
7521
7522 lStatus = EffectQueryNumberEffects(&numEffects);
7523 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007524 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007525 goto Exit;
7526 }
7527 for (uint32_t i = 0; i < numEffects; i++) {
7528 lStatus = EffectQueryEffect(i, &desc);
7529 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007530 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007531 continue;
7532 }
7533 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7534 // If matching type found save effect descriptor. If the session is
7535 // 0 and the effect is not auxiliary, continue enumeration in case
7536 // an auxiliary version of this effect type is available
7537 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08007538 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07007539 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007540 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7541 break;
7542 }
7543 }
7544 }
7545 if (!found) {
7546 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007547 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007548 goto Exit;
7549 }
7550 // For same effect type, chose auxiliary version over insert version if
7551 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007552 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007553 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08007554 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007555 }
7556 }
7557
7558 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007559 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007560 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7561 lStatus = INVALID_OPERATION;
7562 goto Exit;
7563 }
7564
Eric Laurent59255e42011-07-27 19:49:51 -07007565 // check recording permission for visualizer
7566 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7567 !recordingAllowed()) {
7568 lStatus = PERMISSION_DENIED;
7569 goto Exit;
7570 }
7571
Mathias Agopian65ab4712010-07-14 17:59:35 -07007572 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08007573 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007574
7575 // If output is not specified try to find a matching audio session ID in one of the
7576 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007577 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7578 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007579 // Note: io is never 0 when creating an effect on an input
7580 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007581 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007582 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7583 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007584 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007585 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007586 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007587 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007588 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007589 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7590 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7591 io = mRecordThreads.keyAt(i);
7592 break;
7593 }
7594 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007595 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007596 // If no output thread contains the requested session ID, default to
7597 // first output. The effect chain will be moved to the correct output
7598 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007599 if (io == 0 && mPlaybackThreads.size()) {
7600 io = mPlaybackThreads.keyAt(0);
7601 }
Steve Block3856b092011-10-20 11:56:00 +01007602 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007603 }
7604 ThreadBase *thread = checkRecordThread_l(io);
7605 if (thread == NULL) {
7606 thread = checkPlaybackThread_l(io);
7607 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007608 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007609 lStatus = BAD_VALUE;
7610 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007611 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007612 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007613
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007614 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007615
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007616 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007617 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7618 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007619 if (handle != 0 && id != NULL) {
7620 *id = handle->id();
7621 }
7622 }
7623
7624Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007625 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007626 *status = lStatus;
7627 }
7628 return handle;
7629}
7630
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007631status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7632 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007633{
Steve Block3856b092011-10-20 11:56:00 +01007634 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007635 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007636 Mutex::Autolock _l(mLock);
7637 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007638 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007639 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007640 }
Eric Laurentde070132010-07-13 04:45:46 -07007641 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7642 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007643 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007644 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007645 }
Eric Laurentde070132010-07-13 04:45:46 -07007646 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7647 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007648 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007649 return BAD_VALUE;
7650 }
7651
7652 Mutex::Autolock _dl(dstThread->mLock);
7653 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007654 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007655
Mathias Agopian65ab4712010-07-14 17:59:35 -07007656 return NO_ERROR;
7657}
7658
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007659// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007660status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007661 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007662 AudioFlinger::PlaybackThread *dstThread,
7663 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007664{
Steve Block3856b092011-10-20 11:56:00 +01007665 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007666 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007667
Eric Laurent59255e42011-07-27 19:49:51 -07007668 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007669 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007670 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007671 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007672 return INVALID_OPERATION;
7673 }
7674
Eric Laurent39e94f82010-07-28 01:32:47 -07007675 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007676 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007677 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007678 // removed.
7679 srcThread->removeEffectChain_l(chain);
7680
7681 // transfer all effects one by one so that new effect chain is created on new thread with
7682 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007683 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007684 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007685 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007686 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7687 while (effect != 0) {
7688 srcThread->removeEffect_l(effect);
7689 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007690 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7691 if (effect->state() == EffectModule::ACTIVE ||
7692 effect->state() == EffectModule::STOPPING) {
7693 effect->start();
7694 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007695 // if the move request is not received from audio policy manager, the effect must be
7696 // re-registered with the new strategy and output
7697 if (dstChain == 0) {
7698 dstChain = effect->chain().promote();
7699 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007700 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007701 srcThread->addEffect_l(effect);
7702 return NO_INIT;
7703 }
7704 strategy = dstChain->strategy();
7705 }
7706 if (reRegister) {
7707 AudioSystem::unregisterEffect(effect->id());
7708 AudioSystem::registerEffect(&effect->desc(),
7709 dstOutput,
7710 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007711 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007712 effect->id());
7713 }
Eric Laurentde070132010-07-13 04:45:46 -07007714 effect = chain->getEffectFromId_l(0);
7715 }
7716
7717 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007718}
7719
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007720
Mathias Agopian65ab4712010-07-14 17:59:35 -07007721// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007722sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007723 const sp<AudioFlinger::Client>& client,
7724 const sp<IEffectClient>& effectClient,
7725 int32_t priority,
7726 int sessionId,
7727 effect_descriptor_t *desc,
7728 int *enabled,
7729 status_t *status
7730 )
7731{
7732 sp<EffectModule> effect;
7733 sp<EffectHandle> handle;
7734 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007735 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007736 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007737 bool effectCreated = false;
7738 bool effectRegistered = false;
7739
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007740 lStatus = initCheck();
7741 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007742 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007743 goto Exit;
7744 }
7745
7746 // Do not allow effects with session ID 0 on direct output or duplicating threads
7747 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007748 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007749 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007750 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007751 lStatus = BAD_VALUE;
7752 goto Exit;
7753 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007754 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007755 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007756 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007757 desc->name, desc->flags, mType);
7758 lStatus = BAD_VALUE;
7759 goto Exit;
7760 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007761
Steve Block3856b092011-10-20 11:56:00 +01007762 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007763
7764 { // scope for mLock
7765 Mutex::Autolock _l(mLock);
7766
7767 // check for existing effect chain with the requested audio session
7768 chain = getEffectChain_l(sessionId);
7769 if (chain == 0) {
7770 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007771 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007772 chain = new EffectChain(this, sessionId);
7773 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007774 chain->setStrategy(getStrategyForSession_l(sessionId));
7775 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007776 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007777 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007778 }
7779
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007780 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007781
7782 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007783 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007784 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007785 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007786 if (lStatus != NO_ERROR) {
7787 goto Exit;
7788 }
7789 effectRegistered = true;
7790 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007791 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007792 lStatus = effect->status();
7793 if (lStatus != NO_ERROR) {
7794 goto Exit;
7795 }
Eric Laurentcab11242010-07-15 12:50:15 -07007796 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007797 if (lStatus != NO_ERROR) {
7798 goto Exit;
7799 }
7800 effectCreated = true;
7801
Eric Laurentf1c04f92012-08-28 14:26:53 -07007802 effect->setDevice(mOutDevice);
7803 effect->setDevice(mInDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007804 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07007805 effect->setAudioSource(mAudioSource);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007806 }
7807 // create effect handle and connect it to effect module
7808 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007809 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007810 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007811 *enabled = (int)effect->isEnabled();
7812 }
7813 }
7814
7815Exit:
7816 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007817 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007818 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007819 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007820 }
7821 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007822 AudioSystem::unregisterEffect(effect->id());
7823 }
7824 if (chainCreated) {
7825 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007826 }
7827 handle.clear();
7828 }
7829
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007830 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007831 *status = lStatus;
7832 }
7833 return handle;
7834}
7835
Eric Laurent717e1282012-06-29 16:36:52 -07007836sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7837{
7838 Mutex::Autolock _l(mLock);
7839 return getEffect_l(sessionId, effectId);
7840}
7841
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007842sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7843{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007844 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007845 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007846}
7847
Eric Laurentde070132010-07-13 04:45:46 -07007848// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7849// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007850status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007851{
7852 // check for existing effect chain with the requested audio session
7853 int sessionId = effect->sessionId();
7854 sp<EffectChain> chain = getEffectChain_l(sessionId);
7855 bool chainCreated = false;
7856
7857 if (chain == 0) {
7858 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007859 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007860 chain = new EffectChain(this, sessionId);
7861 addEffectChain_l(chain);
7862 chain->setStrategy(getStrategyForSession_l(sessionId));
7863 chainCreated = true;
7864 }
Steve Block3856b092011-10-20 11:56:00 +01007865 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007866
7867 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007868 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007869 this, effect->desc().name, chain.get());
7870 return BAD_VALUE;
7871 }
7872
7873 status_t status = chain->addEffect_l(effect);
7874 if (status != NO_ERROR) {
7875 if (chainCreated) {
7876 removeEffectChain_l(chain);
7877 }
7878 return status;
7879 }
7880
Eric Laurentf1c04f92012-08-28 14:26:53 -07007881 effect->setDevice(mOutDevice);
7882 effect->setDevice(mInDevice);
Eric Laurentde070132010-07-13 04:45:46 -07007883 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07007884 effect->setAudioSource(mAudioSource);
Eric Laurentde070132010-07-13 04:45:46 -07007885 return NO_ERROR;
7886}
7887
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007888void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007889
Steve Block3856b092011-10-20 11:56:00 +01007890 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007891 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007892 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7893 detachAuxEffect_l(effect->id());
7894 }
7895
7896 sp<EffectChain> chain = effect->chain().promote();
7897 if (chain != 0) {
7898 // remove effect chain if removing last effect
7899 if (chain->removeEffect_l(effect) == 0) {
7900 removeEffectChain_l(chain);
7901 }
7902 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007903 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007904 }
7905}
7906
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007907void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007908 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007909{
7910 effectChains = mEffectChains;
7911 for (size_t i = 0; i < mEffectChains.size(); i++) {
7912 mEffectChains[i]->lock();
7913 }
7914}
7915
7916void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007917 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007918{
7919 for (size_t i = 0; i < effectChains.size(); i++) {
7920 effectChains[i]->unlock();
7921 }
7922}
7923
7924sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7925{
7926 Mutex::Autolock _l(mLock);
7927 return getEffectChain_l(sessionId);
7928}
7929
Glenn Kasten106e8a42012-08-02 13:37:12 -07007930sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007931{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007932 size_t size = mEffectChains.size();
7933 for (size_t i = 0; i < size; i++) {
7934 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007935 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007936 }
7937 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007938 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007939}
7940
Glenn Kastenf78aee72012-01-04 11:00:47 -08007941void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007942{
7943 Mutex::Autolock _l(mLock);
7944 size_t size = mEffectChains.size();
7945 for (size_t i = 0; i < size; i++) {
7946 mEffectChains[i]->setMode_l(mode);
7947 }
7948}
7949
7950void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007951 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007952 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007953
Mathias Agopian65ab4712010-07-14 17:59:35 -07007954 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007955 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007956 // delete the effect module if removing last handle on it
7957 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007958 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007959 removeEffect_l(effect);
7960 AudioSystem::unregisterEffect(effect->id());
7961 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007962 }
7963}
7964
7965status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7966{
7967 int session = chain->sessionId();
7968 int16_t *buffer = mMixBuffer;
7969 bool ownsBuffer = false;
7970
Steve Block3856b092011-10-20 11:56:00 +01007971 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007972 if (session > 0) {
7973 // Only one effect chain can be present in direct output thread and it uses
7974 // the mix buffer as input
7975 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007976 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007977 buffer = new int16_t[numSamples];
7978 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007979 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007980 ownsBuffer = true;
7981 }
7982
7983 // Attach all tracks with same session ID to this chain.
7984 for (size_t i = 0; i < mTracks.size(); ++i) {
7985 sp<Track> track = mTracks[i];
7986 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007987 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007988 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007989 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007990 }
7991 }
7992
7993 // indicate all active tracks in the chain
7994 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7995 sp<Track> track = mActiveTracks[i].promote();
7996 if (track == 0) continue;
7997 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007998 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007999 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008000 }
8001 }
8002 }
8003
8004 chain->setInBuffer(buffer, ownsBuffer);
8005 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07008006 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07008007 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008008 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
8009 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008010 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07008011 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
8012 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07008013 // Effect chain for other sessions are inserted at beginning of effect
8014 // chains list to be processed before output mix effects. Relative order between other
8015 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07008016 size_t size = mEffectChains.size();
8017 size_t i = 0;
8018 for (i = 0; i < size; i++) {
8019 if (mEffectChains[i]->sessionId() < session) break;
8020 }
8021 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008022 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008023
8024 return NO_ERROR;
8025}
8026
8027size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
8028{
8029 int session = chain->sessionId();
8030
Steve Block3856b092011-10-20 11:56:00 +01008031 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008032
8033 for (size_t i = 0; i < mEffectChains.size(); i++) {
8034 if (chain == mEffectChains[i]) {
8035 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07008036 // detach all active tracks from the chain
8037 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8038 sp<Track> track = mActiveTracks[i].promote();
8039 if (track == 0) continue;
8040 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008041 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07008042 chain.get(), session);
8043 chain->decActiveTrackCnt();
8044 }
8045 }
8046
Mathias Agopian65ab4712010-07-14 17:59:35 -07008047 // detach all tracks with same session ID from this chain
8048 for (size_t i = 0; i < mTracks.size(); ++i) {
8049 sp<Track> track = mTracks[i];
8050 if (session == track->sessionId()) {
8051 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008052 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008053 }
8054 }
Eric Laurentde070132010-07-13 04:45:46 -07008055 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008056 }
8057 }
8058 return mEffectChains.size();
8059}
8060
Eric Laurentde070132010-07-13 04:45:46 -07008061status_t AudioFlinger::PlaybackThread::attachAuxEffect(
8062 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008063{
8064 Mutex::Autolock _l(mLock);
8065 return attachAuxEffect_l(track, EffectId);
8066}
8067
Eric Laurentde070132010-07-13 04:45:46 -07008068status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
8069 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008070{
8071 status_t status = NO_ERROR;
8072
8073 if (EffectId == 0) {
8074 track->setAuxBuffer(0, NULL);
8075 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07008076 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
8077 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008078 if (effect != 0) {
8079 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8080 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
8081 } else {
8082 status = INVALID_OPERATION;
8083 }
8084 } else {
8085 status = BAD_VALUE;
8086 }
8087 }
8088 return status;
8089}
8090
8091void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
8092{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008093 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008094 sp<Track> track = mTracks[i];
8095 if (track->auxEffectId() == effectId) {
8096 attachAuxEffect_l(track, 0);
8097 }
8098 }
8099}
8100
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008101status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8102{
8103 // only one chain per input thread
8104 if (mEffectChains.size() != 0) {
8105 return INVALID_OPERATION;
8106 }
Steve Block3856b092011-10-20 11:56:00 +01008107 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008108
8109 chain->setInBuffer(NULL);
8110 chain->setOutBuffer(NULL);
8111
Eric Laurent59255e42011-07-27 19:49:51 -07008112 checkSuspendOnAddEffectChain_l(chain);
8113
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008114 mEffectChains.add(chain);
8115
8116 return NO_ERROR;
8117}
8118
8119size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8120{
Steve Block3856b092011-10-20 11:56:00 +01008121 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00008122 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008123 "removeEffectChain_l() %p invalid chain size %d on thread %p",
8124 chain.get(), mEffectChains.size(), this);
8125 if (mEffectChains.size() == 1) {
8126 mEffectChains.removeAt(0);
8127 }
8128 return 0;
8129}
8130
Mathias Agopian65ab4712010-07-14 17:59:35 -07008131// ----------------------------------------------------------------------------
8132// EffectModule implementation
8133// ----------------------------------------------------------------------------
8134
8135#undef LOG_TAG
8136#define LOG_TAG "AudioFlinger::EffectModule"
8137
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008138AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008139 const wp<AudioFlinger::EffectChain>& chain,
8140 effect_descriptor_t *desc,
8141 int id,
8142 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07008143 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
8144 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07008145 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07008146 // mConfig is set by configure() and not used before then
8147 mEffectInterface(NULL),
8148 mStatus(NO_INIT), mState(IDLE),
8149 // mMaxDisableWaitCnt is set by configure() and not used before then
8150 // mDisableWaitCnt is set by process() and updateState() and not used before then
8151 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008152{
Steve Block3856b092011-10-20 11:56:00 +01008153 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008154 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008155
8156 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008157 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008158
8159 if (mStatus != NO_ERROR) {
8160 return;
8161 }
8162 lStatus = init();
8163 if (lStatus < 0) {
8164 mStatus = lStatus;
8165 goto Error;
8166 }
8167
Steve Block3856b092011-10-20 11:56:00 +01008168 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008169 return;
8170Error:
8171 EffectRelease(mEffectInterface);
8172 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008173 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008174}
8175
8176AudioFlinger::EffectModule::~EffectModule()
8177{
Steve Block3856b092011-10-20 11:56:00 +01008178 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008179 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008180 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8181 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8182 sp<ThreadBase> thread = mThread.promote();
8183 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008184 audio_stream_t *stream = thread->stream();
8185 if (stream != NULL) {
8186 stream->remove_audio_effect(stream, mEffectInterface);
8187 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008188 }
8189 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008190 // release effect engine
8191 EffectRelease(mEffectInterface);
8192 }
8193}
8194
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008195status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008196{
8197 status_t status;
8198
8199 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008200 int priority = handle->priority();
8201 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008202 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008203 size_t i;
8204 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008205 EffectHandle *h = mHandles[i];
8206 if (h == NULL || h->destroyed_l()) continue;
8207 // first non destroyed handle is considered in control
8208 if (controlHandle == NULL)
8209 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008210 if (h->priority() <= priority) break;
8211 }
8212 // if inserted in first place, move effect control from previous owner to this handle
8213 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008214 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008215 if (controlHandle != NULL) {
8216 enabled = controlHandle->enabled();
8217 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008218 }
Eric Laurent59255e42011-07-27 19:49:51 -07008219 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008220 status = NO_ERROR;
8221 } else {
8222 status = ALREADY_EXISTS;
8223 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008224 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008225 mHandles.insertAt(handle, i);
8226 return status;
8227}
8228
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008229size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008230{
8231 Mutex::Autolock _l(mLock);
8232 size_t size = mHandles.size();
8233 size_t i;
8234 for (i = 0; i < size; i++) {
8235 if (mHandles[i] == handle) break;
8236 }
8237 if (i == size) {
8238 return size;
8239 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008240 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008241
Mathias Agopian65ab4712010-07-14 17:59:35 -07008242 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008243 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008244 if (i == 0) {
8245 EffectHandle *h = controlHandle_l();
8246 if (h != NULL) {
8247 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008248 }
8249 }
8250
Eric Laurentec437d82011-07-26 20:54:46 -07008251 // Prevent calls to process() and other functions on effect interface from now on.
8252 // The effect engine will be released by the destructor when the last strong reference on
8253 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008254 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008255 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008256 }
8257
Eric Laurente65c8912012-07-20 15:57:23 -07008258 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008259}
8260
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008261// must be called with EffectModule::mLock held
8262AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008263{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008264 // the first valid handle in the list has control over the module
8265 for (size_t i = 0; i < mHandles.size(); i++) {
8266 EffectHandle *h = mHandles[i];
8267 if (h != NULL && !h->destroyed_l()) {
8268 return h;
8269 }
8270 }
8271
8272 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008273}
8274
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008275size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008276{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008277 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008278 // keep a strong reference on this EffectModule to avoid calling the
8279 // destructor before we exit
8280 sp<EffectModule> keep(this);
8281 {
8282 sp<ThreadBase> thread = mThread.promote();
8283 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008284 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008285 }
8286 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008287 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008288}
8289
8290void AudioFlinger::EffectModule::updateState() {
8291 Mutex::Autolock _l(mLock);
8292
8293 switch (mState) {
8294 case RESTART:
8295 reset_l();
8296 // FALL THROUGH
8297
8298 case STARTING:
8299 // clear auxiliary effect input buffer for next accumulation
8300 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8301 memset(mConfig.inputCfg.buffer.raw,
8302 0,
8303 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8304 }
8305 start_l();
8306 mState = ACTIVE;
8307 break;
8308 case STOPPING:
8309 stop_l();
8310 mDisableWaitCnt = mMaxDisableWaitCnt;
8311 mState = STOPPED;
8312 break;
8313 case STOPPED:
8314 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8315 // turn off sequence.
8316 if (--mDisableWaitCnt == 0) {
8317 reset_l();
8318 mState = IDLE;
8319 }
8320 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008321 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008322 break;
8323 }
8324}
8325
8326void AudioFlinger::EffectModule::process()
8327{
8328 Mutex::Autolock _l(mLock);
8329
Eric Laurentec437d82011-07-26 20:54:46 -07008330 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008331 mConfig.inputCfg.buffer.raw == NULL ||
8332 mConfig.outputCfg.buffer.raw == NULL) {
8333 return;
8334 }
8335
Eric Laurent8f45bd72010-08-31 13:50:07 -07008336 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008337 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8338 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008339 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008340 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008341 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008342 }
8343
8344 // do the actual processing in the effect engine
8345 int ret = (*mEffectInterface)->process(mEffectInterface,
8346 &mConfig.inputCfg.buffer,
8347 &mConfig.outputCfg.buffer);
8348
8349 // force transition to IDLE state when engine is ready
8350 if (mState == STOPPED && ret == -ENODATA) {
8351 mDisableWaitCnt = 1;
8352 }
8353
8354 // clear auxiliary effect input buffer for next accumulation
8355 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008356 memset(mConfig.inputCfg.buffer.raw, 0,
8357 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008358 }
8359 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008360 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8361 // If an insert effect is idle and input buffer is different from output buffer,
8362 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008363 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008364 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008365 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8366 int16_t *in = mConfig.inputCfg.buffer.s16;
8367 int16_t *out = mConfig.outputCfg.buffer.s16;
8368 for (size_t i = 0; i < frameCnt; i++) {
8369 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008370 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008371 }
8372 }
8373}
8374
8375void AudioFlinger::EffectModule::reset_l()
8376{
8377 if (mEffectInterface == NULL) {
8378 return;
8379 }
8380 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8381}
8382
8383status_t AudioFlinger::EffectModule::configure()
8384{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008385 if (mEffectInterface == NULL) {
8386 return NO_INIT;
8387 }
8388
8389 sp<ThreadBase> thread = mThread.promote();
8390 if (thread == 0) {
8391 return DEAD_OBJECT;
8392 }
8393
8394 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07008395 audio_channel_mask_t channelMask = thread->channelMask();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008396
8397 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008398 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008399 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07008400 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008401 }
Glenn Kasten254af182012-07-03 14:59:05 -07008402 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07008403 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8404 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008405 mConfig.inputCfg.samplingRate = thread->sampleRate();
8406 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8407 mConfig.inputCfg.bufferProvider.cookie = NULL;
8408 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8409 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8410 mConfig.outputCfg.bufferProvider.cookie = NULL;
8411 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8412 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8413 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8414 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008415 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008416 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008417 // - in other sessions:
8418 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8419 // other effect: overwrites output buffer: input buffer == output buffer
8420 // Auxiliary effect:
8421 // accumulates in output buffer: input buffer != output buffer
8422 // Therefore: accumulate <=> input buffer != output buffer
8423 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8424 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8425 } else {
8426 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8427 }
8428 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8429 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8430 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8431 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8432
Steve Block3856b092011-10-20 11:56:00 +01008433 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008434 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8435
Mathias Agopian65ab4712010-07-14 17:59:35 -07008436 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008437 uint32_t size = sizeof(int);
8438 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008439 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008440 sizeof(effect_config_t),
8441 &mConfig,
8442 &size,
8443 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008444 if (status == 0) {
8445 status = cmdStatus;
8446 }
8447
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008448 if (status == 0 &&
8449 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8450 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8451 effect_param_t *p = (effect_param_t *)buf32;
8452
8453 p->psize = sizeof(uint32_t);
8454 p->vsize = sizeof(uint32_t);
8455 size = sizeof(int);
8456 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8457
8458 uint32_t latency = 0;
8459 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8460 if (pbt != NULL) {
8461 latency = pbt->latency_l();
8462 }
8463
8464 *((int32_t *)p->data + 1)= latency;
8465 (*mEffectInterface)->command(mEffectInterface,
8466 EFFECT_CMD_SET_PARAM,
8467 sizeof(effect_param_t) + 8,
8468 &buf32,
8469 &size,
8470 &cmdStatus);
8471 }
8472
Mathias Agopian65ab4712010-07-14 17:59:35 -07008473 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8474 (1000 * mConfig.outputCfg.buffer.frameCount);
8475
8476 return status;
8477}
8478
8479status_t AudioFlinger::EffectModule::init()
8480{
8481 Mutex::Autolock _l(mLock);
8482 if (mEffectInterface == NULL) {
8483 return NO_INIT;
8484 }
8485 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008486 uint32_t size = sizeof(status_t);
8487 status_t status = (*mEffectInterface)->command(mEffectInterface,
8488 EFFECT_CMD_INIT,
8489 0,
8490 NULL,
8491 &size,
8492 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008493 if (status == 0) {
8494 status = cmdStatus;
8495 }
8496 return status;
8497}
8498
Eric Laurentec35a142011-10-05 17:42:25 -07008499status_t AudioFlinger::EffectModule::start()
8500{
8501 Mutex::Autolock _l(mLock);
8502 return start_l();
8503}
8504
Mathias Agopian65ab4712010-07-14 17:59:35 -07008505status_t AudioFlinger::EffectModule::start_l()
8506{
8507 if (mEffectInterface == NULL) {
8508 return NO_INIT;
8509 }
8510 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008511 uint32_t size = sizeof(status_t);
8512 status_t status = (*mEffectInterface)->command(mEffectInterface,
8513 EFFECT_CMD_ENABLE,
8514 0,
8515 NULL,
8516 &size,
8517 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008518 if (status == 0) {
8519 status = cmdStatus;
8520 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008521 if (status == 0 &&
8522 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8523 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8524 sp<ThreadBase> thread = mThread.promote();
8525 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008526 audio_stream_t *stream = thread->stream();
8527 if (stream != NULL) {
8528 stream->add_audio_effect(stream, mEffectInterface);
8529 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008530 }
8531 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008532 return status;
8533}
8534
Eric Laurentec437d82011-07-26 20:54:46 -07008535status_t AudioFlinger::EffectModule::stop()
8536{
8537 Mutex::Autolock _l(mLock);
8538 return stop_l();
8539}
8540
Mathias Agopian65ab4712010-07-14 17:59:35 -07008541status_t AudioFlinger::EffectModule::stop_l()
8542{
8543 if (mEffectInterface == NULL) {
8544 return NO_INIT;
8545 }
8546 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008547 uint32_t size = sizeof(status_t);
8548 status_t status = (*mEffectInterface)->command(mEffectInterface,
8549 EFFECT_CMD_DISABLE,
8550 0,
8551 NULL,
8552 &size,
8553 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008554 if (status == 0) {
8555 status = cmdStatus;
8556 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008557 if (status == 0 &&
8558 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8559 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8560 sp<ThreadBase> thread = mThread.promote();
8561 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008562 audio_stream_t *stream = thread->stream();
8563 if (stream != NULL) {
8564 stream->remove_audio_effect(stream, mEffectInterface);
8565 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008566 }
8567 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008568 return status;
8569}
8570
Eric Laurent25f43952010-07-28 05:40:18 -07008571status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8572 uint32_t cmdSize,
8573 void *pCmdData,
8574 uint32_t *replySize,
8575 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008576{
8577 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008578// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008579
Eric Laurentec437d82011-07-26 20:54:46 -07008580 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008581 return NO_INIT;
8582 }
Eric Laurent25f43952010-07-28 05:40:18 -07008583 status_t status = (*mEffectInterface)->command(mEffectInterface,
8584 cmdCode,
8585 cmdSize,
8586 pCmdData,
8587 replySize,
8588 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008589 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008590 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008591 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008592 EffectHandle *h = mHandles[i];
8593 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008594 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8595 }
8596 }
8597 }
8598 return status;
8599}
8600
8601status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8602{
8603 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008604 return setEnabled_l(enabled);
8605}
8606
8607// must be called with EffectModule::mLock held
8608status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8609{
8610
Steve Block3856b092011-10-20 11:56:00 +01008611 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008612
8613 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008614 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8615 if (enabled && status != NO_ERROR) {
8616 return status;
8617 }
8618
Mathias Agopian65ab4712010-07-14 17:59:35 -07008619 switch (mState) {
8620 // going from disabled to enabled
8621 case IDLE:
8622 mState = STARTING;
8623 break;
8624 case STOPPED:
8625 mState = RESTART;
8626 break;
8627 case STOPPING:
8628 mState = ACTIVE;
8629 break;
8630
8631 // going from enabled to disabled
8632 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008633 mState = STOPPED;
8634 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008635 case STARTING:
8636 mState = IDLE;
8637 break;
8638 case ACTIVE:
8639 mState = STOPPING;
8640 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008641 case DESTROYED:
8642 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008643 }
8644 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008645 EffectHandle *h = mHandles[i];
8646 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008647 h->setEnabled(enabled);
8648 }
8649 }
8650 }
8651 return NO_ERROR;
8652}
8653
Glenn Kastenc59c0042012-02-02 14:06:11 -08008654bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008655{
8656 switch (mState) {
8657 case RESTART:
8658 case STARTING:
8659 case ACTIVE:
8660 return true;
8661 case IDLE:
8662 case STOPPING:
8663 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008664 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008665 default:
8666 return false;
8667 }
8668}
8669
Glenn Kastenc59c0042012-02-02 14:06:11 -08008670bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008671{
8672 switch (mState) {
8673 case RESTART:
8674 case ACTIVE:
8675 case STOPPING:
8676 case STOPPED:
8677 return true;
8678 case IDLE:
8679 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008680 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008681 default:
8682 return false;
8683 }
8684}
8685
Mathias Agopian65ab4712010-07-14 17:59:35 -07008686status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8687{
8688 Mutex::Autolock _l(mLock);
8689 status_t status = NO_ERROR;
8690
8691 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8692 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008693 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008694 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8695 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008696 status_t cmdStatus;
8697 uint32_t volume[2];
8698 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008699 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008700 volume[0] = *left;
8701 volume[1] = *right;
8702 if (controller) {
8703 pVolume = volume;
8704 }
Eric Laurent25f43952010-07-28 05:40:18 -07008705 status = (*mEffectInterface)->command(mEffectInterface,
8706 EFFECT_CMD_SET_VOLUME,
8707 size,
8708 volume,
8709 &size,
8710 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008711 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8712 *left = volume[0];
8713 *right = volume[1];
8714 }
8715 }
8716 return status;
8717}
8718
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008719status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008720{
Eric Laurentf1c04f92012-08-28 14:26:53 -07008721 if (device == AUDIO_DEVICE_NONE) {
8722 return NO_ERROR;
8723 }
8724
Mathias Agopian65ab4712010-07-14 17:59:35 -07008725 Mutex::Autolock _l(mLock);
8726 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008727 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07008728 status_t cmdStatus;
8729 uint32_t size = sizeof(status_t);
8730 uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE :
8731 EFFECT_CMD_SET_INPUT_DEVICE;
8732 status = (*mEffectInterface)->command(mEffectInterface,
8733 cmd,
8734 sizeof(uint32_t),
8735 &device,
8736 &size,
8737 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008738 }
8739 return status;
8740}
8741
Glenn Kastenf78aee72012-01-04 11:00:47 -08008742status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008743{
8744 Mutex::Autolock _l(mLock);
8745 status_t status = NO_ERROR;
8746 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008747 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008748 uint32_t size = sizeof(status_t);
8749 status = (*mEffectInterface)->command(mEffectInterface,
8750 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008751 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008752 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008753 &size,
8754 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008755 if (status == NO_ERROR) {
8756 status = cmdStatus;
8757 }
8758 }
8759 return status;
8760}
8761
Eric Laurent57b2dd12012-08-31 17:44:06 -07008762status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
8763{
8764 Mutex::Autolock _l(mLock);
8765 status_t status = NO_ERROR;
8766 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
8767 uint32_t size = 0;
8768 status = (*mEffectInterface)->command(mEffectInterface,
8769 EFFECT_CMD_SET_AUDIO_SOURCE,
8770 sizeof(audio_source_t),
8771 &source,
8772 &size,
8773 NULL);
8774 }
8775 return status;
8776}
8777
Eric Laurent59255e42011-07-27 19:49:51 -07008778void AudioFlinger::EffectModule::setSuspended(bool suspended)
8779{
8780 Mutex::Autolock _l(mLock);
8781 mSuspended = suspended;
8782}
Glenn Kastena3a85482012-01-04 11:01:11 -08008783
8784bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008785{
8786 Mutex::Autolock _l(mLock);
8787 return mSuspended;
8788}
8789
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008790bool AudioFlinger::EffectModule::purgeHandles()
8791{
8792 bool enabled = false;
8793 Mutex::Autolock _l(mLock);
8794 for (size_t i = 0; i < mHandles.size(); i++) {
8795 EffectHandle *handle = mHandles[i];
8796 if (handle != NULL && !handle->destroyed_l()) {
8797 handle->effect().clear();
8798 if (handle->hasControl()) {
8799 enabled = handle->enabled();
8800 }
8801 }
8802 }
8803 return enabled;
8804}
8805
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07008806void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008807{
8808 const size_t SIZE = 256;
8809 char buffer[SIZE];
8810 String8 result;
8811
8812 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8813 result.append(buffer);
8814
8815 bool locked = tryLock(mLock);
8816 // failed to lock - AudioFlinger is probably deadlocked
8817 if (!locked) {
8818 result.append("\t\tCould not lock Fx mutex:\n");
8819 }
8820
8821 result.append("\t\tSession Status State Engine:\n");
8822 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8823 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8824 result.append(buffer);
8825
8826 result.append("\t\tDescriptor:\n");
8827 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8828 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8829 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8830 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8831 result.append(buffer);
8832 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8833 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8834 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8835 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8836 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008837 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008838 mDescriptor.apiVersion,
8839 mDescriptor.flags);
8840 result.append(buffer);
8841 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8842 mDescriptor.name);
8843 result.append(buffer);
8844 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8845 mDescriptor.implementor);
8846 result.append(buffer);
8847
8848 result.append("\t\t- Input configuration:\n");
8849 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8850 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8851 (uint32_t)mConfig.inputCfg.buffer.raw,
8852 mConfig.inputCfg.buffer.frameCount,
8853 mConfig.inputCfg.samplingRate,
8854 mConfig.inputCfg.channels,
8855 mConfig.inputCfg.format);
8856 result.append(buffer);
8857
8858 result.append("\t\t- Output configuration:\n");
8859 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8860 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8861 (uint32_t)mConfig.outputCfg.buffer.raw,
8862 mConfig.outputCfg.buffer.frameCount,
8863 mConfig.outputCfg.samplingRate,
8864 mConfig.outputCfg.channels,
8865 mConfig.outputCfg.format);
8866 result.append(buffer);
8867
8868 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8869 result.append(buffer);
8870 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8871 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008872 EffectHandle *handle = mHandles[i];
8873 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008874 handle->dump(buffer, SIZE);
8875 result.append(buffer);
8876 }
8877 }
8878
8879 result.append("\n");
8880
8881 write(fd, result.string(), result.length());
8882
8883 if (locked) {
8884 mLock.unlock();
8885 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008886}
8887
8888// ----------------------------------------------------------------------------
8889// EffectHandle implementation
8890// ----------------------------------------------------------------------------
8891
8892#undef LOG_TAG
8893#define LOG_TAG "AudioFlinger::EffectHandle"
8894
8895AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8896 const sp<AudioFlinger::Client>& client,
8897 const sp<IEffectClient>& effectClient,
8898 int32_t priority)
8899 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008900 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008901 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008902{
Steve Block3856b092011-10-20 11:56:00 +01008903 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008904
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008905 if (client == 0) {
8906 return;
8907 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008908 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8909 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8910 if (mCblkMemory != 0) {
8911 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8912
Glenn Kastena0d68332012-01-27 16:47:15 -08008913 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008914 new(mCblk) effect_param_cblk_t();
8915 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008916 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008917 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008918 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008919 return;
8920 }
8921}
8922
8923AudioFlinger::EffectHandle::~EffectHandle()
8924{
Steve Block3856b092011-10-20 11:56:00 +01008925 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008926
8927 if (mEffect == 0) {
8928 mDestroyed = true;
8929 return;
8930 }
8931 mEffect->lock();
8932 mDestroyed = true;
8933 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008934 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008935}
8936
8937status_t AudioFlinger::EffectHandle::enable()
8938{
Steve Block3856b092011-10-20 11:56:00 +01008939 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008940 if (!mHasControl) return INVALID_OPERATION;
8941 if (mEffect == 0) return DEAD_OBJECT;
8942
Eric Laurentdb7c0792011-08-10 10:37:50 -07008943 if (mEnabled) {
8944 return NO_ERROR;
8945 }
8946
Eric Laurent59255e42011-07-27 19:49:51 -07008947 mEnabled = true;
8948
8949 sp<ThreadBase> thread = mEffect->thread().promote();
8950 if (thread != 0) {
8951 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8952 }
8953
8954 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8955 if (mEffect->suspended()) {
8956 return NO_ERROR;
8957 }
8958
Eric Laurentdb7c0792011-08-10 10:37:50 -07008959 status_t status = mEffect->setEnabled(true);
8960 if (status != NO_ERROR) {
8961 if (thread != 0) {
8962 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8963 }
8964 mEnabled = false;
8965 }
8966 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008967}
8968
8969status_t AudioFlinger::EffectHandle::disable()
8970{
Steve Block3856b092011-10-20 11:56:00 +01008971 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008972 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008973 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008974
Eric Laurentdb7c0792011-08-10 10:37:50 -07008975 if (!mEnabled) {
8976 return NO_ERROR;
8977 }
Eric Laurent59255e42011-07-27 19:49:51 -07008978 mEnabled = false;
8979
8980 if (mEffect->suspended()) {
8981 return NO_ERROR;
8982 }
8983
8984 status_t status = mEffect->setEnabled(false);
8985
8986 sp<ThreadBase> thread = mEffect->thread().promote();
8987 if (thread != 0) {
8988 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8989 }
8990
8991 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008992}
8993
8994void AudioFlinger::EffectHandle::disconnect()
8995{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008996 disconnect(true);
8997}
8998
Glenn Kasten58123c32012-02-03 10:32:24 -08008999void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009000{
Glenn Kasten58123c32012-02-03 10:32:24 -08009001 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009002 if (mEffect == 0) {
9003 return;
9004 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009005 // restore suspended effects if the disconnected handle was enabled and the last one.
9006 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009007 sp<ThreadBase> thread = mEffect->thread().promote();
9008 if (thread != 0) {
9009 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9010 }
Eric Laurent59255e42011-07-27 19:49:51 -07009011 }
9012
Mathias Agopian65ab4712010-07-14 17:59:35 -07009013 // release sp on module => module destructor can be called now
9014 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009015 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08009016 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08009017 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009018 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
9019 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08009020 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08009021 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07009022 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
9023 mClient.clear();
9024 }
9025}
9026
Eric Laurent25f43952010-07-28 05:40:18 -07009027status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
9028 uint32_t cmdSize,
9029 void *pCmdData,
9030 uint32_t *replySize,
9031 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009032{
Steve Block3856b092011-10-20 11:56:00 +01009033// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07009034// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07009035
9036 // only get parameter command is permitted for applications not controlling the effect
9037 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
9038 return INVALID_OPERATION;
9039 }
9040 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009041 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009042
9043 // handle commands that are not forwarded transparently to effect engine
9044 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
9045 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
9046 // no risk to block the whole media server process or mixer threads is we are stuck here
9047 Mutex::Autolock _l(mCblk->lock);
9048 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
9049 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
9050 mCblk->serverIndex = 0;
9051 mCblk->clientIndex = 0;
9052 return BAD_VALUE;
9053 }
9054 status_t status = NO_ERROR;
9055 while (mCblk->serverIndex < mCblk->clientIndex) {
9056 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07009057 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009058 int *p = (int *)(mBuffer + mCblk->serverIndex);
9059 int size = *p++;
9060 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009061 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009062 break;
9063 }
9064 effect_param_t *param = (effect_param_t *)p;
9065 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009066 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009067 mCblk->serverIndex += size;
9068 continue;
9069 }
Eric Laurent25f43952010-07-28 05:40:18 -07009070 uint32_t psize = sizeof(effect_param_t) +
9071 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
9072 param->vsize;
9073 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
9074 psize,
9075 p,
9076 &rsize,
9077 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07009078 // stop at first error encountered
9079 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009080 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07009081 *(int *)pReplyData = reply;
9082 break;
9083 } else if (reply != NO_ERROR) {
9084 *(int *)pReplyData = reply;
9085 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009086 }
9087 mCblk->serverIndex += size;
9088 }
9089 mCblk->serverIndex = 0;
9090 mCblk->clientIndex = 0;
9091 return status;
9092 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009093 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009094 return enable();
9095 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009096 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009097 return disable();
9098 }
9099
9100 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9101}
9102
Eric Laurent59255e42011-07-27 19:49:51 -07009103void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009104{
Steve Block3856b092011-10-20 11:56:00 +01009105 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009106
9107 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07009108 mEnabled = enabled;
9109
Mathias Agopian65ab4712010-07-14 17:59:35 -07009110 if (signal && mEffectClient != 0) {
9111 mEffectClient->controlStatusChanged(hasControl);
9112 }
9113}
9114
Eric Laurent25f43952010-07-28 05:40:18 -07009115void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
9116 uint32_t cmdSize,
9117 void *pCmdData,
9118 uint32_t replySize,
9119 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009120{
9121 if (mEffectClient != 0) {
9122 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9123 }
9124}
9125
9126
9127
9128void AudioFlinger::EffectHandle::setEnabled(bool enabled)
9129{
9130 if (mEffectClient != 0) {
9131 mEffectClient->enableStatusChanged(enabled);
9132 }
9133}
9134
9135status_t AudioFlinger::EffectHandle::onTransact(
9136 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9137{
9138 return BnEffect::onTransact(code, data, reply, flags);
9139}
9140
9141
9142void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
9143{
Glenn Kastena0d68332012-01-27 16:47:15 -08009144 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009145
9146 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08009147 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07009148 mPriority,
9149 mHasControl,
9150 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009151 mCblk ? mCblk->clientIndex : 0,
9152 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07009153 );
9154
9155 if (locked) {
9156 mCblk->lock.unlock();
9157 }
9158}
9159
9160#undef LOG_TAG
9161#define LOG_TAG "AudioFlinger::EffectChain"
9162
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009163AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009164 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009165 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07009166 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9167 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009168{
Dima Zavinfce7a472011-04-19 22:30:36 -07009169 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009170 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009171 return;
9172 }
9173 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9174 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009175}
9176
9177AudioFlinger::EffectChain::~EffectChain()
9178{
9179 if (mOwnInBuffer) {
9180 delete mInBuffer;
9181 }
9182
9183}
9184
Eric Laurent59255e42011-07-27 19:49:51 -07009185// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009186sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009187{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009188 size_t size = mEffects.size();
9189
9190 for (size_t i = 0; i < size; i++) {
9191 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009192 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009193 }
9194 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009195 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009196}
9197
Eric Laurent59255e42011-07-27 19:49:51 -07009198// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009199sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009200{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009201 size_t size = mEffects.size();
9202
9203 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009204 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9205 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009206 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009207 }
9208 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009209 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009210}
9211
Eric Laurent59255e42011-07-27 19:49:51 -07009212// getEffectFromType_l() must be called with ThreadBase::mLock held
9213sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9214 const effect_uuid_t *type)
9215{
Eric Laurent59255e42011-07-27 19:49:51 -07009216 size_t size = mEffects.size();
9217
9218 for (size_t i = 0; i < size; i++) {
9219 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009220 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009221 }
9222 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009223 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009224}
9225
Eric Laurent91b14c42012-05-30 12:30:29 -07009226void AudioFlinger::EffectChain::clearInputBuffer()
9227{
9228 Mutex::Autolock _l(mLock);
9229 sp<ThreadBase> thread = mThread.promote();
9230 if (thread == 0) {
9231 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9232 return;
9233 }
9234 clearInputBuffer_l(thread);
9235}
9236
9237// Must be called with EffectChain::mLock locked
9238void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9239{
9240 size_t numSamples = thread->frameCount() * thread->channelCount();
9241 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9242
9243}
9244
Mathias Agopian65ab4712010-07-14 17:59:35 -07009245// Must be called with EffectChain::mLock locked
9246void AudioFlinger::EffectChain::process_l()
9247{
Eric Laurentdac69112010-09-28 14:09:57 -07009248 sp<ThreadBase> thread = mThread.promote();
9249 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009250 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009251 return;
9252 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009253 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9254 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009255 // always process effects unless no more tracks are on the session and the effect tail
9256 // has been rendered
9257 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009258 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009259 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009260
Eric Laurent544fe9b2011-11-11 15:42:52 -08009261 if (!tracksOnSession && mTailBufferCount == 0) {
9262 doProcess = false;
9263 }
9264
9265 if (activeTrackCnt() == 0) {
9266 // if no track is active and the effect tail has not been rendered,
9267 // the input buffer must be cleared here as the mixer process will not do it
9268 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009269 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009270 if (mTailBufferCount > 0) {
9271 mTailBufferCount--;
9272 }
9273 }
9274 }
Eric Laurentdac69112010-09-28 14:09:57 -07009275 }
9276
Mathias Agopian65ab4712010-07-14 17:59:35 -07009277 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009278 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009279 for (size_t i = 0; i < size; i++) {
9280 mEffects[i]->process();
9281 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009282 }
9283 for (size_t i = 0; i < size; i++) {
9284 mEffects[i]->updateState();
9285 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009286}
9287
Eric Laurentcab11242010-07-15 12:50:15 -07009288// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009289status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009290{
9291 effect_descriptor_t desc = effect->desc();
9292 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9293
9294 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009295 effect->setChain(this);
9296 sp<ThreadBase> thread = mThread.promote();
9297 if (thread == 0) {
9298 return NO_INIT;
9299 }
9300 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009301
9302 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9303 // Auxiliary effects are inserted at the beginning of mEffects vector as
9304 // they are processed first and accumulated in chain input buffer
9305 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009306
Mathias Agopian65ab4712010-07-14 17:59:35 -07009307 // the input buffer for auxiliary effect contains mono samples in
9308 // 32 bit format. This is to avoid saturation in AudoMixer
9309 // accumulation stage. Saturation is done in EffectModule::process() before
9310 // calling the process in effect engine
9311 size_t numSamples = thread->frameCount();
9312 int32_t *buffer = new int32_t[numSamples];
9313 memset(buffer, 0, numSamples * sizeof(int32_t));
9314 effect->setInBuffer((int16_t *)buffer);
9315 // auxiliary effects output samples to chain input buffer for further processing
9316 // by insert effects
9317 effect->setOutBuffer(mInBuffer);
9318 } else {
9319 // Insert effects are inserted at the end of mEffects vector as they are processed
9320 // after track and auxiliary effects.
9321 // Insert effect order as a function of indicated preference:
9322 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9323 // another effect is present
9324 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9325 // last effect claiming first position
9326 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9327 // first effect claiming last position
9328 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9329 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9330 // already present
9331
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009332 size_t size = mEffects.size();
9333 size_t idx_insert = size;
9334 ssize_t idx_insert_first = -1;
9335 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009336
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009337 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009338 effect_descriptor_t d = mEffects[i]->desc();
9339 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9340 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9341 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9342 // check invalid effect chaining combinations
9343 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9344 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009345 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009346 return INVALID_OPERATION;
9347 }
9348 // remember position of first insert effect and by default
9349 // select this as insert position for new effect
9350 if (idx_insert == size) {
9351 idx_insert = i;
9352 }
9353 // remember position of last insert effect claiming
9354 // first position
9355 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9356 idx_insert_first = i;
9357 }
9358 // remember position of first insert effect claiming
9359 // last position
9360 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9361 idx_insert_last == -1) {
9362 idx_insert_last = i;
9363 }
9364 }
9365 }
9366
9367 // modify idx_insert from first position if needed
9368 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9369 if (idx_insert_last != -1) {
9370 idx_insert = idx_insert_last;
9371 } else {
9372 idx_insert = size;
9373 }
9374 } else {
9375 if (idx_insert_first != -1) {
9376 idx_insert = idx_insert_first + 1;
9377 }
9378 }
9379
9380 // always read samples from chain input buffer
9381 effect->setInBuffer(mInBuffer);
9382
9383 // if last effect in the chain, output samples to chain
9384 // output buffer, otherwise to chain input buffer
9385 if (idx_insert == size) {
9386 if (idx_insert != 0) {
9387 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9388 mEffects[idx_insert-1]->configure();
9389 }
9390 effect->setOutBuffer(mOutBuffer);
9391 } else {
9392 effect->setOutBuffer(mInBuffer);
9393 }
9394 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009395
Steve Block3856b092011-10-20 11:56:00 +01009396 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009397 }
9398 effect->configure();
9399 return NO_ERROR;
9400}
9401
Eric Laurentcab11242010-07-15 12:50:15 -07009402// removeEffect_l() must be called with PlaybackThread::mLock held
9403size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009404{
9405 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009406 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009407 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9408
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009409 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009410 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009411 // calling stop here will remove pre-processing effect from the audio HAL.
9412 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9413 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009414 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9415 mEffects[i]->state() == EffectModule::STOPPING) {
9416 mEffects[i]->stop();
9417 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009418 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9419 delete[] effect->inBuffer();
9420 } else {
9421 if (i == size - 1 && i != 0) {
9422 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9423 mEffects[i - 1]->configure();
9424 }
9425 }
9426 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009427 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009428 break;
9429 }
9430 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009431
9432 return mEffects.size();
9433}
9434
Eric Laurentcab11242010-07-15 12:50:15 -07009435// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009436void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009437{
9438 size_t size = mEffects.size();
9439 for (size_t i = 0; i < size; i++) {
9440 mEffects[i]->setDevice(device);
9441 }
9442}
9443
Eric Laurentcab11242010-07-15 12:50:15 -07009444// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009445void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009446{
9447 size_t size = mEffects.size();
9448 for (size_t i = 0; i < size; i++) {
9449 mEffects[i]->setMode(mode);
9450 }
9451}
9452
Eric Laurent57b2dd12012-08-31 17:44:06 -07009453// setAudioSource_l() must be called with PlaybackThread::mLock held
9454void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
9455{
9456 size_t size = mEffects.size();
9457 for (size_t i = 0; i < size; i++) {
9458 mEffects[i]->setAudioSource(source);
9459 }
9460}
9461
Eric Laurentcab11242010-07-15 12:50:15 -07009462// setVolume_l() must be called with PlaybackThread::mLock held
9463bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009464{
9465 uint32_t newLeft = *left;
9466 uint32_t newRight = *right;
9467 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009468 int ctrlIdx = -1;
9469 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009470
Eric Laurentcab11242010-07-15 12:50:15 -07009471 // first update volume controller
9472 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009473 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009474 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9475 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009476 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009477 break;
9478 }
9479 }
9480
9481 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009482 if (hasControl) {
9483 *left = mNewLeftVolume;
9484 *right = mNewRightVolume;
9485 }
9486 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009487 }
9488
9489 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009490 mLeftVolume = newLeft;
9491 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009492
9493 // second get volume update from volume controller
9494 if (ctrlIdx >= 0) {
9495 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009496 mNewLeftVolume = newLeft;
9497 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009498 }
9499 // then indicate volume to all other effects in chain.
9500 // Pass altered volume to effects before volume controller
9501 // and requested volume to effects after controller
9502 uint32_t lVol = newLeft;
9503 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009504
Mathias Agopian65ab4712010-07-14 17:59:35 -07009505 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009506 if ((int)i == ctrlIdx) continue;
9507 // this also works for ctrlIdx == -1 when there is no volume controller
9508 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009509 lVol = *left;
9510 rVol = *right;
9511 }
9512 mEffects[i]->setVolume(&lVol, &rVol, false);
9513 }
9514 *left = newLeft;
9515 *right = newRight;
9516
9517 return hasControl;
9518}
9519
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009520void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009521{
9522 const size_t SIZE = 256;
9523 char buffer[SIZE];
9524 String8 result;
9525
9526 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9527 result.append(buffer);
9528
9529 bool locked = tryLock(mLock);
9530 // failed to lock - AudioFlinger is probably deadlocked
9531 if (!locked) {
9532 result.append("\tCould not lock mutex:\n");
9533 }
9534
Eric Laurentcab11242010-07-15 12:50:15 -07009535 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9536 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009537 mEffects.size(),
9538 (uint32_t)mInBuffer,
9539 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009540 mActiveTrackCnt);
9541 result.append(buffer);
9542 write(fd, result.string(), result.size());
9543
9544 for (size_t i = 0; i < mEffects.size(); ++i) {
9545 sp<EffectModule> effect = mEffects[i];
9546 if (effect != 0) {
9547 effect->dump(fd, args);
9548 }
9549 }
9550
9551 if (locked) {
9552 mLock.unlock();
9553 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009554}
9555
Eric Laurent59255e42011-07-27 19:49:51 -07009556// must be called with ThreadBase::mLock held
9557void AudioFlinger::EffectChain::setEffectSuspended_l(
9558 const effect_uuid_t *type, bool suspend)
9559{
9560 sp<SuspendedEffectDesc> desc;
9561 // use effect type UUID timelow as key as there is no real risk of identical
9562 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009563 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009564 if (suspend) {
9565 if (index >= 0) {
9566 desc = mSuspendedEffects.valueAt(index);
9567 } else {
9568 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -08009569 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07009570 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009571 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009572 }
9573 if (desc->mRefCount++ == 0) {
9574 sp<EffectModule> effect = getEffectIfEnabled(type);
9575 if (effect != 0) {
9576 desc->mEffect = effect;
9577 effect->setSuspended(true);
9578 effect->setEnabled(false);
9579 }
9580 }
9581 } else {
9582 if (index < 0) {
9583 return;
9584 }
9585 desc = mSuspendedEffects.valueAt(index);
9586 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009587 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009588 desc->mRefCount = 1;
9589 }
9590 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009591 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009592 if (desc->mEffect != 0) {
9593 sp<EffectModule> effect = desc->mEffect.promote();
9594 if (effect != 0) {
9595 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009596 effect->lock();
9597 EffectHandle *handle = effect->controlHandle_l();
9598 if (handle != NULL && !handle->destroyed_l()) {
9599 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009600 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009601 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009602 }
9603 desc->mEffect.clear();
9604 }
9605 mSuspendedEffects.removeItemsAt(index);
9606 }
9607 }
9608}
9609
9610// must be called with ThreadBase::mLock held
9611void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9612{
9613 sp<SuspendedEffectDesc> desc;
9614
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009615 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009616 if (suspend) {
9617 if (index >= 0) {
9618 desc = mSuspendedEffects.valueAt(index);
9619 } else {
9620 desc = new SuspendedEffectDesc();
9621 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009622 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009623 }
9624 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009625 Vector< sp<EffectModule> > effects;
9626 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009627 for (size_t i = 0; i < effects.size(); i++) {
9628 setEffectSuspended_l(&effects[i]->desc().type, true);
9629 }
9630 }
9631 } else {
9632 if (index < 0) {
9633 return;
9634 }
9635 desc = mSuspendedEffects.valueAt(index);
9636 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009637 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009638 desc->mRefCount = 1;
9639 }
9640 if (--desc->mRefCount == 0) {
9641 Vector<const effect_uuid_t *> types;
9642 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9643 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9644 continue;
9645 }
9646 types.add(&mSuspendedEffects.valueAt(i)->mType);
9647 }
9648 for (size_t i = 0; i < types.size(); i++) {
9649 setEffectSuspended_l(types[i], false);
9650 }
Steve Block3856b092011-10-20 11:56:00 +01009651 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009652 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9653 }
9654 }
9655}
9656
Eric Laurent6bffdb82011-09-23 08:40:41 -07009657
9658// The volume effect is used for automated tests only
9659#ifndef OPENSL_ES_H_
9660static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9661 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9662const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9663#endif //OPENSL_ES_H_
9664
Eric Laurentdb7c0792011-08-10 10:37:50 -07009665bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9666{
9667 // auxiliary effects and visualizer are never suspended on output mix
9668 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9669 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009670 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9671 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009672 return false;
9673 }
9674 return true;
9675}
9676
Glenn Kastend0539712012-01-30 12:56:03 -08009677void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009678{
Glenn Kastend0539712012-01-30 12:56:03 -08009679 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009680 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009681 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9682 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009683 }
Eric Laurent59255e42011-07-27 19:49:51 -07009684 }
Eric Laurent59255e42011-07-27 19:49:51 -07009685}
9686
9687sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9688 const effect_uuid_t *type)
9689{
Glenn Kasten090f0192012-01-30 13:00:02 -08009690 sp<EffectModule> effect = getEffectFromType_l(type);
9691 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009692}
9693
9694void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9695 bool enabled)
9696{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009697 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009698 if (enabled) {
9699 if (index < 0) {
9700 // if the effect is not suspend check if all effects are suspended
9701 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9702 if (index < 0) {
9703 return;
9704 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009705 if (!isEffectEligibleForSuspend(effect->desc())) {
9706 return;
9707 }
Eric Laurent59255e42011-07-27 19:49:51 -07009708 setEffectSuspended_l(&effect->desc().type, enabled);
9709 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009710 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009711 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009712 return;
9713 }
Eric Laurent59255e42011-07-27 19:49:51 -07009714 }
Steve Block3856b092011-10-20 11:56:00 +01009715 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009716 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009717 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9718 // if effect is requested to suspended but was not yet enabled, supend it now.
9719 if (desc->mEffect == 0) {
9720 desc->mEffect = effect;
9721 effect->setEnabled(false);
9722 effect->setSuspended(true);
9723 }
9724 } else {
9725 if (index < 0) {
9726 return;
9727 }
Steve Block3856b092011-10-20 11:56:00 +01009728 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009729 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009730 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9731 desc->mEffect.clear();
9732 effect->setSuspended(false);
9733 }
9734}
9735
Mathias Agopian65ab4712010-07-14 17:59:35 -07009736#undef LOG_TAG
9737#define LOG_TAG "AudioFlinger"
9738
9739// ----------------------------------------------------------------------------
9740
9741status_t AudioFlinger::onTransact(
9742 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9743{
9744 return BnAudioFlinger::onTransact(code, data, reply, flags);
9745}
9746
Mathias Agopian65ab4712010-07-14 17:59:35 -07009747}; // namespace android