blob: de116a9074f0a19e0d34c33cb9ab14518c382537 [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();
1178 mWaitWorkCV.signal();
1179 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001180 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1181 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001182 requestExitAndWait();
1183}
1184
Mathias Agopian65ab4712010-07-14 17:59:35 -07001185status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1186{
1187 status_t status;
1188
Steve Block3856b092011-10-20 11:56:00 +01001189 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001190 Mutex::Autolock _l(mLock);
1191
1192 mNewParameters.add(keyValuePairs);
1193 mWaitWorkCV.signal();
1194 // wait condition with timeout in case the thread loop has exited
1195 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001196 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001197 status = mParamStatus;
1198 mWaitWorkCV.signal();
1199 } else {
1200 status = TIMED_OUT;
1201 }
1202 return status;
1203}
1204
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
Dima Zavin799a70e2011-04-18 16:57:27 -07002119 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002120}
2121
Glenn Kasten106e8a42012-08-02 13:37:12 -07002122uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002123{
2124 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002125 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002126 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002127 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002128 }
2129
2130 for (size_t i = 0; i < mTracks.size(); ++i) {
2131 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002132 if (sessionId == track->sessionId() &&
2133 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002134 result |= TRACK_SESSION;
2135 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002136 }
2137 }
2138
Eric Laurent39e94f82010-07-28 01:32:47 -07002139 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002140}
2141
Eric Laurentde070132010-07-13 04:45:46 -07002142uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2143{
Dima Zavinfce7a472011-04-19 22:30:36 -07002144 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002145 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002146 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2147 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002148 }
2149 for (size_t i = 0; i < mTracks.size(); i++) {
2150 sp<Track> track = mTracks[i];
2151 if (sessionId == track->sessionId() &&
2152 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002153 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002154 }
2155 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002156 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002157}
2158
Mathias Agopian65ab4712010-07-14 17:59:35 -07002159
Glenn Kastenaed850d2012-01-26 09:46:34 -08002160AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002161{
2162 Mutex::Autolock _l(mLock);
2163 return mOutput;
2164}
2165
2166AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2167{
2168 Mutex::Autolock _l(mLock);
2169 AudioStreamOut *output = mOutput;
2170 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002171 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2172 // must push a NULL and wait for ack
2173 mOutputSink.clear();
2174 mPipeSink.clear();
2175 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002176 return output;
2177}
2178
2179// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002180audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002181{
2182 if (mOutput == NULL) {
2183 return NULL;
2184 }
2185 return &mOutput->stream->common;
2186}
2187
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002188uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002189{
Eric Laurentab9071b2012-06-04 13:45:29 -07002190 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002191}
2192
Eric Laurenta011e352012-03-29 15:51:43 -07002193status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2194{
2195 if (!isValidSyncEvent(event)) {
2196 return BAD_VALUE;
2197 }
2198
2199 Mutex::Autolock _l(mLock);
2200
2201 for (size_t i = 0; i < mTracks.size(); ++i) {
2202 sp<Track> track = mTracks[i];
2203 if (event->triggerSession() == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07002204 (void) track->setSyncEvent(event);
Eric Laurenta011e352012-03-29 15:51:43 -07002205 return NO_ERROR;
2206 }
2207 }
2208
2209 return NAME_NOT_FOUND;
2210}
2211
Glenn Kasten106e8a42012-08-02 13:37:12 -07002212bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07002213{
Glenn Kasten0dbb3562012-08-02 16:36:50 -07002214 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
Eric Laurenta011e352012-03-29 15:51:43 -07002215}
2216
Eric Laurent44a957f2012-05-15 15:26:05 -07002217void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2218{
2219 size_t count = tracksToRemove.size();
2220 if (CC_UNLIKELY(count)) {
2221 for (size_t i = 0 ; i < count ; i++) {
2222 const sp<Track>& track = tracksToRemove.itemAt(i);
2223 if ((track->sharedBuffer() != 0) &&
2224 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2225 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2226 }
2227 }
2228 }
2229
2230}
2231
Mathias Agopian65ab4712010-07-14 17:59:35 -07002232// ----------------------------------------------------------------------------
2233
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002234AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002235 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002236 : PlaybackThread(audioFlinger, output, id, device, type),
2237 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002238 // mFastMixer below
2239 mFastMixerFutex(0)
2240 // mOutputSink below
2241 // mPipeSink below
2242 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002243{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002244 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002245 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002246 "mFrameCount=%d, mNormalFrameCount=%d",
2247 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2248 mNormalFrameCount);
2249 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2250
Mathias Agopian65ab4712010-07-14 17:59:35 -07002251 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002252 if (mChannelCount != FCC_2) {
2253 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002254 }
Glenn Kasten58912562012-04-03 10:45:00 -07002255
2256 // create an NBAIO sink for the HAL output stream, and negotiate
2257 mOutputSink = new AudioStreamOutSink(output->stream);
2258 size_t numCounterOffers = 0;
2259 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2260 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2261 ALOG_ASSERT(index == 0);
2262
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002263 // initialize fast mixer depending on configuration
2264 bool initFastMixer;
2265 switch (kUseFastMixer) {
2266 case FastMixer_Never:
2267 initFastMixer = false;
2268 break;
2269 case FastMixer_Always:
2270 initFastMixer = true;
2271 break;
2272 case FastMixer_Static:
2273 case FastMixer_Dynamic:
2274 initFastMixer = mFrameCount < mNormalFrameCount;
2275 break;
2276 }
2277 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002278
2279 // create a MonoPipe to connect our submix to FastMixer
2280 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002281 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2282 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2283 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2284 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002285 const NBAIO_Format offers[1] = {format};
2286 size_t numCounterOffers = 0;
2287 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2288 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002289 monoPipe->setAvgFrames((mScreenState & 1) ?
2290 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002291 mPipeSink = monoPipe;
2292
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002293#ifdef TEE_SINK_FRAMES
2294 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2295 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2296 numCounterOffers = 0;
2297 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2298 ALOG_ASSERT(index == 0);
2299 mTeeSink = teeSink;
2300 PipeReader *teeSource = new PipeReader(*teeSink);
2301 numCounterOffers = 0;
2302 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2303 ALOG_ASSERT(index == 0);
2304 mTeeSource = teeSource;
2305#endif
2306
Glenn Kasten58912562012-04-03 10:45:00 -07002307 // create fast mixer and configure it initially with just one fast track for our submix
2308 mFastMixer = new FastMixer();
2309 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002310#ifdef STATE_QUEUE_DUMP
2311 sq->setObserverDump(&mStateQueueObserverDump);
2312 sq->setMutatorDump(&mStateQueueMutatorDump);
2313#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002314 FastMixerState *state = sq->begin();
2315 FastTrack *fastTrack = &state->mFastTracks[0];
2316 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2317 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2318 fastTrack->mVolumeProvider = NULL;
2319 fastTrack->mGeneration++;
2320 state->mFastTracksGen++;
2321 state->mTrackMask = 1;
2322 // fast mixer will use the HAL output sink
2323 state->mOutputSink = mOutputSink.get();
2324 state->mOutputSinkGen++;
2325 state->mFrameCount = mFrameCount;
2326 state->mCommand = FastMixerState::COLD_IDLE;
2327 // already done in constructor initialization list
2328 //mFastMixerFutex = 0;
2329 state->mColdFutexAddr = &mFastMixerFutex;
2330 state->mColdGen++;
2331 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002332 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002333 sq->end();
2334 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2335
2336 // start the fast mixer
2337 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002338 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002339 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002340 if (err != 0) {
2341 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002342 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002343 }
Glenn Kasten58912562012-04-03 10:45:00 -07002344
Glenn Kastenc15d6652012-05-30 14:52:57 -07002345#ifdef AUDIO_WATCHDOG
2346 // create and start the watchdog
2347 mAudioWatchdog = new AudioWatchdog();
2348 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2349 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2350 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002351 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002352 if (err != 0) {
2353 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002354 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002355 }
2356#endif
2357
Glenn Kasten58912562012-04-03 10:45:00 -07002358 } else {
2359 mFastMixer = NULL;
2360 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002361
2362 switch (kUseFastMixer) {
2363 case FastMixer_Never:
2364 case FastMixer_Dynamic:
2365 mNormalSink = mOutputSink;
2366 break;
2367 case FastMixer_Always:
2368 mNormalSink = mPipeSink;
2369 break;
2370 case FastMixer_Static:
2371 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2372 break;
2373 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002374}
2375
2376AudioFlinger::MixerThread::~MixerThread()
2377{
Glenn Kasten58912562012-04-03 10:45:00 -07002378 if (mFastMixer != NULL) {
2379 FastMixerStateQueue *sq = mFastMixer->sq();
2380 FastMixerState *state = sq->begin();
2381 if (state->mCommand == FastMixerState::COLD_IDLE) {
2382 int32_t old = android_atomic_inc(&mFastMixerFutex);
2383 if (old == -1) {
2384 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2385 }
2386 }
2387 state->mCommand = FastMixerState::EXIT;
2388 sq->end();
2389 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2390 mFastMixer->join();
2391 // Though the fast mixer thread has exited, it's state queue is still valid.
2392 // We'll use that extract the final state which contains one remaining fast track
2393 // corresponding to our sub-mix.
2394 state = sq->begin();
2395 ALOG_ASSERT(state->mTrackMask == 1);
2396 FastTrack *fastTrack = &state->mFastTracks[0];
2397 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2398 delete fastTrack->mBufferProvider;
2399 sq->end(false /*didModify*/);
2400 delete mFastMixer;
Glenn Kastenc15d6652012-05-30 14:52:57 -07002401 if (mAudioWatchdog != 0) {
2402 mAudioWatchdog->requestExit();
2403 mAudioWatchdog->requestExitAndWait();
2404 mAudioWatchdog.clear();
2405 }
Glenn Kasten58912562012-04-03 10:45:00 -07002406 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002407 delete mAudioMixer;
2408}
2409
Glenn Kasten83efdd02012-02-24 07:21:32 -08002410class CpuStats {
2411public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002412 CpuStats();
2413 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002414#ifdef DEBUG_CPU_USAGE
2415private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002416 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2417 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2418
2419 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2420
2421 int mCpuNum; // thread's current CPU number
2422 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002423#endif
2424};
2425
Glenn Kasten190a46f2012-03-06 11:27:10 -08002426CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002427#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002428 : mCpuNum(-1), mCpukHz(-1)
2429#endif
2430{
2431}
2432
2433void CpuStats::sample(const String8 &title) {
2434#ifdef DEBUG_CPU_USAGE
2435 // get current thread's delta CPU time in wall clock ns
2436 double wcNs;
2437 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2438
2439 // record sample for wall clock statistics
2440 if (valid) {
2441 mWcStats.sample(wcNs);
2442 }
2443
2444 // get the current CPU number
2445 int cpuNum = sched_getcpu();
2446
2447 // get the current CPU frequency in kHz
2448 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2449
2450 // check if either CPU number or frequency changed
2451 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2452 mCpuNum = cpuNum;
2453 mCpukHz = cpukHz;
2454 // ignore sample for purposes of cycles
2455 valid = false;
2456 }
2457
2458 // if no change in CPU number or frequency, then record sample for cycle statistics
2459 if (valid && mCpukHz > 0) {
2460 double cycles = wcNs * cpukHz * 0.000001;
2461 mHzStats.sample(cycles);
2462 }
2463
2464 unsigned n = mWcStats.n();
2465 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002466 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002467 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002468 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2469 double perLoop = elapsed / (double) n;
2470 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002471 double perLoop1k = perLoop * 0.001;
2472 double mean = mWcStats.mean();
2473 double stddev = mWcStats.stddev();
2474 double minimum = mWcStats.minimum();
2475 double maximum = mWcStats.maximum();
2476 double meanCycles = mHzStats.mean();
2477 double stddevCycles = mHzStats.stddev();
2478 double minCycles = mHzStats.minimum();
2479 double maxCycles = mHzStats.maximum();
2480 mCpuUsage.resetElapsed();
2481 mWcStats.reset();
2482 mHzStats.reset();
2483 ALOGD("CPU usage for %s over past %.1f secs\n"
2484 " (%u mixer loops at %.1f mean ms per loop):\n"
2485 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2486 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2487 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2488 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002489 elapsed * .000000001, n, perLoop * .000001,
2490 mean * .001,
2491 stddev * .001,
2492 minimum * .001,
2493 maximum * .001,
2494 mean / perLoop100,
2495 stddev / perLoop100,
2496 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002497 maximum / perLoop100,
2498 meanCycles / perLoop1k,
2499 stddevCycles / perLoop1k,
2500 minCycles / perLoop1k,
2501 maxCycles / perLoop1k);
2502
Glenn Kasten83efdd02012-02-24 07:21:32 -08002503 }
2504 }
2505#endif
2506};
2507
Glenn Kasten37d825e2012-02-24 07:21:48 -08002508void AudioFlinger::PlaybackThread::checkSilentMode_l()
2509{
2510 if (!mMasterMute) {
2511 char value[PROPERTY_VALUE_MAX];
2512 if (property_get("ro.audio.silent", value, "0") > 0) {
2513 char *endptr;
2514 unsigned long ul = strtoul(value, &endptr, 0);
2515 if (*endptr == '\0' && ul != 0) {
2516 ALOGD("Silence is golden");
2517 // The setprop command will not allow a property to be changed after
2518 // the first time it is set, so we don't have to worry about un-muting.
2519 setMasterMute_l(true);
2520 }
2521 }
2522 }
2523}
2524
Glenn Kasten000f0e32012-03-01 17:10:56 -08002525bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002526{
2527 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002528
Glenn Kasten000f0e32012-03-01 17:10:56 -08002529 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002530
2531 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002532 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002533
Glenn Kasten000f0e32012-03-01 17:10:56 -08002534 // DUPLICATING
2535 // FIXME could this be made local to while loop?
2536 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002537
Glenn Kasten66fcab92012-02-24 14:59:21 -08002538 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002539 sleepTime = idleSleepTime;
2540
Glenn Kasten9f34a362012-03-20 16:46:41 -07002541 if (mType == MIXER) {
2542 sleepTimeShift = 0;
2543 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002544
Glenn Kasten83efdd02012-02-24 07:21:32 -08002545 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002546 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002547
Eric Laurentfeb0db62011-07-22 09:04:31 -07002548 acquireWakeLock();
2549
Mathias Agopian65ab4712010-07-14 17:59:35 -07002550 while (!exitPending())
2551 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002552 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002553
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002554 Vector< sp<EffectChain> > effectChains;
2555
Mathias Agopian65ab4712010-07-14 17:59:35 -07002556 processConfigEvents();
2557
Mathias Agopian65ab4712010-07-14 17:59:35 -07002558 { // scope for mLock
2559
2560 Mutex::Autolock _l(mLock);
2561
2562 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002563 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002564 }
2565
Glenn Kastenfa26a852012-03-06 11:28:04 -08002566 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002567
Mathias Agopian65ab4712010-07-14 17:59:35 -07002568 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002569 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002570 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002571 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002572
2573 threadLoop_standby();
2574
Mathias Agopian65ab4712010-07-14 17:59:35 -07002575 mStandby = true;
2576 mBytesWritten = 0;
2577 }
2578
Glenn Kasten3e074702012-02-28 18:40:35 -08002579 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002580 // we're about to wait, flush the binder command buffer
2581 IPCThreadState::self()->flushCommands();
2582
Glenn Kastenfa26a852012-03-06 11:28:04 -08002583 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002584
Mathias Agopian65ab4712010-07-14 17:59:35 -07002585 if (exitPending()) break;
2586
Eric Laurentfeb0db62011-07-22 09:04:31 -07002587 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002588 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002589 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002590 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002591 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002592 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002593
Eric Laurentda747442012-04-25 18:53:13 -07002594 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002595 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002596
Glenn Kasten37d825e2012-02-24 07:21:48 -08002597 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002598
Glenn Kasten000f0e32012-03-01 17:10:56 -08002599 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002600 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002601 if (mType == MIXER) {
2602 sleepTimeShift = 0;
2603 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002604
Mathias Agopian65ab4712010-07-14 17:59:35 -07002605 continue;
2606 }
2607 }
2608
Glenn Kasten81028042012-04-30 18:15:12 -07002609 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002610 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002611
2612 // prevent any changes in effect chain list and in each effect chain
2613 // during mixing and effect process as the audio buffers could be deleted
2614 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002615 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002616 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002617
Glenn Kastenfec279f2012-03-08 07:47:15 -08002618 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002619 threadLoop_mix();
2620 } else {
2621 threadLoop_sleepTime();
2622 }
2623
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002624 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002625 sleepTime = suspendSleepTimeUs();
2626 }
2627
2628 // only process effects if we're going to write
2629 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002630 for (size_t i = 0; i < effectChains.size(); i ++) {
2631 effectChains[i]->process_l();
2632 }
2633 }
2634
2635 // enable changes in effect chain
2636 unlockEffectChains(effectChains);
2637
2638 // sleepTime == 0 means we must write to audio hardware
2639 if (sleepTime == 0) {
2640
2641 threadLoop_write();
2642
2643if (mType == MIXER) {
2644 // write blocked detection
2645 nsecs_t now = systemTime();
2646 nsecs_t delta = now - mLastWriteTime;
2647 if (!mStandby && delta > maxPeriod) {
2648 mNumDelayedWrites++;
2649 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002650#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002651 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002652#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002653 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2654 ns2ms(delta), mNumDelayedWrites, this);
2655 lastWarning = now;
2656 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002657 }
2658}
2659
2660 mStandby = false;
2661 } else {
2662 usleep(sleepTime);
2663 }
2664
Glenn Kasten58912562012-04-03 10:45:00 -07002665 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002666 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002667 // same lock. This will also mutate and push a new fast mixer state.
2668 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002669 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002670
Glenn Kastenfa26a852012-03-06 11:28:04 -08002671 // FIXME I don't understand the need for this here;
2672 // it was in the original code but maybe the
2673 // assignment in saveOutputTracks() makes this unnecessary?
2674 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002675
2676 // Effect chains will be actually deleted here if they were removed from
2677 // mEffectChains list during mixing or effects processing
2678 effectChains.clear();
2679
2680 // FIXME Note that the above .clear() is no longer necessary since effectChains
2681 // is now local to this block, but will keep it for now (at least until merge done).
2682 }
2683
Glenn Kasten9f34a362012-03-20 16:46:41 -07002684 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2685 if (mType == MIXER || mType == DIRECT) {
2686 // put output stream into standby mode
2687 if (!mStandby) {
2688 mOutput->stream->common.standby(&mOutput->stream->common);
2689 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002690 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002691
2692 releaseWakeLock();
2693
2694 ALOGV("Thread %p type %d exiting", this, mType);
2695 return false;
2696}
2697
Glenn Kasten58912562012-04-03 10:45:00 -07002698void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2699{
Glenn Kasten58912562012-04-03 10:45:00 -07002700 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2701}
2702
2703void AudioFlinger::MixerThread::threadLoop_write()
2704{
2705 // FIXME we should only do one push per cycle; confirm this is true
2706 // Start the fast mixer if it's not already running
2707 if (mFastMixer != NULL) {
2708 FastMixerStateQueue *sq = mFastMixer->sq();
2709 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002710 if (state->mCommand != FastMixerState::MIX_WRITE &&
2711 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002712 if (state->mCommand == FastMixerState::COLD_IDLE) {
2713 int32_t old = android_atomic_inc(&mFastMixerFutex);
2714 if (old == -1) {
2715 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2716 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002717 if (mAudioWatchdog != 0) {
2718 mAudioWatchdog->resume();
2719 }
Glenn Kasten58912562012-04-03 10:45:00 -07002720 }
2721 state->mCommand = FastMixerState::MIX_WRITE;
2722 sq->end();
2723 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002724 if (kUseFastMixer == FastMixer_Dynamic) {
2725 mNormalSink = mPipeSink;
2726 }
Glenn Kasten58912562012-04-03 10:45:00 -07002727 } else {
2728 sq->end(false /*didModify*/);
2729 }
2730 }
2731 PlaybackThread::threadLoop_write();
2732}
2733
Glenn Kasten000f0e32012-03-01 17:10:56 -08002734// shared by MIXER and DIRECT, overridden by DUPLICATING
2735void AudioFlinger::PlaybackThread::threadLoop_write()
2736{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002737 // FIXME rewrite to reduce number of system calls
2738 mLastWriteTime = systemTime();
2739 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002740 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002741
Eric Laurent67c0a582012-05-01 19:31:12 -07002742 // If an NBAIO sink is present, use it to write the normal mixer's submix
2743 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002744#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002745 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002746#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002747 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002748#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002749 // update the setpoint when gScreenState changes
2750 uint32_t screenState = gScreenState;
2751 if (screenState != mScreenState) {
2752 mScreenState = screenState;
2753 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2754 if (pipe != NULL) {
2755 pipe->setAvgFrames((mScreenState & 1) ?
2756 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2757 }
2758 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002759 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002760#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002761 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002762#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002763 if (framesWritten > 0) {
2764 bytesWritten = framesWritten << mBitShift;
2765 } else {
2766 bytesWritten = framesWritten;
2767 }
2768 // otherwise use the HAL / AudioStreamOut directly
2769 } else {
2770 // Direct output thread.
2771 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002772 }
2773
Eric Laurent67c0a582012-05-01 19:31:12 -07002774 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002775 mNumWrites++;
2776 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002777}
2778
Glenn Kasten58912562012-04-03 10:45:00 -07002779void AudioFlinger::MixerThread::threadLoop_standby()
2780{
2781 // Idle the fast mixer if it's currently running
2782 if (mFastMixer != NULL) {
2783 FastMixerStateQueue *sq = mFastMixer->sq();
2784 FastMixerState *state = sq->begin();
2785 if (!(state->mCommand & FastMixerState::IDLE)) {
2786 state->mCommand = FastMixerState::COLD_IDLE;
2787 state->mColdFutexAddr = &mFastMixerFutex;
2788 state->mColdGen++;
2789 mFastMixerFutex = 0;
2790 sq->end();
2791 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2792 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002793 if (kUseFastMixer == FastMixer_Dynamic) {
2794 mNormalSink = mOutputSink;
2795 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002796 if (mAudioWatchdog != 0) {
2797 mAudioWatchdog->pause();
2798 }
Glenn Kasten58912562012-04-03 10:45:00 -07002799 } else {
2800 sq->end(false /*didModify*/);
2801 }
2802 }
2803 PlaybackThread::threadLoop_standby();
2804}
2805
Glenn Kasten000f0e32012-03-01 17:10:56 -08002806// shared by MIXER and DIRECT, overridden by DUPLICATING
2807void AudioFlinger::PlaybackThread::threadLoop_standby()
2808{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002809 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002810 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002811}
2812
2813void AudioFlinger::MixerThread::threadLoop_mix()
2814{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002815 // obtain the presentation timestamp of the next output buffer
2816 int64_t pts;
2817 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002818
John Grossman2c3b2da2012-08-02 17:08:54 -07002819 if (mNormalSink != 0) {
2820 status = mNormalSink->getNextWriteTimestamp(&pts);
2821 } else {
2822 status = mOutputSink->getNextWriteTimestamp(&pts);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002823 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002824
Glenn Kasten952eeb22012-03-06 11:30:57 -08002825 if (status != NO_ERROR) {
2826 pts = AudioBufferProvider::kInvalidPTS;
2827 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002828
Glenn Kasten952eeb22012-03-06 11:30:57 -08002829 // mix buffers...
2830 mAudioMixer->process(pts);
2831 // increase sleep time progressively when application underrun condition clears.
2832 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2833 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2834 // such that we would underrun the audio HAL.
2835 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2836 sleepTimeShift--;
2837 }
2838 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002839 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002840 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002841}
2842
2843void AudioFlinger::MixerThread::threadLoop_sleepTime()
2844{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002845 // If no tracks are ready, sleep once for the duration of an output
2846 // buffer size, then write 0s to the output
2847 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002848 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002849 sleepTime = activeSleepTime >> sleepTimeShift;
2850 if (sleepTime < kMinThreadSleepTimeUs) {
2851 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002852 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002853 // reduce sleep time in case of consecutive application underruns to avoid
2854 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2855 // duration we would end up writing less data than needed by the audio HAL if
2856 // the condition persists.
2857 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2858 sleepTimeShift++;
2859 }
2860 } else {
2861 sleepTime = idleSleepTime;
2862 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002863 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002864 memset (mMixBuffer, 0, mixBufferSize);
2865 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002866 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002867 }
2868 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002869}
2870
2871// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002872AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002873 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002874{
2875
Glenn Kasten29c23c32012-01-26 13:37:52 -08002876 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002877 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002878 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002879 size_t mixedTracks = 0;
2880 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002881 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002882 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002883 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002884
2885 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002886 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002887
Eric Laurent571d49c2010-08-11 05:20:11 -07002888 if (masterMute) {
2889 masterVolume = 0;
2890 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002891 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002892 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002893 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002894 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002895 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002896 masterVolume = (float)((v + (1 << 23)) >> 24);
2897 chain.clear();
2898 }
2899
Glenn Kasten288ed212012-04-25 17:52:27 -07002900 // prepare a new state to push
2901 FastMixerStateQueue *sq = NULL;
2902 FastMixerState *state = NULL;
2903 bool didModify = false;
2904 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2905 if (mFastMixer != NULL) {
2906 sq = mFastMixer->sq();
2907 state = sq->begin();
2908 }
2909
Mathias Agopian65ab4712010-07-14 17:59:35 -07002910 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002911 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002912 if (t == 0) continue;
2913
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002914 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002915 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002916
Glenn Kasten288ed212012-04-25 17:52:27 -07002917 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002918 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002919
2920 // It's theoretically possible (though unlikely) for a fast track to be created
2921 // and then removed within the same normal mix cycle. This is not a problem, as
2922 // the track never becomes active so it's fast mixer slot is never touched.
2923 // The converse, of removing an (active) track and then creating a new track
2924 // at the identical fast mixer slot within the same normal mix cycle,
2925 // is impossible because the slot isn't marked available until the end of each cycle.
2926 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002927 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2928 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002929 FastTrack *fastTrack = &state->mFastTracks[j];
2930
2931 // Determine whether the track is currently in underrun condition,
2932 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002933 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2934 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002935 uint32_t recentFull = (underruns.mBitFields.mFull -
2936 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2937 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2938 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2939 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2940 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2941 uint32_t recentUnderruns = recentPartial + recentEmpty;
2942 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002943 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002944 // or stopped which can occur when flush() is called while active
2945 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002946 track->mUnderrunCount += recentUnderruns;
2947 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002948
Glenn Kastend08f48c2012-05-01 18:14:02 -07002949 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002950 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002951 bool isActive = true;
2952 switch (track->mState) {
2953 case TrackBase::STOPPING_1:
2954 // track stays active in STOPPING_1 state until first underrun
2955 if (recentUnderruns > 0) {
2956 track->mState = TrackBase::STOPPING_2;
2957 }
2958 break;
2959 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002960 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002961 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002962 break;
2963 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002964 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002965 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002966 break;
2967 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002968 if (recentFull > 0 || recentPartial > 0) {
2969 // track has provided at least some frames recently: reset retry count
2970 track->mRetryCount = kMaxTrackRetries;
2971 }
2972 if (recentUnderruns == 0) {
2973 // no recent underruns: stay active
2974 break;
2975 }
2976 // there has recently been an underrun of some kind
2977 if (track->sharedBuffer() == 0) {
2978 // were any of the recent underruns "empty" (no frames available)?
2979 if (recentEmpty == 0) {
2980 // no, then ignore the partial underruns as they are allowed indefinitely
2981 break;
2982 }
2983 // there has recently been an "empty" underrun: decrement the retry counter
2984 if (--(track->mRetryCount) > 0) {
2985 break;
2986 }
2987 // indicate to client process that the track was disabled because of underrun;
2988 // it will then automatically call start() when data is available
2989 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2990 // remove from active list, but state remains ACTIVE [confusing but true]
2991 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002992 break;
2993 }
2994 // fall through
2995 case TrackBase::STOPPING_2:
2996 case TrackBase::PAUSED:
2997 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002998 case TrackBase::STOPPED:
2999 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07003000 // Check for presentation complete if track is inactive
3001 // We have consumed all the buffers of this track.
3002 // This would be incomplete if we auto-paused on underrun
3003 {
3004 size_t audioHALFrames =
3005 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3006 size_t framesWritten =
3007 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3008 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
3009 // track stays in active list until presentation is complete
3010 break;
3011 }
3012 }
3013 if (track->isStopping_2()) {
3014 track->mState = TrackBase::STOPPED;
3015 }
3016 if (track->isStopped()) {
3017 // Can't reset directly, as fast mixer is still polling this track
3018 // track->reset();
3019 // So instead mark this track as needing to be reset after push with ack
3020 resetMask |= 1 << i;
3021 }
3022 isActive = false;
3023 break;
3024 case TrackBase::IDLE:
3025 default:
3026 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003027 }
3028
3029 if (isActive) {
3030 // was it previously inactive?
3031 if (!(state->mTrackMask & (1 << j))) {
3032 ExtendedAudioBufferProvider *eabp = track;
3033 VolumeProvider *vp = track;
3034 fastTrack->mBufferProvider = eabp;
3035 fastTrack->mVolumeProvider = vp;
3036 fastTrack->mSampleRate = track->mSampleRate;
3037 fastTrack->mChannelMask = track->mChannelMask;
3038 fastTrack->mGeneration++;
3039 state->mTrackMask |= 1 << j;
3040 didModify = true;
3041 // no acknowledgement required for newly active tracks
3042 }
3043 // cache the combined master volume and stream type volume for fast mixer; this
3044 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3045 track->mCachedVolume = track->isMuted() ?
3046 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3047 ++fastTracks;
3048 } else {
3049 // was it previously active?
3050 if (state->mTrackMask & (1 << j)) {
3051 fastTrack->mBufferProvider = NULL;
3052 fastTrack->mGeneration++;
3053 state->mTrackMask &= ~(1 << j);
3054 didModify = true;
3055 // If any fast tracks were removed, we must wait for acknowledgement
3056 // because we're about to decrement the last sp<> on those tracks.
3057 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003058 } else {
3059 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003060 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003061 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003062 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003063 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003064 }
3065 continue;
3066 }
3067
3068 { // local variable scope to avoid goto warning
3069
Mathias Agopian65ab4712010-07-14 17:59:35 -07003070 audio_track_cblk_t* cblk = track->cblk();
3071
3072 // The first time a track is added we wait
3073 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003074 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003075 // make sure that we have enough frames to mix one full buffer.
3076 // enforce this condition only once to enable draining the buffer in case the client
3077 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003078 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003079 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003080 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003081 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003082 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003083 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003084 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003085 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003086 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003087 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003088 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003089 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003090 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3091 // the minimum track buffer size is normally twice the number of frames necessary
3092 // to fill one buffer and the resampler should not leave more than one buffer worth
3093 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003094 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003095 }
3096 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003097 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003098 !track->isPaused() && !track->isTerminated())
3099 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003100 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003101
3102 mixedTracks++;
3103
3104 // track->mainBuffer() != mMixBuffer means there is an effect chain
3105 // connected to the track
3106 chain.clear();
3107 if (track->mainBuffer() != mMixBuffer) {
3108 chain = getEffectChain_l(track->sessionId());
3109 // Delegate volume control to effect in track effect chain if needed
3110 if (chain != 0) {
3111 tracksWithEffect++;
3112 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003113 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003114 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003115 }
3116 }
3117
3118
3119 int param = AudioMixer::VOLUME;
3120 if (track->mFillingUpStatus == Track::FS_FILLED) {
3121 // no ramp for the first volume setting
3122 track->mFillingUpStatus = Track::FS_ACTIVE;
3123 if (track->mState == TrackBase::RESUMING) {
3124 track->mState = TrackBase::ACTIVE;
3125 param = AudioMixer::RAMP_VOLUME;
3126 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003127 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003128 } else if (cblk->server != 0) {
3129 // If the track is stopped before the first frame was mixed,
3130 // do not apply ramp
3131 param = AudioMixer::RAMP_VOLUME;
3132 }
3133
3134 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003135 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003136 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003137 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003138 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003139 if (track->isPausing()) {
3140 track->setPaused();
3141 }
3142 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003143
Mathias Agopian65ab4712010-07-14 17:59:35 -07003144 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003145 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003146 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003147 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003148 vl = vlr & 0xFFFF;
3149 vr = vlr >> 16;
3150 // track volumes come from shared memory, so can't be trusted and must be clamped
3151 if (vl > MAX_GAIN_INT) {
3152 ALOGV("Track left volume out of range: %04X", vl);
3153 vl = MAX_GAIN_INT;
3154 }
3155 if (vr > MAX_GAIN_INT) {
3156 ALOGV("Track right volume out of range: %04X", vr);
3157 vr = MAX_GAIN_INT;
3158 }
3159 // now apply the master volume and stream type volume
3160 vl = (uint32_t)(v * vl) << 12;
3161 vr = (uint32_t)(v * vr) << 12;
3162 // assuming master volume and stream type volume each go up to 1.0,
3163 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003164
Glenn Kasten05632a52012-01-03 14:22:33 -08003165 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3166 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003167 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003168 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003169 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003170 }
3171 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003172 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003173 // Delegate volume control to effect in track effect chain if needed
3174 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3175 // Do not ramp volume if volume is controlled by effect
3176 param = AudioMixer::VOLUME;
3177 track->mHasVolumeController = true;
3178 } else {
3179 // force no volume ramp when volume controller was just disabled or removed
3180 // from effect chain to avoid volume spike
3181 if (track->mHasVolumeController) {
3182 param = AudioMixer::VOLUME;
3183 }
3184 track->mHasVolumeController = false;
3185 }
3186
3187 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003188 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003189 vl = (vl + (1 << 11)) >> 12;
3190 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3191 vr = (vr + (1 << 11)) >> 12;
3192 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003193
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003194 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 -07003195
Mathias Agopian65ab4712010-07-14 17:59:35 -07003196 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003197 mAudioMixer->setBufferProvider(name, track);
3198 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003199
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003200 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3201 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3202 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003203 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003204 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003205 AudioMixer::TRACK,
3206 AudioMixer::FORMAT, (void *)track->format());
3207 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003208 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003209 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003210 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003211 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003212 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003213 AudioMixer::RESAMPLE,
3214 AudioMixer::SAMPLE_RATE,
3215 (void *)(cblk->sampleRate));
3216 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003217 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003218 AudioMixer::TRACK,
3219 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3220 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003221 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003222 AudioMixer::TRACK,
3223 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3224
3225 // reset retry count
3226 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003227
Eric Laurent27741442012-01-17 19:20:12 -08003228 // If one track is ready, set the mixer ready if:
3229 // - the mixer was not ready during previous round OR
3230 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003231 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003232 mixerStatus != MIXER_TRACKS_ENABLED) {
3233 mixerStatus = MIXER_TRACKS_READY;
3234 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003235 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003236 // clear effect chain input buffer if an active track underruns to avoid sending
3237 // previous audio buffer again to effects
3238 chain = getEffectChain_l(track->sessionId());
3239 if (chain != 0) {
3240 chain->clearInputBuffer();
3241 }
3242
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003243 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003244 if ((track->sharedBuffer() != 0) ||
Eric Laurent83faee02012-04-27 18:24:29 -07003245 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003246 // We have consumed all the buffers of this track.
3247 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003248 // TODO: use actual buffer filling status instead of latency when available from
3249 // audio HAL
3250 size_t audioHALFrames =
3251 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3252 size_t framesWritten =
3253 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3254 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003255 if (track->isStopped()) {
3256 track->reset();
3257 }
Eric Laurenta011e352012-03-29 15:51:43 -07003258 tracksToRemove->add(track);
3259 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003260 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003261 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003262 // No buffers for this track. Give it a few chances to
3263 // fill a buffer, then remove it from active list.
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003264 if (--(track->mRetryCount) <= 0 || track->isTerminated()) {
3265 ALOGV_IF(track->mRetryCount <= 0, "BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003266 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003267 // indicate to client process that the track was disabled because of underrun;
3268 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003269 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003270 // If one track is not ready, mark the mixer also not ready if:
3271 // - the mixer was ready during previous round OR
3272 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003273 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003274 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003275 mixerStatus = MIXER_TRACKS_ENABLED;
3276 }
3277 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003278 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003279 }
Glenn Kasten58912562012-04-03 10:45:00 -07003280
3281 } // local variable scope to avoid goto warning
3282track_is_ready: ;
3283
Mathias Agopian65ab4712010-07-14 17:59:35 -07003284 }
3285
Glenn Kasten288ed212012-04-25 17:52:27 -07003286 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003287 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003288 if (didModify) {
3289 state->mFastTracksGen++;
3290 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3291 if (kUseFastMixer == FastMixer_Dynamic &&
3292 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3293 state->mCommand = FastMixerState::COLD_IDLE;
3294 state->mColdFutexAddr = &mFastMixerFutex;
3295 state->mColdGen++;
3296 mFastMixerFutex = 0;
3297 if (kUseFastMixer == FastMixer_Dynamic) {
3298 mNormalSink = mOutputSink;
3299 }
3300 // If we go into cold idle, need to wait for acknowledgement
3301 // so that fast mixer stops doing I/O.
3302 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003303 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003304 }
3305 sq->end();
3306 }
3307 if (sq != NULL) {
3308 sq->end(didModify);
3309 sq->push(block);
3310 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07003311 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3312 mAudioWatchdog->pause();
3313 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003314
3315 // Now perform the deferred reset on fast tracks that have stopped
3316 while (resetMask != 0) {
3317 size_t i = __builtin_ctz(resetMask);
3318 ALOG_ASSERT(i < count);
3319 resetMask &= ~(1 << i);
3320 sp<Track> t = mActiveTracks[i].promote();
3321 if (t == 0) continue;
3322 Track* track = t.get();
3323 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3324 track->reset();
3325 }
Glenn Kasten58912562012-04-03 10:45:00 -07003326
Mathias Agopian65ab4712010-07-14 17:59:35 -07003327 // remove all the tracks that need to be...
3328 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003329 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003330 for (size_t i=0 ; i<count ; i++) {
3331 const sp<Track>& track = tracksToRemove->itemAt(i);
3332 mActiveTracks.remove(track);
3333 if (track->mainBuffer() != mMixBuffer) {
3334 chain = getEffectChain_l(track->sessionId());
3335 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003336 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003337 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003338 }
3339 }
3340 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003341 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003342 }
3343 }
3344 }
3345
3346 // mix buffer must be cleared if all tracks are connected to an
3347 // effect chain as in this case the mixer will not write to
3348 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003349 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3350 // FIXME as a performance optimization, should remember previous zero status
3351 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003352 }
3353
Glenn Kasten58912562012-04-03 10:45:00 -07003354 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003355 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003356 if (fastTracks > 0) {
3357 mixerStatus = MIXER_TRACKS_READY;
3358 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003359 return mixerStatus;
3360}
3361
Glenn Kasten66fcab92012-02-24 14:59:21 -08003362/*
3363The derived values that are cached:
3364 - mixBufferSize from frame count * frame size
3365 - activeSleepTime from activeSleepTimeUs()
3366 - idleSleepTime from idleSleepTimeUs()
3367 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3368 - maxPeriod from frame count and sample rate (MIXER only)
3369
3370The parameters that affect these derived values are:
3371 - frame count
3372 - frame size
3373 - sample rate
3374 - device type: A2DP or not
3375 - device latency
3376 - format: PCM or not
3377 - active sleep time
3378 - idle sleep time
3379*/
3380
3381void AudioFlinger::PlaybackThread::cacheParameters_l()
3382{
Glenn Kasten58912562012-04-03 10:45:00 -07003383 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003384 activeSleepTime = activeSleepTimeUs();
3385 idleSleepTime = idleSleepTimeUs();
3386}
3387
Eric Laurent22167852012-06-20 12:26:32 -07003388void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003389{
Steve Block3856b092011-10-20 11:56:00 +01003390 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003391 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003392 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003393
Mathias Agopian65ab4712010-07-14 17:59:35 -07003394 size_t size = mTracks.size();
3395 for (size_t i = 0; i < size; i++) {
3396 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003397 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003398 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003399 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003400 }
3401 }
3402}
3403
Mathias Agopian65ab4712010-07-14 17:59:35 -07003404// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003405int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003406{
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003407 return mAudioMixer->getTrackName(channelMask, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003408}
3409
3410// deleteTrackName_l() must be called with ThreadBase::mLock held
3411void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3412{
Steve Block3856b092011-10-20 11:56:00 +01003413 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003414 mAudioMixer->deleteTrackName(name);
3415}
3416
3417// checkForNewParameters_l() must be called with ThreadBase::mLock held
3418bool AudioFlinger::MixerThread::checkForNewParameters_l()
3419{
Glenn Kasten58912562012-04-03 10:45:00 -07003420 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3421 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003422 bool reconfig = false;
3423
3424 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003425
3426 if (mFastMixer != NULL) {
3427 FastMixerStateQueue *sq = mFastMixer->sq();
3428 FastMixerState *state = sq->begin();
3429 if (!(state->mCommand & FastMixerState::IDLE)) {
3430 previousCommand = state->mCommand;
3431 state->mCommand = FastMixerState::HOT_IDLE;
3432 sq->end();
3433 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3434 } else {
3435 sq->end(false /*didModify*/);
3436 }
3437 }
3438
Mathias Agopian65ab4712010-07-14 17:59:35 -07003439 status_t status = NO_ERROR;
3440 String8 keyValuePair = mNewParameters[0];
3441 AudioParameter param = AudioParameter(keyValuePair);
3442 int value;
3443
3444 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3445 reconfig = true;
3446 }
3447 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003448 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003449 status = BAD_VALUE;
3450 } else {
3451 reconfig = true;
3452 }
3453 }
3454 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003455 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003456 status = BAD_VALUE;
3457 } else {
3458 reconfig = true;
3459 }
3460 }
3461 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3462 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003463 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003464 // if frame count is changed after track creation
3465 if (!mTracks.isEmpty()) {
3466 status = INVALID_OPERATION;
3467 } else {
3468 reconfig = true;
3469 }
3470 }
3471 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003472#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003473 // when changing the audio output device, call addBatteryData to notify
3474 // the change
Eric Laurentf1c04f92012-08-28 14:26:53 -07003475 if (mOutDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003476 uint32_t params = 0;
3477 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003478 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003479 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3480 }
3481
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003482 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003483 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003484 // check if any other device (except speaker) is on
3485 if (value & deviceWithoutSpeaker ) {
3486 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3487 }
3488
3489 if (params != 0) {
3490 addBatteryData(params);
3491 }
3492 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003493#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003494
Mathias Agopian65ab4712010-07-14 17:59:35 -07003495 // forward device change to effects that have requested to be
3496 // aware of attached audio device.
Eric Laurentf1c04f92012-08-28 14:26:53 -07003497 mOutDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003498 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07003499 mEffectChains[i]->setDevice_l(mOutDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003500 }
3501 }
3502
3503 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003504 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003505 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003506 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003507 mOutput->stream->common.standby(&mOutput->stream->common);
3508 mStandby = true;
3509 mBytesWritten = 0;
3510 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003511 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003512 }
3513 if (status == NO_ERROR && reconfig) {
3514 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003515 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3516 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003517 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003518 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003519 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003520 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003521 if (name < 0) break;
3522 mTracks[i]->mName = name;
3523 // limit track sample rate to 2 x new output sample rate
3524 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3525 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3526 }
3527 }
Eric Laurent896adcd2012-09-13 11:18:23 -07003528 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003529 }
3530 }
3531
3532 mNewParameters.removeAt(0);
3533
3534 mParamStatus = status;
3535 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003536 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3537 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003538 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003539 }
Glenn Kasten58912562012-04-03 10:45:00 -07003540
3541 if (!(previousCommand & FastMixerState::IDLE)) {
3542 ALOG_ASSERT(mFastMixer != NULL);
3543 FastMixerStateQueue *sq = mFastMixer->sq();
3544 FastMixerState *state = sq->begin();
3545 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3546 state->mCommand = previousCommand;
3547 sq->end();
3548 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3549 }
3550
Mathias Agopian65ab4712010-07-14 17:59:35 -07003551 return reconfig;
3552}
3553
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07003554void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003555{
3556 const size_t SIZE = 256;
3557 char buffer[SIZE];
3558 String8 result;
3559
3560 PlaybackThread::dumpInternals(fd, args);
3561
3562 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3563 result.append(buffer);
3564 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003565
3566 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3567 FastMixerDumpState copy = mFastMixerDumpState;
3568 copy.dump(fd);
3569
Glenn Kasten39993082012-05-31 13:40:27 -07003570#ifdef STATE_QUEUE_DUMP
3571 // Similar for state queue
3572 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3573 observerCopy.dump(fd);
3574 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3575 mutatorCopy.dump(fd);
3576#endif
3577
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003578 // Write the tee output to a .wav file
3579 NBAIO_Source *teeSource = mTeeSource.get();
3580 if (teeSource != NULL) {
3581 char teePath[64];
3582 struct timeval tv;
3583 gettimeofday(&tv, NULL);
3584 struct tm tm;
3585 localtime_r(&tv.tv_sec, &tm);
3586 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3587 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3588 if (teeFd >= 0) {
3589 char wavHeader[44];
3590 memcpy(wavHeader,
3591 "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",
3592 sizeof(wavHeader));
3593 NBAIO_Format format = teeSource->format();
3594 unsigned channelCount = Format_channelCount(format);
3595 ALOG_ASSERT(channelCount <= FCC_2);
3596 unsigned sampleRate = Format_sampleRate(format);
3597 wavHeader[22] = channelCount; // number of channels
3598 wavHeader[24] = sampleRate; // sample rate
3599 wavHeader[25] = sampleRate >> 8;
3600 wavHeader[32] = channelCount * 2; // block alignment
3601 write(teeFd, wavHeader, sizeof(wavHeader));
3602 size_t total = 0;
3603 bool firstRead = true;
3604 for (;;) {
3605#define TEE_SINK_READ 1024
3606 short buffer[TEE_SINK_READ * FCC_2];
3607 size_t count = TEE_SINK_READ;
John Grossman2c3b2da2012-08-02 17:08:54 -07003608 ssize_t actual = teeSource->read(buffer, count,
3609 AudioBufferProvider::kInvalidPTS);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003610 bool wasFirstRead = firstRead;
3611 firstRead = false;
3612 if (actual <= 0) {
3613 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3614 continue;
3615 }
3616 break;
3617 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003618 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003619 write(teeFd, buffer, actual * channelCount * sizeof(short));
3620 total += actual;
3621 }
3622 lseek(teeFd, (off_t) 4, SEEK_SET);
3623 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3624 write(teeFd, &temp, sizeof(temp));
3625 lseek(teeFd, (off_t) 40, SEEK_SET);
3626 temp = total * channelCount * sizeof(short);
3627 write(teeFd, &temp, sizeof(temp));
3628 close(teeFd);
3629 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3630 } else {
3631 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3632 }
3633 }
3634
Glenn Kastenc15d6652012-05-30 14:52:57 -07003635 if (mAudioWatchdog != 0) {
3636 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3637 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3638 wdCopy.dump(fd);
3639 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003640}
3641
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003642uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003643{
Glenn Kasten58912562012-04-03 10:45:00 -07003644 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003645}
3646
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003647uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003648{
Glenn Kasten58912562012-04-03 10:45:00 -07003649 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003650}
3651
Glenn Kasten66fcab92012-02-24 14:59:21 -08003652void AudioFlinger::MixerThread::cacheParameters_l()
3653{
3654 PlaybackThread::cacheParameters_l();
3655
3656 // FIXME: Relaxed timing because of a certain device that can't meet latency
3657 // Should be reduced to 2x after the vendor fixes the driver issue
3658 // increase threshold again due to low power audio mode. The way this warning
3659 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003660 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003661}
3662
Mathias Agopian65ab4712010-07-14 17:59:35 -07003663// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003664AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003665 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003666 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003667 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003668{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003669}
3670
3671AudioFlinger::DirectOutputThread::~DirectOutputThread()
3672{
3673}
3674
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003675AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3676 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003677)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003678{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003679 sp<Track> trackToRemove;
3680
Glenn Kastenfec279f2012-03-08 07:47:15 -08003681 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003682
Glenn Kasten952eeb22012-03-06 11:30:57 -08003683 // find out which tracks need to be processed
3684 if (mActiveTracks.size() != 0) {
3685 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003686 // The track died recently
3687 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003688
Glenn Kasten952eeb22012-03-06 11:30:57 -08003689 Track* const track = t.get();
3690 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003691
Glenn Kasten952eeb22012-03-06 11:30:57 -08003692 // The first time a track is added we wait
3693 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003694 uint32_t minFrames;
3695 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3696 minFrames = mNormalFrameCount;
3697 } else {
3698 minFrames = 1;
3699 }
3700 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003701 !track->isPaused() && !track->isTerminated())
3702 {
3703 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003704
Glenn Kasten952eeb22012-03-06 11:30:57 -08003705 if (track->mFillingUpStatus == Track::FS_FILLED) {
3706 track->mFillingUpStatus = Track::FS_ACTIVE;
3707 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003708 if (track->mState == TrackBase::RESUMING) {
3709 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003710 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003711 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003712
Glenn Kasten952eeb22012-03-06 11:30:57 -08003713 // compute volume for this track
3714 float left, right;
3715 if (track->isMuted() || mMasterMute || track->isPausing() ||
3716 mStreamTypes[track->streamType()].mute) {
3717 left = right = 0;
3718 if (track->isPausing()) {
3719 track->setPaused();
3720 }
3721 } else {
3722 float typeVolume = mStreamTypes[track->streamType()].volume;
3723 float v = mMasterVolume * typeVolume;
3724 uint32_t vlr = cblk->getVolumeLR();
3725 float v_clamped = v * (vlr & 0xFFFF);
3726 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3727 left = v_clamped/MAX_GAIN;
3728 v_clamped = v * (vlr >> 16);
3729 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3730 right = v_clamped/MAX_GAIN;
3731 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003732
Glenn Kasten952eeb22012-03-06 11:30:57 -08003733 if (left != mLeftVolFloat || right != mRightVolFloat) {
3734 mLeftVolFloat = left;
3735 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003736
Glenn Kasten952eeb22012-03-06 11:30:57 -08003737 // Convert volumes from float to 8.24
3738 uint32_t vl = (uint32_t)(left * (1 << 24));
3739 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003740
Glenn Kasten952eeb22012-03-06 11:30:57 -08003741 // Delegate volume control to effect in track effect chain if needed
3742 // only one effect chain can be present on DirectOutputThread, so if
3743 // there is one, the track is connected to it
3744 if (!mEffectChains.isEmpty()) {
3745 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003746 mEffectChains[0]->setVolume_l(&vl, &vr);
3747 left = (float)vl / (1 << 24);
3748 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003749 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003750 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003751 }
3752
3753 // reset retry count
3754 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003755 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003756 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003757 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003758 // clear effect chain input buffer if an active track underruns to avoid sending
3759 // previous audio buffer again to effects
3760 if (!mEffectChains.isEmpty()) {
3761 mEffectChains[0]->clearInputBuffer();
3762 }
3763
Glenn Kasten952eeb22012-03-06 11:30:57 -08003764 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003765 if ((track->sharedBuffer() != 0) ||
Eric Laurent67c0a582012-05-01 19:31:12 -07003766 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003767 // We have consumed all the buffers of this track.
3768 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003769 // TODO: implement behavior for compressed audio
3770 size_t audioHALFrames =
3771 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3772 size_t framesWritten =
3773 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3774 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003775 if (track->isStopped()) {
3776 track->reset();
3777 }
Eric Laurenta011e352012-03-29 15:51:43 -07003778 trackToRemove = track;
3779 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003780 } else {
3781 // No buffers for this track. Give it a few chances to
3782 // fill a buffer, then remove it from active list.
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003783 if (--(track->mRetryCount) <= 0 || track->isTerminated()) {
3784 ALOGV_IF(track->mRetryCount <= 0, "BUFFER TIMEOUT: remove(%d) from active list", track->name());
Glenn Kasten952eeb22012-03-06 11:30:57 -08003785 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003786 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003787 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003788 }
3789 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003790 }
3791 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003792
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003793 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003794 // remove all the tracks that need to be...
3795 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003796 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003797 mActiveTracks.remove(trackToRemove);
3798 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003799 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003800 trackToRemove->sessionId());
3801 mEffectChains[0]->decActiveTrackCnt();
3802 }
3803 if (trackToRemove->isTerminated()) {
3804 removeTrack_l(trackToRemove);
3805 }
3806 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003807
Glenn Kastenfec279f2012-03-08 07:47:15 -08003808 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003809}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003810
Glenn Kasten000f0e32012-03-01 17:10:56 -08003811void AudioFlinger::DirectOutputThread::threadLoop_mix()
3812{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003813 AudioBufferProvider::Buffer buffer;
3814 size_t frameCount = mFrameCount;
3815 int8_t *curBuf = (int8_t *)mMixBuffer;
3816 // output audio to hardware
3817 while (frameCount) {
3818 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003819 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003820 if (CC_UNLIKELY(buffer.raw == NULL)) {
3821 memset(curBuf, 0, frameCount * mFrameSize);
3822 break;
3823 }
3824 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3825 frameCount -= buffer.frameCount;
3826 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003827 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003828 }
3829 sleepTime = 0;
3830 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003831 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003832
Glenn Kasten000f0e32012-03-01 17:10:56 -08003833}
3834
3835void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3836{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003837 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003838 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003839 sleepTime = activeSleepTime;
3840 } else {
3841 sleepTime = idleSleepTime;
3842 }
3843 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003844 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003845 sleepTime = 0;
3846 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003847}
3848
3849// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003850int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3851 int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003852{
3853 return 0;
3854}
3855
3856// deleteTrackName_l() must be called with ThreadBase::mLock held
3857void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3858{
3859}
3860
3861// checkForNewParameters_l() must be called with ThreadBase::mLock held
3862bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3863{
3864 bool reconfig = false;
3865
3866 while (!mNewParameters.isEmpty()) {
3867 status_t status = NO_ERROR;
3868 String8 keyValuePair = mNewParameters[0];
3869 AudioParameter param = AudioParameter(keyValuePair);
3870 int value;
3871
3872 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3873 // do not accept frame count changes if tracks are open as the track buffer
3874 // size depends on frame count and correct behavior would not be garantied
3875 // if frame count is changed after track creation
3876 if (!mTracks.isEmpty()) {
3877 status = INVALID_OPERATION;
3878 } else {
3879 reconfig = true;
3880 }
3881 }
3882 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003883 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003884 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003885 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003886 mOutput->stream->common.standby(&mOutput->stream->common);
3887 mStandby = true;
3888 mBytesWritten = 0;
3889 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003890 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003891 }
3892 if (status == NO_ERROR && reconfig) {
3893 readOutputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07003894 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003895 }
3896 }
3897
3898 mNewParameters.removeAt(0);
3899
3900 mParamStatus = status;
3901 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003902 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3903 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003904 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003905 }
3906 return reconfig;
3907}
3908
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003909uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003910{
3911 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003912 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003913 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003914 } else {
3915 time = 10000;
3916 }
3917 return time;
3918}
3919
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003920uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() 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 Laurent60e18242010-07-29 06:50:24 -07003924 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
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::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003932{
3933 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003934 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003935 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3936 } else {
3937 time = 10000;
3938 }
3939 return time;
3940}
3941
Glenn Kasten66fcab92012-02-24 14:59:21 -08003942void AudioFlinger::DirectOutputThread::cacheParameters_l()
3943{
3944 PlaybackThread::cacheParameters_l();
3945
3946 // use shorter standby delay as on normal output to release
3947 // hardware resources as soon as possible
3948 standbyDelay = microseconds(activeSleepTime*2);
3949}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003950
Mathias Agopian65ab4712010-07-14 17:59:35 -07003951// ----------------------------------------------------------------------------
3952
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003953AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003954 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Eric Laurentf1c04f92012-08-28 14:26:53 -07003955 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), DUPLICATING),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003956 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003957{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003958 addOutputTrack(mainThread);
3959}
3960
3961AudioFlinger::DuplicatingThread::~DuplicatingThread()
3962{
3963 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3964 mOutputTracks[i]->destroy();
3965 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003966}
3967
Glenn Kasten000f0e32012-03-01 17:10:56 -08003968void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003969{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003970 // mix buffers...
3971 if (outputsReady(outputTracks)) {
3972 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3973 } else {
3974 memset(mMixBuffer, 0, mixBufferSize);
3975 }
3976 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003977 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003978 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003979}
3980
3981void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3982{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003983 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003984 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003985 sleepTime = activeSleepTime;
3986 } else {
3987 sleepTime = idleSleepTime;
3988 }
3989 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003990 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3991 writeFrames = mNormalFrameCount;
3992 memset(mMixBuffer, 0, mixBufferSize);
3993 } else {
3994 // flush remaining overflow buffers in output tracks
3995 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003996 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003997 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003998 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003999}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004000
Glenn Kasten000f0e32012-03-01 17:10:56 -08004001void AudioFlinger::DuplicatingThread::threadLoop_write()
4002{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004003 for (size_t i = 0; i < outputTracks.size(); i++) {
4004 outputTracks[i]->write(mMixBuffer, writeFrames);
4005 }
4006 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004007}
Glenn Kasten688a6402012-02-29 07:57:06 -08004008
Glenn Kasten000f0e32012-03-01 17:10:56 -08004009void AudioFlinger::DuplicatingThread::threadLoop_standby()
4010{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004011 // DuplicatingThread implements standby by stopping all tracks
4012 for (size_t i = 0; i < outputTracks.size(); i++) {
4013 outputTracks[i]->stop();
4014 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004015}
4016
Glenn Kastenfa26a852012-03-06 11:28:04 -08004017void AudioFlinger::DuplicatingThread::saveOutputTracks()
4018{
4019 outputTracks = mOutputTracks;
4020}
4021
4022void AudioFlinger::DuplicatingThread::clearOutputTracks()
4023{
4024 outputTracks.clear();
4025}
4026
Mathias Agopian65ab4712010-07-14 17:59:35 -07004027void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4028{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004029 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004030 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004031 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004032 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004033 this,
4034 mSampleRate,
4035 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004036 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004037 frameCount);
4038 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004039 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004040 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004041 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004042 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004043 }
4044}
4045
4046void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4047{
4048 Mutex::Autolock _l(mLock);
4049 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004050 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004051 mOutputTracks[i]->destroy();
4052 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004053 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004054 return;
4055 }
4056 }
Steve Block3856b092011-10-20 11:56:00 +01004057 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004058}
4059
Glenn Kasten438b0362012-03-06 11:24:48 -08004060// caller must hold mLock
4061void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004062{
4063 mWaitTimeMs = UINT_MAX;
4064 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4065 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004066 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004067 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4068 if (waitTimeMs < mWaitTimeMs) {
4069 mWaitTimeMs = waitTimeMs;
4070 }
4071 }
4072 }
4073}
4074
4075
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004076bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004077{
4078 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004079 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004080 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004081 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004082 return false;
4083 }
4084 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004085 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004086 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004087 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004088 return false;
4089 }
4090 }
4091 return true;
4092}
4093
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004094uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004095{
4096 return (mWaitTimeMs * 1000) / 2;
4097}
4098
Glenn Kasten66fcab92012-02-24 14:59:21 -08004099void AudioFlinger::DuplicatingThread::cacheParameters_l()
4100{
4101 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4102 updateWaitTime_l();
4103
4104 MixerThread::cacheParameters_l();
4105}
4106
Mathias Agopian65ab4712010-07-14 17:59:35 -07004107// ----------------------------------------------------------------------------
4108
4109// TrackBase constructor must be called with AudioFlinger::mLock held
4110AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004111 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004112 const sp<Client>& client,
4113 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004114 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004115 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004116 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004117 const sp<IMemory>& sharedBuffer,
4118 int sessionId)
4119 : RefBase(),
4120 mThread(thread),
4121 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004122 mCblk(NULL),
4123 // mBuffer
4124 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004125 mFrameCount(0),
4126 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004127 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004128 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004129 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004130 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004131 // mChannelCount
4132 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004133{
Steve Block3856b092011-10-20 11:56:00 +01004134 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004135
Steve Blockb8a80522011-12-20 16:23:08 +00004136 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004137 size_t size = sizeof(audio_track_cblk_t);
4138 uint8_t channelCount = popcount(channelMask);
4139 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4140 if (sharedBuffer == 0) {
4141 size += bufferSize;
4142 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004143
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004144 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004145 mCblkMemory = client->heap()->allocate(size);
4146 if (mCblkMemory != 0) {
4147 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004148 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004149 new(mCblk) audio_track_cblk_t();
4150 // clear all buffers
4151 mCblk->frameCount = frameCount;
4152 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004153// uncomment the following lines to quickly test 32-bit wraparound
4154// mCblk->user = 0xffff0000;
4155// mCblk->server = 0xffff0000;
4156// mCblk->userBase = 0xffff0000;
4157// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004158 mChannelCount = channelCount;
4159 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004160 if (sharedBuffer == 0) {
4161 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4162 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4163 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004164 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004165 mCblk->flags = CBLK_UNDERRUN_ON;
4166 } else {
4167 mBuffer = sharedBuffer->pointer();
4168 }
4169 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4170 }
4171 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004172 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004173 client->heap()->dump("AudioTrack");
4174 return;
4175 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004176 } else {
4177 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004178 // construct the shared structure in-place.
4179 new(mCblk) audio_track_cblk_t();
4180 // clear all buffers
4181 mCblk->frameCount = frameCount;
4182 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004183// uncomment the following lines to quickly test 32-bit wraparound
4184// mCblk->user = 0xffff0000;
4185// mCblk->server = 0xffff0000;
4186// mCblk->userBase = 0xffff0000;
4187// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004188 mChannelCount = channelCount;
4189 mChannelMask = channelMask;
4190 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4191 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4192 // Force underrun condition to avoid false underrun callback until first data is
4193 // written to buffer (other flags are cleared)
4194 mCblk->flags = CBLK_UNDERRUN_ON;
4195 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004196 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004197}
4198
4199AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4200{
Glenn Kastena0d68332012-01-27 16:47:15 -08004201 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004202 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004204 } else {
4205 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004206 }
4207 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004208 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004209 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004210 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004211 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004212 // If the client's reference count drops to zero, the associated destructor
4213 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4214 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004215 mClient.clear();
4216 }
4217}
4218
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004219// AudioBufferProvider interface
4220// getNextBuffer() = 0;
4221// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004222void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4223{
Glenn Kastene0feee32011-12-13 11:53:26 -08004224 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004225 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004226 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004227 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004228 buffer->frameCount = 0;
4229}
4230
4231bool AudioFlinger::ThreadBase::TrackBase::step() {
4232 bool result;
4233 audio_track_cblk_t* cblk = this->cblk();
4234
4235 result = cblk->stepServer(mFrameCount);
4236 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004237 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004238 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004239 }
4240 return result;
4241}
4242
4243void AudioFlinger::ThreadBase::TrackBase::reset() {
4244 audio_track_cblk_t* cblk = this->cblk();
4245
4246 cblk->user = 0;
4247 cblk->server = 0;
4248 cblk->userBase = 0;
4249 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004250 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004251 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004252}
4253
Mathias Agopian65ab4712010-07-14 17:59:35 -07004254int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4255 return (int)mCblk->sampleRate;
4256}
4257
Mathias Agopian65ab4712010-07-14 17:59:35 -07004258void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4259 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004260 size_t frameSize = cblk->frameSize;
4261 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4262 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004263
4264 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004265 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4266 "TrackBase::getBuffer buffer out of range:\n"
4267 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4268 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004269 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004270 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004271
4272 return bufferStart;
4273}
4274
Eric Laurenta011e352012-03-29 15:51:43 -07004275status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4276{
4277 mSyncEvents.add(event);
4278 return NO_ERROR;
4279}
4280
Mathias Agopian65ab4712010-07-14 17:59:35 -07004281// ----------------------------------------------------------------------------
4282
4283// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4284AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004285 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004286 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004287 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004288 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004289 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004290 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004291 int frameCount,
4292 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004293 int sessionId,
4294 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004295 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004296 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004297 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004298 // mRetryCount initialized later when needed
4299 mSharedBuffer(sharedBuffer),
4300 mStreamType(streamType),
4301 mName(-1), // see note below
4302 mMainBuffer(thread->mixBuffer()),
4303 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004304 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004305 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004306 mFlags(flags),
4307 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004308 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004309 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004310{
4311 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004312 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4313 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004314 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004315 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07004316 mName = thread->getTrackName_l(channelMask, sessionId);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004317 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004318 if (mName < 0) {
4319 ALOGE("no more track names available");
4320 return;
4321 }
4322 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004323 if (flags & IAudioFlinger::TRACK_FAST) {
4324 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4325 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4326 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004327 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004328 // FIXME This is too eager. We allocate a fast track index before the
4329 // fast track becomes active. Since fast tracks are a scarce resource,
4330 // this means we are potentially denying other more important fast tracks from
4331 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004332 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004333 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004334 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004335 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004336 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004337 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004338 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004339 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004340}
4341
4342AudioFlinger::PlaybackThread::Track::~Track()
4343{
Steve Block3856b092011-10-20 11:56:00 +01004344 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004345}
4346
4347void AudioFlinger::PlaybackThread::Track::destroy()
4348{
4349 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4350 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004351 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004352 // we must acquire a strong reference on this Track before locking mLock
4353 // here so that the destructor is called only when exiting this function.
4354 // On the other hand, as long as Track::destroy() is only called by
4355 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4356 // this Track with its member mTrack.
4357 sp<Track> keep(this);
4358 { // scope for mLock
4359 sp<ThreadBase> thread = mThread.promote();
4360 if (thread != 0) {
4361 if (!isOutputTrack()) {
4362 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004363 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004364
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004365#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004366 // to track the speaker usage
4367 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004368#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004369 }
4370 AudioSystem::releaseOutput(thread->id());
4371 }
4372 Mutex::Autolock _l(thread->mLock);
4373 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4374 playbackThread->destroyTrack_l(this);
4375 }
4376 }
4377}
4378
Glenn Kasten288ed212012-04-25 17:52:27 -07004379/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4380{
Glenn Kastene213c862012-04-25 13:46:15 -07004381 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 -07004382 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004383}
4384
Mathias Agopian65ab4712010-07-14 17:59:35 -07004385void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4386{
Glenn Kasten83d86532012-01-17 14:39:34 -08004387 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004388 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004389 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004390 } else {
4391 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4392 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004393 track_state state = mState;
4394 char stateChar;
4395 switch (state) {
4396 case IDLE:
4397 stateChar = 'I';
4398 break;
4399 case TERMINATED:
4400 stateChar = 'T';
4401 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004402 case STOPPING_1:
4403 stateChar = 's';
4404 break;
4405 case STOPPING_2:
4406 stateChar = '5';
4407 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004408 case STOPPED:
4409 stateChar = 'S';
4410 break;
4411 case RESUMING:
4412 stateChar = 'R';
4413 break;
4414 case ACTIVE:
4415 stateChar = 'A';
4416 break;
4417 case PAUSING:
4418 stateChar = 'p';
4419 break;
4420 case PAUSED:
4421 stateChar = 'P';
4422 break;
Eric Laurent29864602012-05-08 18:57:51 -07004423 case FLUSHED:
4424 stateChar = 'F';
4425 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004426 default:
4427 stateChar = '?';
4428 break;
4429 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004430 char nowInUnderrun;
4431 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4432 case UNDERRUN_FULL:
4433 nowInUnderrun = ' ';
4434 break;
4435 case UNDERRUN_PARTIAL:
4436 nowInUnderrun = '<';
4437 break;
4438 case UNDERRUN_EMPTY:
4439 nowInUnderrun = '*';
4440 break;
4441 default:
4442 nowInUnderrun = '?';
4443 break;
4444 }
Glenn Kastene213c862012-04-25 13:46:15 -07004445 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4446 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004447 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004448 mStreamType,
4449 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004450 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004451 mSessionId,
4452 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004453 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004454 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004455 mMute,
4456 mFillingUpStatus,
4457 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004458 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4459 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004460 mCblk->server,
4461 mCblk->user,
4462 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004463 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004464 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004465 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004466 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004467}
4468
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004469// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004470status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004471 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004472{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004473 audio_track_cblk_t* cblk = this->cblk();
4474 uint32_t framesReady;
4475 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004476
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004477 // Check if last stepServer failed, try to step now
4478 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004479 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4480 // Since the fast mixer is higher priority than client callback thread,
4481 // it does not result in priority inversion for client.
4482 // But a non-blocking solution would be preferable to avoid
4483 // fast mixer being unable to tryLock(), and
4484 // to avoid the extra context switches if the client wakes up,
4485 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004486 if (!step()) goto getNextBuffer_exit;
4487 ALOGV("stepServer recovered");
4488 mStepServerFailed = false;
4489 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004490
Glenn Kasten288ed212012-04-25 17:52:27 -07004491 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004492 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004493
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004494 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004495 uint32_t s = cblk->server;
4496 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4497
4498 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4499 if (framesReq > framesReady) {
4500 framesReq = framesReady;
4501 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004502 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004503 framesReq = bufferEnd - s;
4504 }
4505
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004506 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004507 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004508 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004509 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004510
4511getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004512 buffer->raw = NULL;
4513 buffer->frameCount = 0;
4514 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4515 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004516}
4517
Glenn Kasten288ed212012-04-25 17:52:27 -07004518// Note that framesReady() takes a mutex on the control block using tryLock().
4519// This could result in priority inversion if framesReady() is called by the normal mixer,
4520// as the normal mixer thread runs at lower
4521// priority than the client's callback thread: there is a short window within framesReady()
4522// during which the normal mixer could be preempted, and the client callback would block.
4523// Another problem can occur if framesReady() is called by the fast mixer:
4524// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4525// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4526size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004527 return mCblk->framesReady();
4528}
4529
Glenn Kasten288ed212012-04-25 17:52:27 -07004530// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004531bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004532 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004533
John Grossman4ff14ba2012-02-08 16:37:41 -08004534 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004535 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4536 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004537 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004538 return true;
4539 }
4540 return false;
4541}
4542
Glenn Kasten3acbd052012-02-28 10:39:56 -08004543status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004544 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004545{
4546 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004547 ALOGV("start(%d), calling pid %d session %d",
4548 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004549
Mathias Agopian65ab4712010-07-14 17:59:35 -07004550 sp<ThreadBase> thread = mThread.promote();
4551 if (thread != 0) {
4552 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004553 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004554 // here the track could be either new, or restarted
4555 // in both cases "unstop" the track
4556 if (mState == PAUSED) {
4557 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004558 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004559 } else {
4560 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004561 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004562 }
4563
4564 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4565 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004566 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004567 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004568
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004569#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004570 // to track the speaker usage
4571 if (status == NO_ERROR) {
4572 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4573 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004574#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004575 }
4576 if (status == NO_ERROR) {
4577 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4578 playbackThread->addTrack_l(this);
4579 } else {
4580 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004581 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004582 }
4583 } else {
4584 status = BAD_VALUE;
4585 }
4586 return status;
4587}
4588
4589void AudioFlinger::PlaybackThread::Track::stop()
4590{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004591 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004592 sp<ThreadBase> thread = mThread.promote();
4593 if (thread != 0) {
4594 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004595 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004596 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004597 // If the track is not active (PAUSED and buffers full), flush buffers
4598 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4599 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4600 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004601 mState = STOPPED;
4602 } else if (!isFastTrack()) {
4603 mState = STOPPED;
4604 } else {
4605 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4606 // and then to STOPPED and reset() when presentation is complete
4607 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004608 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004609 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004610 }
4611 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4612 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004613 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004614 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004615
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004616#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004617 // to track the speaker usage
4618 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004619#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004620 }
4621 }
4622}
4623
4624void AudioFlinger::PlaybackThread::Track::pause()
4625{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004626 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004627 sp<ThreadBase> thread = mThread.promote();
4628 if (thread != 0) {
4629 Mutex::Autolock _l(thread->mLock);
4630 if (mState == ACTIVE || mState == RESUMING) {
4631 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004632 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004633 if (!isOutputTrack()) {
4634 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004635 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004636 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004637
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004638#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004639 // to track the speaker usage
4640 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004641#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004642 }
4643 }
4644 }
4645}
4646
4647void AudioFlinger::PlaybackThread::Track::flush()
4648{
Steve Block3856b092011-10-20 11:56:00 +01004649 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004650 sp<ThreadBase> thread = mThread.promote();
4651 if (thread != 0) {
4652 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004653 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4654 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004655 return;
4656 }
4657 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004658 // FLUSHED state
4659 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004660 // do not reset the track if it is still in the process of being stopped or paused.
4661 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004662 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004663 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004664 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4665 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4666 reset();
4667 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004668 }
4669}
4670
4671void AudioFlinger::PlaybackThread::Track::reset()
4672{
4673 // Do not reset twice to avoid discarding data written just after a flush and before
4674 // the audioflinger thread detects the track is stopped.
4675 if (!mResetDone) {
4676 TrackBase::reset();
4677 // Force underrun condition to avoid false underrun callback until first data is
4678 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004679 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4680 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004681 mFillingUpStatus = FS_FILLING;
4682 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004683 if (mState == FLUSHED) {
4684 mState = IDLE;
4685 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004686 }
4687}
4688
4689void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4690{
4691 mMute = muted;
4692}
4693
Mathias Agopian65ab4712010-07-14 17:59:35 -07004694status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4695{
4696 status_t status = DEAD_OBJECT;
4697 sp<ThreadBase> thread = mThread.promote();
4698 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004699 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004700 sp<AudioFlinger> af = mClient->audioFlinger();
4701
4702 Mutex::Autolock _l(af->mLock);
4703
4704 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004705
Eric Laurent109347d2012-07-02 12:31:03 -07004706 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004707 Mutex::Autolock _dl(playbackThread->mLock);
4708 Mutex::Autolock _sl(srcThread->mLock);
4709 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4710 if (chain == 0) {
4711 return INVALID_OPERATION;
4712 }
4713
4714 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4715 if (effect == 0) {
4716 return INVALID_OPERATION;
4717 }
4718 srcThread->removeEffect_l(effect);
4719 playbackThread->addEffect_l(effect);
4720 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4721 if (effect->state() == EffectModule::ACTIVE ||
4722 effect->state() == EffectModule::STOPPING) {
4723 effect->start();
4724 }
4725
4726 sp<EffectChain> dstChain = effect->chain().promote();
4727 if (dstChain == 0) {
4728 srcThread->addEffect_l(effect);
4729 return INVALID_OPERATION;
4730 }
4731 AudioSystem::unregisterEffect(effect->id());
4732 AudioSystem::registerEffect(&effect->desc(),
4733 srcThread->id(),
4734 dstChain->strategy(),
4735 AUDIO_SESSION_OUTPUT_MIX,
4736 effect->id());
4737 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004738 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004739 }
4740 return status;
4741}
4742
4743void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4744{
4745 mAuxEffectId = EffectId;
4746 mAuxBuffer = buffer;
4747}
4748
Eric Laurenta011e352012-03-29 15:51:43 -07004749bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4750 size_t audioHalFrames)
4751{
4752 // a track is considered presented when the total number of frames written to audio HAL
4753 // corresponds to the number of frames written when presentationComplete() is called for the
4754 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4755 if (mPresentationCompleteFrames == 0) {
4756 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4757 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4758 mPresentationCompleteFrames, audioHalFrames);
4759 }
4760 if (framesWritten >= mPresentationCompleteFrames) {
4761 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4762 mSessionId, framesWritten);
4763 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004764 return true;
4765 }
4766 return false;
4767}
4768
4769void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4770{
4771 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4772 if (mSyncEvents[i]->type() == type) {
4773 mSyncEvents[i]->trigger();
4774 mSyncEvents.removeAt(i);
4775 i--;
4776 }
4777 }
4778}
4779
Glenn Kasten58912562012-04-03 10:45:00 -07004780// implement VolumeBufferProvider interface
4781
4782uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4783{
4784 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4785 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4786 uint32_t vlr = mCblk->getVolumeLR();
4787 uint32_t vl = vlr & 0xFFFF;
4788 uint32_t vr = vlr >> 16;
4789 // track volumes come from shared memory, so can't be trusted and must be clamped
4790 if (vl > MAX_GAIN_INT) {
4791 vl = MAX_GAIN_INT;
4792 }
4793 if (vr > MAX_GAIN_INT) {
4794 vr = MAX_GAIN_INT;
4795 }
4796 // now apply the cached master volume and stream type volume;
4797 // this is trusted but lacks any synchronization or barrier so may be stale
4798 float v = mCachedVolume;
4799 vl *= v;
4800 vr *= v;
4801 // re-combine into U4.16
4802 vlr = (vr << 16) | (vl & 0xFFFF);
4803 // FIXME look at mute, pause, and stop flags
4804 return vlr;
4805}
Eric Laurenta011e352012-03-29 15:51:43 -07004806
Eric Laurent29864602012-05-08 18:57:51 -07004807status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4808{
4809 if (mState == TERMINATED || mState == PAUSED ||
4810 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4811 (mState == STOPPED)))) {
4812 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4813 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4814 event->cancel();
4815 return INVALID_OPERATION;
4816 }
Glenn Kastend23eedc2012-08-02 13:35:47 -07004817 (void) TrackBase::setSyncEvent(event);
Eric Laurent29864602012-05-08 18:57:51 -07004818 return NO_ERROR;
4819}
4820
John Grossman4ff14ba2012-02-08 16:37:41 -08004821// timed audio tracks
4822
4823sp<AudioFlinger::PlaybackThread::TimedTrack>
4824AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004825 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004826 const sp<Client>& client,
4827 audio_stream_type_t streamType,
4828 uint32_t sampleRate,
4829 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004830 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004831 int frameCount,
4832 const sp<IMemory>& sharedBuffer,
4833 int sessionId) {
4834 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004835 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004836
Glenn Kastena0356762012-03-19 10:38:51 -07004837 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004838 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4839 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004840}
4841
4842AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004843 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004844 const sp<Client>& client,
4845 audio_stream_type_t streamType,
4846 uint32_t sampleRate,
4847 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004848 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004849 int frameCount,
4850 const sp<IMemory>& sharedBuffer,
4851 int sessionId)
4852 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004853 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004854 mQueueHeadInFlight(false),
4855 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004856 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004857 mTimedSilenceBuffer(NULL),
4858 mTimedSilenceBufferSize(0),
4859 mTimedAudioOutputOnTime(false),
4860 mMediaTimeTransformValid(false)
4861{
4862 LocalClock lc;
4863 mLocalTimeFreq = lc.getLocalFreq();
4864
4865 mLocalTimeToSampleTransform.a_zero = 0;
4866 mLocalTimeToSampleTransform.b_zero = 0;
4867 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4868 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4869 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4870 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004871
4872 mMediaTimeToSampleTransform.a_zero = 0;
4873 mMediaTimeToSampleTransform.b_zero = 0;
4874 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4875 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4876 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4877 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004878}
4879
4880AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4881 mClient->releaseTimedTrack();
4882 delete [] mTimedSilenceBuffer;
4883}
4884
4885status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4886 size_t size, sp<IMemory>* buffer) {
4887
4888 Mutex::Autolock _l(mTimedBufferQueueLock);
4889
4890 trimTimedBufferQueue_l();
4891
4892 // lazily initialize the shared memory heap for timed buffers
4893 if (mTimedMemoryDealer == NULL) {
4894 const int kTimedBufferHeapSize = 512 << 10;
4895
4896 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4897 "AudioFlingerTimed");
4898 if (mTimedMemoryDealer == NULL)
4899 return NO_MEMORY;
4900 }
4901
4902 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4903 if (newBuffer == NULL) {
4904 newBuffer = mTimedMemoryDealer->allocate(size);
4905 if (newBuffer == NULL)
4906 return NO_MEMORY;
4907 }
4908
4909 *buffer = newBuffer;
4910 return NO_ERROR;
4911}
4912
4913// caller must hold mTimedBufferQueueLock
4914void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4915 int64_t mediaTimeNow;
4916 {
4917 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4918 if (!mMediaTimeTransformValid)
4919 return;
4920
4921 int64_t targetTimeNow;
4922 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4923 ? mCCHelper.getCommonTime(&targetTimeNow)
4924 : mCCHelper.getLocalTime(&targetTimeNow);
4925
4926 if (OK != res)
4927 return;
4928
4929 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4930 &mediaTimeNow)) {
4931 return;
4932 }
4933 }
4934
John Grossman1c345192012-03-27 14:00:17 -07004935 size_t trimEnd;
4936 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004937 int64_t bufEnd;
4938
John Grossmanc95cfbb2012-04-12 11:53:11 -07004939 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4940 // We have a next buffer. Just use its PTS as the PTS of the frame
4941 // following the last frame in this buffer. If the stream is sparse
4942 // (ie, there are deliberate gaps left in the stream which should be
4943 // filled with silence by the TimedAudioTrack), then this can result
4944 // in one extra buffer being left un-trimmed when it could have
4945 // been. In general, this is not typical, and we would rather
4946 // optimized away the TS calculation below for the more common case
4947 // where PTSes are contiguous.
4948 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4949 } else {
4950 // We have no next buffer. Compute the PTS of the frame following
4951 // the last frame in this buffer by computing the duration of of
4952 // this frame in media time units and adding it to the PTS of the
4953 // buffer.
4954 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4955 / mCblk->frameSize;
4956
4957 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4958 &bufEnd)) {
4959 ALOGE("Failed to convert frame count of %lld to media time"
4960 " duration" " (scale factor %d/%u) in %s",
4961 frameCount,
4962 mMediaTimeToSampleTransform.a_to_b_numer,
4963 mMediaTimeToSampleTransform.a_to_b_denom,
4964 __PRETTY_FUNCTION__);
4965 break;
4966 }
4967 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004968 }
John Grossman9fbdee12012-03-26 17:51:46 -07004969
4970 if (bufEnd > mediaTimeNow)
4971 break;
4972
4973 // Is the buffer we want to use in the middle of a mix operation right
4974 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4975 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004976 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004977 mTrimQueueHeadOnRelease = true;
4978 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004979 }
4980
John Grossman9fbdee12012-03-26 17:51:46 -07004981 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004982 if (trimStart < trimEnd) {
4983 // Update the bookkeeping for framesReady()
4984 for (size_t i = trimStart; i < trimEnd; ++i) {
4985 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4986 }
4987
4988 // Now actually remove the buffers from the queue.
4989 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004990 }
4991}
4992
John Grossman1c345192012-03-27 14:00:17 -07004993void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4994 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004995 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4996 "%s called (reason \"%s\"), but timed buffer queue has no"
4997 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004998
4999 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
5000 mTimedBufferQueue.removeAt(0);
5001}
5002
5003void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
5004 const TimedBuffer& buf,
5005 const char* logTag) {
5006 uint32_t bufBytes = buf.buffer()->size();
5007 uint32_t consumedAlready = buf.position();
5008
Eric Laurentb388e532012-04-14 13:32:48 -07005009 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07005010 "Bad bookkeeping while updating frames pending. Timed buffer is"
5011 " only %u bytes long, but claims to have consumed %u"
5012 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07005013 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005014
5015 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07005016 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5017 "Bad bookkeeping while updating frames pending. Should have at"
5018 " least %u queued frames, but we think we have only %u. (update"
5019 " reason: \"%s\")",
5020 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005021
5022 mFramesPendingInQueue -= bufFrames;
5023}
5024
John Grossman4ff14ba2012-02-08 16:37:41 -08005025status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5026 const sp<IMemory>& buffer, int64_t pts) {
5027
5028 {
5029 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5030 if (!mMediaTimeTransformValid)
5031 return INVALID_OPERATION;
5032 }
5033
5034 Mutex::Autolock _l(mTimedBufferQueueLock);
5035
John Grossman1c345192012-03-27 14:00:17 -07005036 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5037 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005038 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5039
5040 return NO_ERROR;
5041}
5042
5043status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5044 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5045
John Grossman1c345192012-03-27 14:00:17 -07005046 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5047 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5048 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005049
5050 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5051 target == TimedAudioTrack::COMMON_TIME)) {
5052 return BAD_VALUE;
5053 }
5054
5055 Mutex::Autolock lock(mMediaTimeTransformLock);
5056 mMediaTimeTransform = xform;
5057 mMediaTimeTransformTarget = target;
5058 mMediaTimeTransformValid = true;
5059
5060 return NO_ERROR;
5061}
5062
5063#define min(a, b) ((a) < (b) ? (a) : (b))
5064
5065// implementation of getNextBuffer for tracks whose buffers have timestamps
5066status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5067 AudioBufferProvider::Buffer* buffer, int64_t pts)
5068{
5069 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005070 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005071 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005072 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005073 return INVALID_OPERATION;
5074 }
5075
John Grossman4ff14ba2012-02-08 16:37:41 -08005076 Mutex::Autolock _l(mTimedBufferQueueLock);
5077
John Grossman9fbdee12012-03-26 17:51:46 -07005078 ALOG_ASSERT(!mQueueHeadInFlight,
5079 "getNextBuffer called without releaseBuffer!");
5080
John Grossman4ff14ba2012-02-08 16:37:41 -08005081 while (true) {
5082
5083 // if we have no timed buffers, then fail
5084 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005085 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005086 buffer->frameCount = 0;
5087 return NOT_ENOUGH_DATA;
5088 }
5089
5090 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5091
5092 // calculate the PTS of the head of the timed buffer queue expressed in
5093 // local time
5094 int64_t headLocalPTS;
5095 {
5096 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5097
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005098 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005099
5100 if (mMediaTimeTransform.a_to_b_denom == 0) {
5101 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005102 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005103 return NO_ERROR;
5104 }
5105
5106 int64_t transformedPTS;
5107 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5108 &transformedPTS)) {
5109 // the transform failed. this shouldn't happen, but if it does
5110 // then just drop this buffer
5111 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005112 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005113 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005114 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005115 return NO_ERROR;
5116 }
5117
5118 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5119 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5120 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005121 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005122 buffer->frameCount = 0;
5123 return INVALID_OPERATION;
5124 }
5125 } else {
5126 headLocalPTS = transformedPTS;
5127 }
5128 }
5129
5130 // adjust the head buffer's PTS to reflect the portion of the head buffer
5131 // that has already been consumed
5132 int64_t effectivePTS = headLocalPTS +
5133 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5134
5135 // Calculate the delta in samples between the head of the input buffer
5136 // queue and the start of the next output buffer that will be written.
5137 // If the transformation fails because of over or underflow, it means
5138 // that the sample's position in the output stream is so far out of
5139 // whack that it should just be dropped.
5140 int64_t sampleDelta;
5141 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5142 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005143 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5144 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005145 continue;
5146 }
5147 if (!mLocalTimeToSampleTransform.doForwardTransform(
5148 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005149 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005150 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005151 continue;
5152 }
5153
John Grossman1c345192012-03-27 14:00:17 -07005154 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5155 " sampleDelta=[%d.%08x]",
5156 head.pts(), head.position(), pts,
5157 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5158 + (sampleDelta >> 32)),
5159 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005160
5161 // if the delta between the ideal placement for the next input sample and
5162 // the current output position is within this threshold, then we will
5163 // concatenate the next input samples to the previous output
5164 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005165 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005166
5167 // if this is the first buffer of audio that we're emitting from this track
5168 // then it should be almost exactly on time.
5169 const int64_t kSampleStartupThreshold = 1LL << 32;
5170
5171 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005172 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005173 // the next input is close enough to being on time, so concatenate it
5174 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005175 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005176
John Grossman1c345192012-03-27 14:00:17 -07005177 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5178 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005179 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005180 }
5181
5182 // Looks like our output is not on time. Reset our on timed status.
5183 // Next time we mix samples from our input queue, then should be within
5184 // the StartupThreshold.
5185 mTimedAudioOutputOnTime = false;
5186 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005187 // the gap between the current output position and the proper start of
5188 // the next input sample is too big, so fill it with silence
5189 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5190
John Grossman9fbdee12012-03-26 17:51:46 -07005191 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005192 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5193 return NO_ERROR;
5194 } else {
5195 // the next input sample is late
5196 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5197 size_t onTimeSamplePosition =
5198 head.position() + lateFrames * mCblk->frameSize;
5199
5200 if (onTimeSamplePosition > head.buffer()->size()) {
5201 // all the remaining samples in the head are too late, so
5202 // drop it and move on
5203 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005204 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005205 continue;
5206 } else {
5207 // skip over the late samples
5208 head.setPosition(onTimeSamplePosition);
5209
5210 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005211 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005212
5213 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5214 return NO_ERROR;
5215 }
5216 }
5217 }
5218}
5219
5220// Yield samples from the timed buffer queue head up to the given output
5221// buffer's capacity.
5222//
5223// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005224void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005225 AudioBufferProvider::Buffer* buffer) {
5226
5227 const TimedBuffer& head = mTimedBufferQueue[0];
5228
5229 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5230 head.position());
5231
5232 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5233 mCblk->frameSize);
5234 size_t framesRequested = buffer->frameCount;
5235 buffer->frameCount = min(framesLeftInHead, framesRequested);
5236
John Grossman9fbdee12012-03-26 17:51:46 -07005237 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005238 mTimedAudioOutputOnTime = true;
5239}
5240
5241// Yield samples of silence up to the given output buffer's capacity
5242//
5243// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005244void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005245 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5246
5247 // lazily allocate a buffer filled with silence
5248 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5249 delete [] mTimedSilenceBuffer;
5250 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5251 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5252 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5253 }
5254
5255 buffer->raw = mTimedSilenceBuffer;
5256 size_t framesRequested = buffer->frameCount;
5257 buffer->frameCount = min(numFrames, framesRequested);
5258
5259 mTimedAudioOutputOnTime = false;
5260}
5261
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005262// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005263void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5264 AudioBufferProvider::Buffer* buffer) {
5265
5266 Mutex::Autolock _l(mTimedBufferQueueLock);
5267
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005268 // If the buffer which was just released is part of the buffer at the head
5269 // of the queue, be sure to update the amt of the buffer which has been
5270 // consumed. If the buffer being returned is not part of the head of the
5271 // queue, its either because the buffer is part of the silence buffer, or
5272 // because the head of the timed queue was trimmed after the mixer called
5273 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005274 if (buffer->raw == mTimedSilenceBuffer) {
5275 ALOG_ASSERT(!mQueueHeadInFlight,
5276 "Queue head in flight during release of silence buffer!");
5277 goto done;
5278 }
5279
5280 ALOG_ASSERT(mQueueHeadInFlight,
5281 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5282 " head in flight.");
5283
5284 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005285 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005286
5287 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005288 void* end = reinterpret_cast<void*>(
5289 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5290 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005291
John Grossman9fbdee12012-03-26 17:51:46 -07005292 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5293 "released buffer not within the head of the timed buffer"
5294 " queue; qHead = [%p, %p], released buffer = %p",
5295 start, end, buffer->raw);
5296
5297 head.setPosition(head.position() +
5298 (buffer->frameCount * mCblk->frameSize));
5299 mQueueHeadInFlight = false;
5300
John Grossman1c345192012-03-27 14:00:17 -07005301 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5302 "Bad bookkeeping during releaseBuffer! Should have at"
5303 " least %u queued frames, but we think we have only %u",
5304 buffer->frameCount, mFramesPendingInQueue);
5305
5306 mFramesPendingInQueue -= buffer->frameCount;
5307
John Grossman9fbdee12012-03-26 17:51:46 -07005308 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5309 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005310 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005311 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005312 }
John Grossman9fbdee12012-03-26 17:51:46 -07005313 } else {
5314 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5315 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005316 }
5317
John Grossman9fbdee12012-03-26 17:51:46 -07005318done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005319 buffer->raw = 0;
5320 buffer->frameCount = 0;
5321}
5322
Glenn Kasten288ed212012-04-25 17:52:27 -07005323size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005324 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005325 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005326}
5327
5328AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5329 : mPTS(0), mPosition(0) {}
5330
5331AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5332 const sp<IMemory>& buffer, int64_t pts)
5333 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5334
Mathias Agopian65ab4712010-07-14 17:59:35 -07005335// ----------------------------------------------------------------------------
5336
5337// RecordTrack constructor must be called with AudioFlinger::mLock held
5338AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005339 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005340 const sp<Client>& client,
5341 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005342 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005343 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005344 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005345 int sessionId)
5346 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005347 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005348 mOverflow(false)
5349{
5350 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005351 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5352 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5353 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5354 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5355 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5356 } else {
5357 mCblk->frameSize = sizeof(int8_t);
5358 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005359 }
5360}
5361
5362AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5363{
Glenn Kasten510a3d62012-07-16 14:24:34 -07005364 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005365}
5366
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005367// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005368status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005369{
5370 audio_track_cblk_t* cblk = this->cblk();
5371 uint32_t framesAvail;
5372 uint32_t framesReq = buffer->frameCount;
5373
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005374 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005375 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005376 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005377 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005378 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005379 }
5380
5381 framesAvail = cblk->framesAvailable_l();
5382
Glenn Kastenf6b16782011-12-15 09:51:17 -08005383 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005384 uint32_t s = cblk->server;
5385 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5386
5387 if (framesReq > framesAvail) {
5388 framesReq = framesAvail;
5389 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005390 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005391 framesReq = bufferEnd - s;
5392 }
5393
5394 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005395 buffer->frameCount = framesReq;
5396 return NO_ERROR;
5397 }
5398
5399getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005400 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005401 buffer->frameCount = 0;
5402 return NOT_ENOUGH_DATA;
5403}
5404
Glenn Kasten3acbd052012-02-28 10:39:56 -08005405status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005406 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005407{
5408 sp<ThreadBase> thread = mThread.promote();
5409 if (thread != 0) {
5410 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005411 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005412 } else {
5413 return BAD_VALUE;
5414 }
5415}
5416
5417void AudioFlinger::RecordThread::RecordTrack::stop()
5418{
5419 sp<ThreadBase> thread = mThread.promote();
5420 if (thread != 0) {
5421 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005422 recordThread->mLock.lock();
5423 bool doStop = recordThread->stop_l(this);
5424 if (doStop) {
5425 TrackBase::reset();
5426 // Force overrun condition to avoid false overrun callback until first data is
5427 // read from buffer
5428 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5429 }
5430 recordThread->mLock.unlock();
5431 if (doStop) {
5432 AudioSystem::stopInput(recordThread->id());
5433 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005434 }
5435}
5436
Glenn Kasten510a3d62012-07-16 14:24:34 -07005437/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
5438{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005439 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User FrameCount\n");
Glenn Kasten510a3d62012-07-16 14:24:34 -07005440}
5441
Mathias Agopian65ab4712010-07-14 17:59:35 -07005442void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5443{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005444 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x %05d\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005445 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005447 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005448 mSessionId,
5449 mFrameCount,
5450 mState,
5451 mCblk->sampleRate,
5452 mCblk->server,
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005453 mCblk->user,
5454 mCblk->frameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005455}
5456
5457
5458// ----------------------------------------------------------------------------
5459
5460AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005461 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005462 DuplicatingThread *sourceThread,
5463 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005464 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005465 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005466 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005467 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5468 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005469 mActive(false), mSourceThread(sourceThread)
5470{
5471
Mathias Agopian65ab4712010-07-14 17:59:35 -07005472 if (mCblk != NULL) {
5473 mCblk->flags |= CBLK_DIRECTION_OUT;
5474 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005475 mOutBuffer.frameCount = 0;
5476 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005477 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005478 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5479 mCblk, mBuffer, mCblk->buffers,
5480 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005481 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005482 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005483 }
5484}
5485
5486AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5487{
5488 clearBufferQueue();
5489}
5490
Glenn Kasten3acbd052012-02-28 10:39:56 -08005491status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005492 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005493{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005494 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005495 if (status != NO_ERROR) {
5496 return status;
5497 }
5498
5499 mActive = true;
5500 mRetryCount = 127;
5501 return status;
5502}
5503
5504void AudioFlinger::PlaybackThread::OutputTrack::stop()
5505{
5506 Track::stop();
5507 clearBufferQueue();
5508 mOutBuffer.frameCount = 0;
5509 mActive = false;
5510}
5511
5512bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5513{
5514 Buffer *pInBuffer;
5515 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005516 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005517 bool outputBufferFull = false;
5518 inBuffer.frameCount = frames;
5519 inBuffer.i16 = data;
5520
5521 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5522
5523 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005524 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005525 sp<ThreadBase> thread = mThread.promote();
5526 if (thread != 0) {
5527 MixerThread *mixerThread = (MixerThread *)thread.get();
5528 if (mCblk->frameCount > frames){
5529 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5530 uint32_t startFrames = (mCblk->frameCount - frames);
5531 pInBuffer = new Buffer;
5532 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5533 pInBuffer->frameCount = startFrames;
5534 pInBuffer->i16 = pInBuffer->mBuffer;
5535 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5536 mBufferQueue.add(pInBuffer);
5537 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005538 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005539 }
5540 }
5541 }
5542 }
5543
5544 while (waitTimeLeftMs) {
5545 // First write pending buffers, then new data
5546 if (mBufferQueue.size()) {
5547 pInBuffer = mBufferQueue.itemAt(0);
5548 } else {
5549 pInBuffer = &inBuffer;
5550 }
5551
5552 if (pInBuffer->frameCount == 0) {
5553 break;
5554 }
5555
5556 if (mOutBuffer.frameCount == 0) {
5557 mOutBuffer.frameCount = pInBuffer->frameCount;
5558 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005559 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005560 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005561 outputBufferFull = true;
5562 break;
5563 }
5564 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5565 if (waitTimeLeftMs >= waitTimeMs) {
5566 waitTimeLeftMs -= waitTimeMs;
5567 } else {
5568 waitTimeLeftMs = 0;
5569 }
5570 }
5571
5572 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5573 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5574 mCblk->stepUser(outFrames);
5575 pInBuffer->frameCount -= outFrames;
5576 pInBuffer->i16 += outFrames * channelCount;
5577 mOutBuffer.frameCount -= outFrames;
5578 mOutBuffer.i16 += outFrames * channelCount;
5579
5580 if (pInBuffer->frameCount == 0) {
5581 if (mBufferQueue.size()) {
5582 mBufferQueue.removeAt(0);
5583 delete [] pInBuffer->mBuffer;
5584 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005585 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005586 } else {
5587 break;
5588 }
5589 }
5590 }
5591
5592 // If we could not write all frames, allocate a buffer and queue it for next time.
5593 if (inBuffer.frameCount) {
5594 sp<ThreadBase> thread = mThread.promote();
5595 if (thread != 0 && !thread->standby()) {
5596 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5597 pInBuffer = new Buffer;
5598 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5599 pInBuffer->frameCount = inBuffer.frameCount;
5600 pInBuffer->i16 = pInBuffer->mBuffer;
5601 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5602 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005603 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005604 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005605 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005606 }
5607 }
5608 }
5609
5610 // Calling write() with a 0 length buffer, means that no more data will be written:
5611 // If no more buffers are pending, fill output track buffer to make sure it is started
5612 // by output mixer.
5613 if (frames == 0 && mBufferQueue.size() == 0) {
5614 if (mCblk->user < mCblk->frameCount) {
5615 frames = mCblk->frameCount - mCblk->user;
5616 pInBuffer = new Buffer;
5617 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5618 pInBuffer->frameCount = frames;
5619 pInBuffer->i16 = pInBuffer->mBuffer;
5620 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5621 mBufferQueue.add(pInBuffer);
5622 } else if (mActive) {
5623 stop();
5624 }
5625 }
5626
5627 return outputBufferFull;
5628}
5629
5630status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5631{
5632 int active;
5633 status_t result;
5634 audio_track_cblk_t* cblk = mCblk;
5635 uint32_t framesReq = buffer->frameCount;
5636
Steve Block3856b092011-10-20 11:56:00 +01005637// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005638 buffer->frameCount = 0;
5639
5640 uint32_t framesAvail = cblk->framesAvailable();
5641
5642
5643 if (framesAvail == 0) {
5644 Mutex::Autolock _l(cblk->lock);
5645 goto start_loop_here;
5646 while (framesAvail == 0) {
5647 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005648 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005649 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005650 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005651 }
5652 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5653 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005654 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005655 }
5656 // read the server count again
5657 start_loop_here:
5658 framesAvail = cblk->framesAvailable_l();
5659 }
5660 }
5661
5662// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005663// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005664// }
5665
5666 if (framesReq > framesAvail) {
5667 framesReq = framesAvail;
5668 }
5669
5670 uint32_t u = cblk->user;
5671 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5672
Marco Nelissena1472d92012-03-30 14:36:54 -07005673 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005674 framesReq = bufferEnd - u;
5675 }
5676
5677 buffer->frameCount = framesReq;
5678 buffer->raw = (void *)cblk->buffer(u);
5679 return NO_ERROR;
5680}
5681
5682
5683void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5684{
5685 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005686
5687 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005688 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005689 delete [] pBuffer->mBuffer;
5690 delete pBuffer;
5691 }
5692 mBufferQueue.clear();
5693}
5694
5695// ----------------------------------------------------------------------------
5696
5697AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5698 : RefBase(),
5699 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005700 // 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 -07005701 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005702 mPid(pid),
5703 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704{
5705 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5706}
5707
5708// Client destructor must be called with AudioFlinger::mLock held
5709AudioFlinger::Client::~Client()
5710{
5711 mAudioFlinger->removeClient_l(mPid);
5712}
5713
Glenn Kasten435dbe62012-01-30 10:15:48 -08005714sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005715{
5716 return mMemoryDealer;
5717}
5718
John Grossman4ff14ba2012-02-08 16:37:41 -08005719// Reserve one of the limited slots for a timed audio track associated
5720// with this client
5721bool AudioFlinger::Client::reserveTimedTrack()
5722{
5723 const int kMaxTimedTracksPerClient = 4;
5724
5725 Mutex::Autolock _l(mTimedTrackLock);
5726
5727 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5728 ALOGW("can not create timed track - pid %d has exceeded the limit",
5729 mPid);
5730 return false;
5731 }
5732
5733 mTimedTrackCount++;
5734 return true;
5735}
5736
5737// Release a slot for a timed audio track
5738void AudioFlinger::Client::releaseTimedTrack()
5739{
5740 Mutex::Autolock _l(mTimedTrackLock);
5741 mTimedTrackCount--;
5742}
5743
Mathias Agopian65ab4712010-07-14 17:59:35 -07005744// ----------------------------------------------------------------------------
5745
5746AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5747 const sp<IAudioFlingerClient>& client,
5748 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005749 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005750{
5751}
5752
5753AudioFlinger::NotificationClient::~NotificationClient()
5754{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005755}
5756
5757void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5758{
5759 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005760 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005761}
5762
5763// ----------------------------------------------------------------------------
5764
5765AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5766 : BnAudioTrack(),
5767 mTrack(track)
5768{
5769}
5770
5771AudioFlinger::TrackHandle::~TrackHandle() {
5772 // just stop the track on deletion, associated resources
5773 // will be freed from the main thread once all pending buffers have
5774 // been played. Unless it's not in the active track list, in which
5775 // case we free everything now...
5776 mTrack->destroy();
5777}
5778
Glenn Kasten90716c52012-01-26 13:40:12 -08005779sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5780 return mTrack->getCblk();
5781}
5782
Glenn Kasten3acbd052012-02-28 10:39:56 -08005783status_t AudioFlinger::TrackHandle::start() {
5784 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005785}
5786
5787void AudioFlinger::TrackHandle::stop() {
5788 mTrack->stop();
5789}
5790
5791void AudioFlinger::TrackHandle::flush() {
5792 mTrack->flush();
5793}
5794
5795void AudioFlinger::TrackHandle::mute(bool e) {
5796 mTrack->mute(e);
5797}
5798
5799void AudioFlinger::TrackHandle::pause() {
5800 mTrack->pause();
5801}
5802
Mathias Agopian65ab4712010-07-14 17:59:35 -07005803status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5804{
5805 return mTrack->attachAuxEffect(EffectId);
5806}
5807
John Grossman4ff14ba2012-02-08 16:37:41 -08005808status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5809 sp<IMemory>* buffer) {
5810 if (!mTrack->isTimedTrack())
5811 return INVALID_OPERATION;
5812
5813 PlaybackThread::TimedTrack* tt =
5814 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5815 return tt->allocateTimedBuffer(size, buffer);
5816}
5817
5818status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5819 int64_t pts) {
5820 if (!mTrack->isTimedTrack())
5821 return INVALID_OPERATION;
5822
5823 PlaybackThread::TimedTrack* tt =
5824 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5825 return tt->queueTimedBuffer(buffer, pts);
5826}
5827
5828status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5829 const LinearTransform& xform, int target) {
5830
5831 if (!mTrack->isTimedTrack())
5832 return INVALID_OPERATION;
5833
5834 PlaybackThread::TimedTrack* tt =
5835 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5836 return tt->setMediaTimeTransform(
5837 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5838}
5839
Mathias Agopian65ab4712010-07-14 17:59:35 -07005840status_t AudioFlinger::TrackHandle::onTransact(
5841 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5842{
5843 return BnAudioTrack::onTransact(code, data, reply, flags);
5844}
5845
5846// ----------------------------------------------------------------------------
5847
5848sp<IAudioRecord> AudioFlinger::openRecord(
5849 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005850 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005851 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005852 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005853 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005854 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005855 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07005856 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005857 int *sessionId,
5858 status_t *status)
5859{
5860 sp<RecordThread::RecordTrack> recordTrack;
5861 sp<RecordHandle> recordHandle;
5862 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005863 status_t lStatus;
5864 RecordThread *thread;
5865 size_t inFrameCount;
5866 int lSessionId;
5867
5868 // check calling permissions
5869 if (!recordingAllowed()) {
5870 lStatus = PERMISSION_DENIED;
5871 goto Exit;
5872 }
5873
5874 // add client to list
5875 { // scope for mLock
5876 Mutex::Autolock _l(mLock);
5877 thread = checkRecordThread_l(input);
5878 if (thread == NULL) {
5879 lStatus = BAD_VALUE;
5880 goto Exit;
5881 }
5882
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005883 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005884
5885 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005886 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005887 lSessionId = *sessionId;
5888 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005889 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005890 if (sessionId != NULL) {
5891 *sessionId = lSessionId;
5892 }
5893 }
5894 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07005895 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5896 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005897 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005898 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005899 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5900 // destructor is called by the TrackBase destructor with mLock held
5901 client.clear();
5902 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005903 goto Exit;
5904 }
5905
5906 // return to handle to client
5907 recordHandle = new RecordHandle(recordTrack);
5908 lStatus = NO_ERROR;
5909
5910Exit:
5911 if (status) {
5912 *status = lStatus;
5913 }
5914 return recordHandle;
5915}
5916
5917// ----------------------------------------------------------------------------
5918
5919AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5920 : BnAudioRecord(),
5921 mRecordTrack(recordTrack)
5922{
5923}
5924
5925AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005926 stop_nonvirtual();
Glenn Kasten510a3d62012-07-16 14:24:34 -07005927 mRecordTrack->destroy();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005928}
5929
Glenn Kasten90716c52012-01-26 13:40:12 -08005930sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5931 return mRecordTrack->getCblk();
5932}
5933
Glenn Kasten0ec23ce2012-07-10 12:56:08 -07005934status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005935 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005936 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005937}
5938
5939void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005940 stop_nonvirtual();
5941}
5942
5943void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01005944 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005945 mRecordTrack->stop();
5946}
5947
Mathias Agopian65ab4712010-07-14 17:59:35 -07005948status_t AudioFlinger::RecordHandle::onTransact(
5949 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5950{
5951 return BnAudioRecord::onTransact(code, data, reply, flags);
5952}
5953
5954// ----------------------------------------------------------------------------
5955
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005956AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5957 AudioStreamIn *input,
5958 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07005959 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005960 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07005961 audio_devices_t device) :
Eric Laurentf1c04f92012-08-28 14:26:53 -07005962 ThreadBase(audioFlinger, id, AUDIO_DEVICE_NONE, device, RECORD),
Glenn Kasten510a3d62012-07-16 14:24:34 -07005963 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005964 // mRsmpInIndex and mInputBytes set by readInputParameters()
Glenn Kasten254af182012-07-03 14:59:05 -07005965 mReqChannelCount(popcount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005966 mReqSampleRate(sampleRate)
5967 // mBytesRead is only meaningful while active, and so is cleared in start()
5968 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005969{
Glenn Kasten480b4682012-02-28 12:30:08 -08005970 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005971
Mathias Agopian65ab4712010-07-14 17:59:35 -07005972 readInputParameters();
5973}
5974
5975
5976AudioFlinger::RecordThread::~RecordThread()
5977{
5978 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005979 delete mResampler;
5980 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005981}
5982
5983void AudioFlinger::RecordThread::onFirstRef()
5984{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005985 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005986}
5987
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005988status_t AudioFlinger::RecordThread::readyToRun()
5989{
5990 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005991 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005992 return status;
5993}
5994
Mathias Agopian65ab4712010-07-14 17:59:35 -07005995bool AudioFlinger::RecordThread::threadLoop()
5996{
5997 AudioBufferProvider::Buffer buffer;
5998 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005999 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006000
Eric Laurent44d98482010-09-30 16:12:31 -07006001 nsecs_t lastWarning = 0;
6002
Glenn Kastene4e2a372012-07-23 12:55:09 -07006003 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07006004 acquireWakeLock();
6005
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07006006 // used to verify we've read at least once before evaluating how many bytes were read
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006007 bool readOnce = false;
6008
Mathias Agopian65ab4712010-07-14 17:59:35 -07006009 // start recording
6010 while (!exitPending()) {
6011
6012 processConfigEvents();
6013
6014 { // scope for mLock
6015 Mutex::Autolock _l(mLock);
6016 checkForNewParameters_l();
6017 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006018 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006019
6020 if (exitPending()) break;
6021
Eric Laurentfeb0db62011-07-22 09:04:31 -07006022 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01006023 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006024 // go to sleep
6025 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006026 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006027 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006028 continue;
6029 }
6030 if (mActiveTrack != 0) {
6031 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006032 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006033 mActiveTrack.clear();
6034 mStartStopCond.broadcast();
6035 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6036 if (mReqChannelCount != mActiveTrack->channelCount()) {
6037 mActiveTrack.clear();
6038 mStartStopCond.broadcast();
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006039 } else if (readOnce) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006040 // record start succeeds only if first read from audio input
6041 // succeeds
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006042 if (mBytesRead >= 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006043 mActiveTrack->mState = TrackBase::ACTIVE;
6044 } else {
6045 mActiveTrack.clear();
6046 }
6047 mStartStopCond.broadcast();
6048 }
6049 mStandby = false;
Glenn Kasten510a3d62012-07-16 14:24:34 -07006050 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
6051 removeTrack_l(mActiveTrack);
6052 mActiveTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006053 }
6054 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006055 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006056 }
6057
6058 if (mActiveTrack != 0) {
6059 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6060 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006061 unlockEffectChains(effectChains);
6062 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006063 continue;
6064 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006065 for (size_t i = 0; i < effectChains.size(); i ++) {
6066 effectChains[i]->process_l();
6067 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006068
Mathias Agopian65ab4712010-07-14 17:59:35 -07006069 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006070 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006071 readOnce = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006072 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006073 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074 // no resampling
6075 while (framesOut) {
6076 size_t framesIn = mFrameCount - mRsmpInIndex;
6077 if (framesIn) {
6078 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6079 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6080 if (framesIn > framesOut)
6081 framesIn = framesOut;
6082 mRsmpInIndex += framesIn;
6083 framesOut -= framesIn;
6084 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006085 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006086 memcpy(dst, src, framesIn * mFrameSize);
6087 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006088 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006089 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6090 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006091 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006092 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6093 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006094 }
6095 }
6096 }
6097 if (framesOut && mFrameCount == mRsmpInIndex) {
6098 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006099 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006100 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006101 framesOut = 0;
6102 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006103 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006104 mRsmpInIndex = 0;
6105 }
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006106 if (mBytesRead <= 0) {
6107 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
6108 {
6109 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006110 // Force input into standby so that it tries to
6111 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006112 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006113 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006114 }
6115 mRsmpInIndex = mFrameCount;
6116 framesOut = 0;
6117 buffer.frameCount = 0;
6118 }
6119 }
6120 }
6121 } else {
6122 // resampling
6123
6124 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6125 // alter output frame count as if we were expecting stereo samples
6126 if (mChannelCount == 1 && mReqChannelCount == 1) {
6127 framesOut >>= 1;
6128 }
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07006129 mResampler->resample(mRsmpOutBuffer, framesOut, this /* AudioBufferProvider* */);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006130 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6131 // are 32 bit aligned which should be always true.
6132 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006133 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006134 // the resampler always outputs stereo samples: do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006135 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6136 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006137 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006138 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006139 }
6140
6141 }
Eric Laurenta011e352012-03-29 15:51:43 -07006142 if (mFramestoDrop == 0) {
6143 mActiveTrack->releaseBuffer(&buffer);
6144 } else {
6145 if (mFramestoDrop > 0) {
6146 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006147 if (mFramestoDrop <= 0) {
6148 clearSyncStartEvent();
6149 }
6150 } else {
6151 mFramestoDrop += buffer.frameCount;
6152 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6153 mSyncStartEvent->isCancelled()) {
6154 ALOGW("Synced record %s, session %d, trigger session %d",
6155 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6156 mActiveTrack->sessionId(),
6157 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6158 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006159 }
6160 }
6161 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006162 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006163 }
6164 // client isn't retrieving buffers fast enough
6165 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006166 if (!mActiveTrack->setOverflow()) {
6167 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006168 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006169 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006170 lastWarning = now;
6171 }
6172 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006173 // Release the processor for a while before asking for a new buffer.
6174 // This will give the application more chance to read from the buffer and
6175 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006176 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006177 }
6178 }
Eric Laurentec437d82011-07-26 20:54:46 -07006179 // enable changes in effect chain
6180 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006181 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006182 }
6183
Glenn Kastene4e2a372012-07-23 12:55:09 -07006184 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006185
Glenn Kasten33e6e352012-07-16 15:56:57 -07006186 {
6187 Mutex::Autolock _l(mLock);
6188 mActiveTrack.clear();
6189 mStartStopCond.broadcast();
6190 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006191
Eric Laurentfeb0db62011-07-22 09:04:31 -07006192 releaseWakeLock();
6193
Steve Block3856b092011-10-20 11:56:00 +01006194 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006195 return false;
6196}
6197
Glenn Kastene4e2a372012-07-23 12:55:09 -07006198void AudioFlinger::RecordThread::standby()
6199{
6200 if (!mStandby) {
6201 inputStandBy();
6202 mStandby = true;
6203 }
6204}
6205
6206void AudioFlinger::RecordThread::inputStandBy()
6207{
6208 mInput->stream->common.standby(&mInput->stream->common);
6209}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006210
6211sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6212 const sp<AudioFlinger::Client>& client,
6213 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006214 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006215 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006216 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006217 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006218 IAudioFlinger::track_flags_t flags,
6219 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006220 status_t *status)
6221{
6222 sp<RecordTrack> track;
6223 status_t lStatus;
6224
6225 lStatus = initCheck();
6226 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006227 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006228 goto Exit;
6229 }
6230
Glenn Kasten1879fff2012-07-11 15:36:59 -07006231 // FIXME use flags and tid similar to createTrack_l()
6232
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006233 { // scope for mLock
6234 Mutex::Autolock _l(mLock);
6235
6236 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006237 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006238
Glenn Kasten7378ca52012-01-20 13:44:40 -08006239 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006240 lStatus = NO_MEMORY;
6241 goto Exit;
6242 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006243 mTracks.add(track);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006244
Eric Laurent59bd0da2011-08-01 09:52:20 -07006245 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1c04f92012-08-28 14:26:53 -07006246 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006247 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006248 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6249 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006250 }
6251 lStatus = NO_ERROR;
6252
6253Exit:
6254 if (status) {
6255 *status = lStatus;
6256 }
6257 return track;
6258}
6259
Eric Laurenta011e352012-03-29 15:51:43 -07006260status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006261 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006262 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006263{
Glenn Kasten58912562012-04-03 10:45:00 -07006264 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006265 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006266 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006267
6268 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006269 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006270 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6271 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6272 triggerSession,
6273 recordTrack->sessionId(),
6274 syncStartEventCallback,
6275 this);
Eric Laurent29864602012-05-08 18:57:51 -07006276 // Sync event can be cancelled by the trigger session if the track is not in a
6277 // compatible state in which case we start record immediately
6278 if (mSyncStartEvent->isCancelled()) {
6279 clearSyncStartEvent();
6280 } else {
6281 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6282 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6283 }
Eric Laurenta011e352012-03-29 15:51:43 -07006284 }
6285
Mathias Agopian65ab4712010-07-14 17:59:35 -07006286 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006287 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006288 if (mActiveTrack != 0) {
6289 if (recordTrack != mActiveTrack.get()) {
6290 status = -EBUSY;
6291 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6292 mActiveTrack->mState = TrackBase::ACTIVE;
6293 }
6294 return status;
6295 }
6296
6297 recordTrack->mState = TrackBase::IDLE;
6298 mActiveTrack = recordTrack;
6299 mLock.unlock();
6300 status_t status = AudioSystem::startInput(mId);
6301 mLock.lock();
6302 if (status != NO_ERROR) {
6303 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006304 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006305 return status;
6306 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006307 mRsmpInIndex = mFrameCount;
6308 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006309 if (mResampler != NULL) {
6310 mResampler->reset();
6311 }
6312 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006313 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006314 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006315 mWaitWorkCV.signal();
6316 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006317 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006318 mActiveTrack.clear();
6319 status = INVALID_OPERATION;
6320 goto startError;
6321 }
6322 mStartStopCond.wait(mLock);
6323 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006324 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006325 status = BAD_VALUE;
6326 goto startError;
6327 }
Steve Block3856b092011-10-20 11:56:00 +01006328 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006329 return status;
6330 }
6331startError:
6332 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006333 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006334 return status;
6335}
6336
Eric Laurenta011e352012-03-29 15:51:43 -07006337void AudioFlinger::RecordThread::clearSyncStartEvent()
6338{
6339 if (mSyncStartEvent != 0) {
6340 mSyncStartEvent->cancel();
6341 }
6342 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006343 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006344}
6345
6346void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6347{
6348 sp<SyncEvent> strongEvent = event.promote();
6349
6350 if (strongEvent != 0) {
6351 RecordThread *me = (RecordThread *)strongEvent->cookie();
6352 me->handleSyncStartEvent(strongEvent);
6353 }
6354}
6355
6356void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6357{
Eric Laurent29864602012-05-08 18:57:51 -07006358 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006359 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6360 // from audio HAL
6361 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006362 }
6363}
6364
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006365bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006366 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006367 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
6368 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006369 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006370 recordTrack->mState = TrackBase::PAUSING;
6371 // do not wait for mStartStopCond if exiting
6372 if (exitPending()) {
6373 return true;
6374 }
6375 mStartStopCond.wait(mLock);
6376 // if we have been restarted, recordTrack == mActiveTrack.get() here
6377 if (exitPending() || recordTrack != mActiveTrack.get()) {
6378 ALOGV("Record stopped OK");
6379 return true;
6380 }
6381 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006382}
6383
Glenn Kasten106e8a42012-08-02 13:37:12 -07006384bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07006385{
6386 return false;
6387}
6388
6389status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6390{
Glenn Kasten7aa25592012-08-02 16:37:07 -07006391#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 -07006392 if (!isValidSyncEvent(event)) {
6393 return BAD_VALUE;
6394 }
6395
Glenn Kasten510a3d62012-07-16 14:24:34 -07006396 int eventSession = event->triggerSession();
6397 status_t ret = NAME_NOT_FOUND;
6398
Eric Laurenta011e352012-03-29 15:51:43 -07006399 Mutex::Autolock _l(mLock);
6400
Glenn Kasten510a3d62012-07-16 14:24:34 -07006401 for (size_t i = 0; i < mTracks.size(); i++) {
6402 sp<RecordTrack> track = mTracks[i];
6403 if (eventSession == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07006404 (void) track->setSyncEvent(event);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006405 ret = NO_ERROR;
6406 }
Eric Laurenta011e352012-03-29 15:51:43 -07006407 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006408 return ret;
Glenn Kasten7aa25592012-08-02 16:37:07 -07006409#else
6410 return BAD_VALUE;
6411#endif
Glenn Kasten510a3d62012-07-16 14:24:34 -07006412}
6413
6414void AudioFlinger::RecordThread::RecordTrack::destroy()
6415{
6416 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
6417 sp<RecordTrack> keep(this);
6418 {
6419 sp<ThreadBase> thread = mThread.promote();
6420 if (thread != 0) {
6421 if (mState == ACTIVE || mState == RESUMING) {
6422 AudioSystem::stopInput(thread->id());
6423 }
6424 AudioSystem::releaseInput(thread->id());
6425 Mutex::Autolock _l(thread->mLock);
6426 RecordThread *recordThread = (RecordThread *) thread.get();
6427 recordThread->destroyTrack_l(this);
6428 }
6429 }
6430}
6431
6432// destroyTrack_l() must be called with ThreadBase::mLock held
6433void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6434{
6435 track->mState = TrackBase::TERMINATED;
6436 // active tracks are removed by threadLoop()
6437 if (mActiveTrack != track) {
6438 removeTrack_l(track);
6439 }
6440}
6441
6442void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6443{
6444 mTracks.remove(track);
6445 // need anything related to effects here?
Eric Laurenta011e352012-03-29 15:51:43 -07006446}
6447
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07006448void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006449{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006450 dumpInternals(fd, args);
6451 dumpTracks(fd, args);
6452 dumpEffectChains(fd, args);
6453}
6454
6455void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6456{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006457 const size_t SIZE = 256;
6458 char buffer[SIZE];
6459 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006460
6461 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6462 result.append(buffer);
6463
6464 if (mActiveTrack != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006465 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6466 result.append(buffer);
6467 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6468 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006469 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006470 result.append(buffer);
6471 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6472 result.append(buffer);
6473 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6474 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006475 } else {
Glenn Kasten510a3d62012-07-16 14:24:34 -07006476 result.append("No active record client\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006477 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006478
Mathias Agopian65ab4712010-07-14 17:59:35 -07006479 write(fd, result.string(), result.size());
6480
6481 dumpBase(fd, args);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006482}
6483
6484void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
6485{
6486 const size_t SIZE = 256;
6487 char buffer[SIZE];
6488 String8 result;
6489
6490 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
6491 result.append(buffer);
6492 RecordTrack::appendDumpHeader(result);
6493 for (size_t i = 0; i < mTracks.size(); ++i) {
6494 sp<RecordTrack> track = mTracks[i];
6495 if (track != 0) {
6496 track->dump(buffer, SIZE);
6497 result.append(buffer);
6498 }
6499 }
6500
6501 if (mActiveTrack != 0) {
6502 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
6503 result.append(buffer);
6504 RecordTrack::appendDumpHeader(result);
6505 mActiveTrack->dump(buffer, SIZE);
6506 result.append(buffer);
6507
6508 }
6509 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006510}
6511
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006512// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006513status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006514{
6515 size_t framesReq = buffer->frameCount;
6516 size_t framesReady = mFrameCount - mRsmpInIndex;
6517 int channelCount;
6518
6519 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006520 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07006521 if (mBytesRead <= 0) {
6522 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
6523 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006524 // Force input into standby so that it tries to
6525 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006526 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006527 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006528 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006529 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006530 buffer->frameCount = 0;
6531 return NOT_ENOUGH_DATA;
6532 }
6533 mRsmpInIndex = 0;
6534 framesReady = mFrameCount;
6535 }
6536
6537 if (framesReq > framesReady) {
6538 framesReq = framesReady;
6539 }
6540
6541 if (mChannelCount == 1 && mReqChannelCount == 2) {
6542 channelCount = 1;
6543 } else {
6544 channelCount = 2;
6545 }
6546 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6547 buffer->frameCount = framesReq;
6548 return NO_ERROR;
6549}
6550
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006551// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006552void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6553{
6554 mRsmpInIndex += buffer->frameCount;
6555 buffer->frameCount = 0;
6556}
6557
6558bool AudioFlinger::RecordThread::checkForNewParameters_l()
6559{
6560 bool reconfig = false;
6561
6562 while (!mNewParameters.isEmpty()) {
6563 status_t status = NO_ERROR;
6564 String8 keyValuePair = mNewParameters[0];
6565 AudioParameter param = AudioParameter(keyValuePair);
6566 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006567 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006568 int reqSamplingRate = mReqSampleRate;
6569 int reqChannelCount = mReqChannelCount;
6570
6571 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6572 reqSamplingRate = value;
6573 reconfig = true;
6574 }
6575 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006576 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006577 reconfig = true;
6578 }
6579 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006580 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006581 reconfig = true;
6582 }
6583 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6584 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006585 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006586 // if frame count is changed after track creation
6587 if (mActiveTrack != 0) {
6588 status = INVALID_OPERATION;
6589 } else {
6590 reconfig = true;
6591 }
6592 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006593 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6594 // forward device change to effects that have requested to be
6595 // aware of attached audio device.
6596 for (size_t i = 0; i < mEffectChains.size(); i++) {
6597 mEffectChains[i]->setDevice_l(value);
6598 }
Eric Laurentf1c04f92012-08-28 14:26:53 -07006599
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006600 // store input device and output device but do not forward output device to audio HAL.
6601 // Note that status is ignored by the caller for output device
6602 // (see AudioFlinger::setParameters()
Eric Laurentf1c04f92012-08-28 14:26:53 -07006603 if (audio_is_output_devices(value)) {
6604 mOutDevice = value;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006605 status = BAD_VALUE;
6606 } else {
Eric Laurentf1c04f92012-08-28 14:26:53 -07006607 mInDevice = value;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006608 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kasten510a3d62012-07-16 14:24:34 -07006609 if (mTracks.size() > 0) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07006610 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6611 mAudioFlinger->btNrecIsOff();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006612 for (size_t i = 0; i < mTracks.size(); i++) {
6613 sp<RecordTrack> track = mTracks[i];
6614 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6615 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6616 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07006617 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006618 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006619 }
Eric Laurent57b2dd12012-08-31 17:44:06 -07006620 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6621 mAudioSource != (audio_source_t)value) {
6622 // forward device change to effects that have requested to be
6623 // aware of attached audio device.
6624 for (size_t i = 0; i < mEffectChains.size(); i++) {
6625 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
6626 }
6627 mAudioSource = (audio_source_t)value;
6628 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006629 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006630 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006631 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006632 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006633 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6634 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006635 }
6636 if (reconfig) {
6637 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006638 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006639 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006640 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006641 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6642 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006643 status = NO_ERROR;
6644 }
6645 if (status == NO_ERROR) {
6646 readInputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07006647 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006648 }
6649 }
6650 }
6651
6652 mNewParameters.removeAt(0);
6653
6654 mParamStatus = status;
6655 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006656 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6657 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006658 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006659 }
6660 return reconfig;
6661}
6662
6663String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6664{
Dima Zavinfce7a472011-04-19 22:30:36 -07006665 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006666 String8 out_s8 = String8();
6667
6668 Mutex::Autolock _l(mLock);
6669 if (initCheck() != NO_ERROR) {
6670 return out_s8;
6671 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006672
Dima Zavin799a70e2011-04-18 16:57:27 -07006673 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006674 out_s8 = String8(s);
6675 free(s);
6676 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006677}
6678
6679void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6680 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006681 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006682
6683 switch (event) {
6684 case AudioSystem::INPUT_OPENED:
6685 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006686 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006687 desc.samplingRate = mSampleRate;
6688 desc.format = mFormat;
6689 desc.frameCount = mFrameCount;
6690 desc.latency = 0;
6691 param2 = &desc;
6692 break;
6693
6694 case AudioSystem::INPUT_CLOSED:
6695 default:
6696 break;
6697 }
6698 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6699}
6700
6701void AudioFlinger::RecordThread::readInputParameters()
6702{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006703 delete mRsmpInBuffer;
6704 // mRsmpInBuffer is always assigned a new[] below
6705 delete mRsmpOutBuffer;
6706 mRsmpOutBuffer = NULL;
6707 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006708 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006709
Dima Zavin799a70e2011-04-18 16:57:27 -07006710 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006711 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6712 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006713 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006714 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006715 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006716 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006717 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006718 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6719
Glenn Kasten53d76db2012-03-08 12:32:47 -08006720 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006721 {
6722 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006723 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6724 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006725 if (mChannelCount == 1 && mReqChannelCount == 2) {
6726 channelCount = 1;
6727 } else {
6728 channelCount = 2;
6729 }
6730 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6731 mResampler->setSampleRate(mSampleRate);
6732 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6733 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6734
6735 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6736 if (mChannelCount == 1 && mReqChannelCount == 1) {
6737 mFrameCount >>= 1;
6738 }
6739
6740 }
6741 mRsmpInIndex = mFrameCount;
6742}
6743
6744unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6745{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006746 Mutex::Autolock _l(mLock);
6747 if (initCheck() != NO_ERROR) {
6748 return 0;
6749 }
6750
Dima Zavin799a70e2011-04-18 16:57:27 -07006751 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006752}
6753
Glenn Kasten106e8a42012-08-02 13:37:12 -07006754uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006755{
6756 Mutex::Autolock _l(mLock);
6757 uint32_t result = 0;
6758 if (getEffectChain_l(sessionId) != 0) {
6759 result = EFFECT_SESSION;
6760 }
6761
Glenn Kasten510a3d62012-07-16 14:24:34 -07006762 for (size_t i = 0; i < mTracks.size(); ++i) {
6763 if (sessionId == mTracks[i]->sessionId()) {
6764 result |= TRACK_SESSION;
6765 break;
6766 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006767 }
6768
6769 return result;
6770}
6771
Glenn Kasten106e8a42012-08-02 13:37:12 -07006772KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent59bd0da2011-08-01 09:52:20 -07006773{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006774 KeyedVector<int, bool> ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006775 Mutex::Autolock _l(mLock);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006776 for (size_t j = 0; j < mTracks.size(); ++j) {
6777 sp<RecordThread::RecordTrack> track = mTracks[j];
6778 int sessionId = track->sessionId();
6779 if (ids.indexOfKey(sessionId) < 0) {
6780 ids.add(sessionId, true);
6781 }
6782 }
6783 return ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006784}
6785
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006786AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6787{
6788 Mutex::Autolock _l(mLock);
6789 AudioStreamIn *input = mInput;
6790 mInput = NULL;
6791 return input;
6792}
6793
6794// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006795audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006796{
6797 if (mInput == NULL) {
6798 return NULL;
6799 }
6800 return &mInput->stream->common;
6801}
6802
6803
Mathias Agopian65ab4712010-07-14 17:59:35 -07006804// ----------------------------------------------------------------------------
6805
Eric Laurenta4c5a552012-03-29 10:12:40 -07006806audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6807{
6808 if (!settingsAllowed()) {
6809 return 0;
6810 }
6811 Mutex::Autolock _l(mLock);
6812 return loadHwModule_l(name);
6813}
6814
6815// loadHwModule_l() must be called with AudioFlinger::mLock held
6816audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6817{
6818 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6819 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6820 ALOGW("loadHwModule() module %s already loaded", name);
6821 return mAudioHwDevs.keyAt(i);
6822 }
6823 }
6824
Eric Laurenta4c5a552012-03-29 10:12:40 -07006825 audio_hw_device_t *dev;
6826
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006827 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006828 if (rc) {
6829 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6830 return 0;
6831 }
6832
6833 mHardwareStatus = AUDIO_HW_INIT;
6834 rc = dev->init_check(dev);
6835 mHardwareStatus = AUDIO_HW_IDLE;
6836 if (rc) {
6837 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6838 return 0;
6839 }
6840
John Grossmanee578c02012-07-23 17:05:46 -07006841 // Check and cache this HAL's level of support for master mute and master
6842 // volume. If this is the first HAL opened, and it supports the get
6843 // methods, use the initial values provided by the HAL as the current
6844 // master mute and volume settings.
6845
6846 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
6847 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07006848 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07006849
6850 if (0 == mAudioHwDevs.size()) {
6851 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6852 if (NULL != dev->get_master_volume) {
6853 float mv;
6854 if (OK == dev->get_master_volume(dev, &mv)) {
6855 mMasterVolume = mv;
6856 }
6857 }
6858
6859 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
6860 if (NULL != dev->get_master_mute) {
6861 bool mm;
6862 if (OK == dev->get_master_mute(dev, &mm)) {
6863 mMasterMute = mm;
6864 }
6865 }
6866 }
6867
Eric Laurenta4c5a552012-03-29 10:12:40 -07006868 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07006869 if ((NULL != dev->set_master_volume) &&
6870 (OK == dev->set_master_volume(dev, mMasterVolume))) {
6871 flags = static_cast<AudioHwDevice::Flags>(flags |
6872 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
6873 }
6874
6875 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
6876 if ((NULL != dev->set_master_mute) &&
6877 (OK == dev->set_master_mute(dev, mMasterMute))) {
6878 flags = static_cast<AudioHwDevice::Flags>(flags |
6879 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
6880 }
6881
Eric Laurenta4c5a552012-03-29 10:12:40 -07006882 mHardwareStatus = AUDIO_HW_IDLE;
6883 }
6884
6885 audio_module_handle_t handle = nextUniqueId();
John Grossmanee578c02012-07-23 17:05:46 -07006886 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07006887
6888 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006889 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006890
6891 return handle;
6892
6893}
6894
6895audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6896 audio_devices_t *pDevices,
6897 uint32_t *pSamplingRate,
6898 audio_format_t *pFormat,
6899 audio_channel_mask_t *pChannelMask,
6900 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006901 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006902{
6903 status_t status;
6904 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006905 struct audio_config config = {
6906 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6907 channel_mask: pChannelMask ? *pChannelMask : 0,
6908 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6909 };
6910 audio_stream_out_t *outStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07006911 AudioHwDevice *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006912
Eric Laurenta4c5a552012-03-29 10:12:40 -07006913 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6914 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006915 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006916 config.sample_rate,
6917 config.format,
6918 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006919 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006920
6921 if (pDevices == NULL || *pDevices == 0) {
6922 return 0;
6923 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006924
Mathias Agopian65ab4712010-07-14 17:59:35 -07006925 Mutex::Autolock _l(mLock);
6926
Eric Laurenta4c5a552012-03-29 10:12:40 -07006927 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006928 if (outHwDev == NULL)
6929 return 0;
6930
John Grossmanee578c02012-07-23 17:05:46 -07006931 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006932 audio_io_handle_t id = nextUniqueId();
6933
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006934 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006935
John Grossmanee578c02012-07-23 17:05:46 -07006936 status = hwDevHal->open_output_stream(hwDevHal,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006937 id,
6938 *pDevices,
6939 (audio_output_flags_t)flags,
6940 &config,
6941 &outStream);
6942
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006943 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006944 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006945 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006946 config.sample_rate,
6947 config.format,
6948 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006949 status);
6950
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006951 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006952 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006953
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006954 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006955 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6956 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006957 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006958 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006959 } else {
6960 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006961 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006962 }
6963 mPlaybackThreads.add(id, thread);
6964
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006965 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6966 if (pFormat != NULL) *pFormat = config.format;
6967 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006968 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006969
6970 // notify client processes of the new output creation
6971 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006972
6973 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006974 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006975 ALOGI("Using module %d has the primary audio interface", module);
6976 mPrimaryHardwareDev = outHwDev;
6977
6978 AutoMutex lock(mHardwareLock);
6979 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -07006980 hwDevHal->set_mode(hwDevHal, mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006981 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006982 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006983 return id;
6984 }
6985
6986 return 0;
6987}
6988
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006989audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6990 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006991{
6992 Mutex::Autolock _l(mLock);
6993 MixerThread *thread1 = checkMixerThread_l(output1);
6994 MixerThread *thread2 = checkMixerThread_l(output2);
6995
6996 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006997 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006998 return 0;
6999 }
7000
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007001 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007002 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
7003 thread->addOutputTrack(thread2);
7004 mPlaybackThreads.add(id, thread);
7005 // notify client processes of the new output creation
7006 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7007 return id;
7008}
7009
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007010status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007011{
Glenn Kastend96c5722012-04-25 13:44:49 -07007012 return closeOutput_nonvirtual(output);
7013}
7014
7015status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
7016{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007017 // keep strong reference on the playback thread so that
7018 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007019 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007020 {
7021 Mutex::Autolock _l(mLock);
7022 thread = checkPlaybackThread_l(output);
7023 if (thread == NULL) {
7024 return BAD_VALUE;
7025 }
7026
Steve Block3856b092011-10-20 11:56:00 +01007027 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007028
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007029 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007030 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007031 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007032 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
7033 dupThread->removeOutputTrack((MixerThread *)thread.get());
7034 }
7035 }
7036 }
Glenn Kastena1117922012-01-26 10:53:32 -08007037 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007038 mPlaybackThreads.removeItem(output);
7039 }
7040 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007041 // The thread entity (active unit of execution) is no longer running here,
7042 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007043
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007044 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007045 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007046 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007047 // from now on thread->mOutput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007048 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007049 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007050 }
7051 return NO_ERROR;
7052}
7053
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007054status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007055{
7056 Mutex::Autolock _l(mLock);
7057 PlaybackThread *thread = checkPlaybackThread_l(output);
7058
7059 if (thread == NULL) {
7060 return BAD_VALUE;
7061 }
7062
Steve Block3856b092011-10-20 11:56:00 +01007063 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007064 thread->suspend();
7065
7066 return NO_ERROR;
7067}
7068
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007069status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007070{
7071 Mutex::Autolock _l(mLock);
7072 PlaybackThread *thread = checkPlaybackThread_l(output);
7073
7074 if (thread == NULL) {
7075 return BAD_VALUE;
7076 }
7077
Steve Block3856b092011-10-20 11:56:00 +01007078 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007079
7080 thread->restore();
7081
7082 return NO_ERROR;
7083}
7084
Eric Laurenta4c5a552012-03-29 10:12:40 -07007085audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
7086 audio_devices_t *pDevices,
7087 uint32_t *pSamplingRate,
7088 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07007089 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007090{
7091 status_t status;
7092 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007093 struct audio_config config = {
7094 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7095 channel_mask: pChannelMask ? *pChannelMask : 0,
7096 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7097 };
7098 uint32_t reqSamplingRate = config.sample_rate;
7099 audio_format_t reqFormat = config.format;
7100 audio_channel_mask_t reqChannels = config.channel_mask;
7101 audio_stream_in_t *inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007102 AudioHwDevice *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007103
7104 if (pDevices == NULL || *pDevices == 0) {
7105 return 0;
7106 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007107
Mathias Agopian65ab4712010-07-14 17:59:35 -07007108 Mutex::Autolock _l(mLock);
7109
Eric Laurenta4c5a552012-03-29 10:12:40 -07007110 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007111 if (inHwDev == NULL)
7112 return 0;
7113
John Grossmanee578c02012-07-23 17:05:46 -07007114 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007115 audio_io_handle_t id = nextUniqueId();
7116
John Grossmanee578c02012-07-23 17:05:46 -07007117 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007118 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007119 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007120 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007121 config.sample_rate,
7122 config.format,
7123 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007124 status);
7125
7126 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7127 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7128 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007129 if (status == BAD_VALUE &&
7130 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7131 (config.sample_rate <= 2 * reqSamplingRate) &&
7132 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007133 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007134 inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007135 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007136 }
7137
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007138 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007139 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7140
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007141 // Start record thread
7142 // RecorThread require both input and output device indication to forward to audio
7143 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007144 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007145 thread = new RecordThread(this,
7146 input,
7147 reqSamplingRate,
7148 reqChannels,
7149 id,
7150 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007151 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007152 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007153 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007154 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007155 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007156
Mathias Agopian65ab4712010-07-14 17:59:35 -07007157 // notify client processes of the new input creation
7158 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7159 return id;
7160 }
7161
7162 return 0;
7163}
7164
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007165status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007166{
Glenn Kastend96c5722012-04-25 13:44:49 -07007167 return closeInput_nonvirtual(input);
7168}
7169
7170status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7171{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007172 // keep strong reference on the record thread so that
7173 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007174 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007175 {
7176 Mutex::Autolock _l(mLock);
7177 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007178 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007179 return BAD_VALUE;
7180 }
7181
Steve Block3856b092011-10-20 11:56:00 +01007182 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007183 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007184 mRecordThreads.removeItem(input);
7185 }
7186 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007187 // The thread entity (active unit of execution) is no longer running here,
7188 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007189
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007190 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007191 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007192 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007193 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007194 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007195
7196 return NO_ERROR;
7197}
7198
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007199status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007200{
7201 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007202 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007203
7204 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7205 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007206 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007207 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007208
7209 return NO_ERROR;
7210}
7211
7212
7213int AudioFlinger::newAudioSessionId()
7214{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007215 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007216}
7217
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007218void AudioFlinger::acquireAudioSessionId(int audioSession)
7219{
7220 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007221 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007222 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007223 size_t num = mAudioSessionRefs.size();
7224 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007225 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007226 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7227 ref->mCnt++;
7228 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007229 return;
7230 }
7231 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007232 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7233 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007234}
7235
7236void AudioFlinger::releaseAudioSessionId(int audioSession)
7237{
7238 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007239 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007240 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007241 size_t num = mAudioSessionRefs.size();
7242 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007243 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007244 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7245 ref->mCnt--;
7246 ALOGV(" decremented refcount to %d", ref->mCnt);
7247 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007248 mAudioSessionRefs.removeAt(i);
7249 delete ref;
7250 purgeStaleEffects_l();
7251 }
7252 return;
7253 }
7254 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007255 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007256}
7257
7258void AudioFlinger::purgeStaleEffects_l() {
7259
Steve Block3856b092011-10-20 11:56:00 +01007260 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007261
7262 Vector< sp<EffectChain> > chains;
7263
7264 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7265 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7266 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7267 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007268 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7269 chains.push(ec);
7270 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007271 }
7272 }
7273 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7274 sp<RecordThread> t = mRecordThreads.valueAt(i);
7275 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7276 sp<EffectChain> ec = t->mEffectChains[j];
7277 chains.push(ec);
7278 }
7279 }
7280
7281 for (size_t i = 0; i < chains.size(); i++) {
7282 sp<EffectChain> ec = chains[i];
7283 int sessionid = ec->sessionId();
7284 sp<ThreadBase> t = ec->mThread.promote();
7285 if (t == 0) {
7286 continue;
7287 }
7288 size_t numsessionrefs = mAudioSessionRefs.size();
7289 bool found = false;
7290 for (size_t k = 0; k < numsessionrefs; k++) {
7291 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007292 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007293 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007294 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007295 found = true;
7296 break;
7297 }
7298 }
7299 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007300 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007301 // remove all effects from the chain
7302 while (ec->mEffects.size()) {
7303 sp<EffectModule> effect = ec->mEffects[0];
7304 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007305 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007306 if (effect->purgeHandles()) {
7307 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007308 }
7309 AudioSystem::unregisterEffect(effect->id());
7310 }
7311 }
7312 }
7313 return;
7314}
7315
Mathias Agopian65ab4712010-07-14 17:59:35 -07007316// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007317AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007318{
Glenn Kastena1117922012-01-26 10:53:32 -08007319 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007320}
7321
7322// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007323AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007324{
7325 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007326 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007327}
7328
7329// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007330AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007331{
Glenn Kastena1117922012-01-26 10:53:32 -08007332 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007333}
7334
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007335uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007336{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007337 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007338}
7339
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007340AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007341{
7342 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7343 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007344 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07007345 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007346 return thread;
7347 }
7348 }
7349 return NULL;
7350}
7351
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007352audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007353{
7354 PlaybackThread *thread = primaryPlaybackThread_l();
7355
7356 if (thread == NULL) {
7357 return 0;
7358 }
7359
Eric Laurentf1c04f92012-08-28 14:26:53 -07007360 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007361}
7362
Eric Laurenta011e352012-03-29 15:51:43 -07007363sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7364 int triggerSession,
7365 int listenerSession,
7366 sync_event_callback_t callBack,
7367 void *cookie)
7368{
7369 Mutex::Autolock _l(mLock);
7370
7371 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7372 status_t playStatus = NAME_NOT_FOUND;
7373 status_t recStatus = NAME_NOT_FOUND;
7374 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7375 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7376 if (playStatus == NO_ERROR) {
7377 return event;
7378 }
7379 }
7380 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7381 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7382 if (recStatus == NO_ERROR) {
7383 return event;
7384 }
7385 }
7386 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7387 mPendingSyncEvents.add(event);
7388 } else {
7389 ALOGV("createSyncEvent() invalid event %d", event->type());
7390 event.clear();
7391 }
7392 return event;
7393}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007394
Mathias Agopian65ab4712010-07-14 17:59:35 -07007395// ----------------------------------------------------------------------------
7396// Effect management
7397// ----------------------------------------------------------------------------
7398
7399
Glenn Kastenf587ba52012-01-26 16:25:10 -08007400status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007401{
7402 Mutex::Autolock _l(mLock);
7403 return EffectQueryNumberEffects(numEffects);
7404}
7405
Glenn Kastenf587ba52012-01-26 16:25:10 -08007406status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007407{
7408 Mutex::Autolock _l(mLock);
7409 return EffectQueryEffect(index, descriptor);
7410}
7411
Glenn Kasten5e92a782012-01-30 07:40:52 -08007412status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007413 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007414{
7415 Mutex::Autolock _l(mLock);
7416 return EffectGetDescriptor(pUuid, descriptor);
7417}
7418
7419
Mathias Agopian65ab4712010-07-14 17:59:35 -07007420sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7421 effect_descriptor_t *pDesc,
7422 const sp<IEffectClient>& effectClient,
7423 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007424 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007425 int sessionId,
7426 status_t *status,
7427 int *id,
7428 int *enabled)
7429{
7430 status_t lStatus = NO_ERROR;
7431 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007432 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007433
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007434 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007435 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007436
7437 if (pDesc == NULL) {
7438 lStatus = BAD_VALUE;
7439 goto Exit;
7440 }
7441
Eric Laurent84e9a102010-09-23 16:10:16 -07007442 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007443 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007444 lStatus = PERMISSION_DENIED;
7445 goto Exit;
7446 }
7447
Dima Zavinfce7a472011-04-19 22:30:36 -07007448 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007449 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007450 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007451 lStatus = PERMISSION_DENIED;
7452 goto Exit;
7453 }
7454
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007455 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007456 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007457 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007458 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007459 lStatus = BAD_VALUE;
7460 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007461 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007462 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007463 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007464 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007465 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007466 }
7467 }
7468
Mathias Agopian65ab4712010-07-14 17:59:35 -07007469 {
7470 Mutex::Autolock _l(mLock);
7471
Mathias Agopian65ab4712010-07-14 17:59:35 -07007472
7473 if (!EffectIsNullUuid(&pDesc->uuid)) {
7474 // if uuid is specified, request effect descriptor
7475 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7476 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007477 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007478 goto Exit;
7479 }
7480 } else {
7481 // if uuid is not specified, look for an available implementation
7482 // of the required type in effect factory
7483 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007484 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007485 lStatus = BAD_VALUE;
7486 goto Exit;
7487 }
7488 uint32_t numEffects = 0;
7489 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007490 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007491 bool found = false;
7492
7493 lStatus = EffectQueryNumberEffects(&numEffects);
7494 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007495 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007496 goto Exit;
7497 }
7498 for (uint32_t i = 0; i < numEffects; i++) {
7499 lStatus = EffectQueryEffect(i, &desc);
7500 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007501 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007502 continue;
7503 }
7504 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7505 // If matching type found save effect descriptor. If the session is
7506 // 0 and the effect is not auxiliary, continue enumeration in case
7507 // an auxiliary version of this effect type is available
7508 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08007509 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07007510 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007511 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7512 break;
7513 }
7514 }
7515 }
7516 if (!found) {
7517 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007518 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007519 goto Exit;
7520 }
7521 // For same effect type, chose auxiliary version over insert version if
7522 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007523 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007524 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08007525 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007526 }
7527 }
7528
7529 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007530 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007531 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7532 lStatus = INVALID_OPERATION;
7533 goto Exit;
7534 }
7535
Eric Laurent59255e42011-07-27 19:49:51 -07007536 // check recording permission for visualizer
7537 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7538 !recordingAllowed()) {
7539 lStatus = PERMISSION_DENIED;
7540 goto Exit;
7541 }
7542
Mathias Agopian65ab4712010-07-14 17:59:35 -07007543 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08007544 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007545
7546 // If output is not specified try to find a matching audio session ID in one of the
7547 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007548 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7549 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007550 // Note: io is never 0 when creating an effect on an input
7551 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007552 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007553 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7554 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007555 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007556 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007557 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007558 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007559 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007560 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7561 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7562 io = mRecordThreads.keyAt(i);
7563 break;
7564 }
7565 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007566 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007567 // If no output thread contains the requested session ID, default to
7568 // first output. The effect chain will be moved to the correct output
7569 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007570 if (io == 0 && mPlaybackThreads.size()) {
7571 io = mPlaybackThreads.keyAt(0);
7572 }
Steve Block3856b092011-10-20 11:56:00 +01007573 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007574 }
7575 ThreadBase *thread = checkRecordThread_l(io);
7576 if (thread == NULL) {
7577 thread = checkPlaybackThread_l(io);
7578 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007579 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007580 lStatus = BAD_VALUE;
7581 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007582 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007583 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007584
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007585 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007586
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007587 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007588 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7589 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007590 if (handle != 0 && id != NULL) {
7591 *id = handle->id();
7592 }
7593 }
7594
7595Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007596 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007597 *status = lStatus;
7598 }
7599 return handle;
7600}
7601
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007602status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7603 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007604{
Steve Block3856b092011-10-20 11:56:00 +01007605 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007606 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007607 Mutex::Autolock _l(mLock);
7608 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007609 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007610 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007611 }
Eric Laurentde070132010-07-13 04:45:46 -07007612 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7613 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007614 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007615 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007616 }
Eric Laurentde070132010-07-13 04:45:46 -07007617 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7618 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007619 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007620 return BAD_VALUE;
7621 }
7622
7623 Mutex::Autolock _dl(dstThread->mLock);
7624 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007625 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007626
Mathias Agopian65ab4712010-07-14 17:59:35 -07007627 return NO_ERROR;
7628}
7629
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007630// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007631status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007632 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007633 AudioFlinger::PlaybackThread *dstThread,
7634 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007635{
Steve Block3856b092011-10-20 11:56:00 +01007636 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007637 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007638
Eric Laurent59255e42011-07-27 19:49:51 -07007639 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007640 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007641 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007642 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007643 return INVALID_OPERATION;
7644 }
7645
Eric Laurent39e94f82010-07-28 01:32:47 -07007646 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007647 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007648 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007649 // removed.
7650 srcThread->removeEffectChain_l(chain);
7651
7652 // transfer all effects one by one so that new effect chain is created on new thread with
7653 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007654 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007655 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007656 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007657 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7658 while (effect != 0) {
7659 srcThread->removeEffect_l(effect);
7660 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007661 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7662 if (effect->state() == EffectModule::ACTIVE ||
7663 effect->state() == EffectModule::STOPPING) {
7664 effect->start();
7665 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007666 // if the move request is not received from audio policy manager, the effect must be
7667 // re-registered with the new strategy and output
7668 if (dstChain == 0) {
7669 dstChain = effect->chain().promote();
7670 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007671 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007672 srcThread->addEffect_l(effect);
7673 return NO_INIT;
7674 }
7675 strategy = dstChain->strategy();
7676 }
7677 if (reRegister) {
7678 AudioSystem::unregisterEffect(effect->id());
7679 AudioSystem::registerEffect(&effect->desc(),
7680 dstOutput,
7681 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007682 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007683 effect->id());
7684 }
Eric Laurentde070132010-07-13 04:45:46 -07007685 effect = chain->getEffectFromId_l(0);
7686 }
7687
7688 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007689}
7690
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007691
Mathias Agopian65ab4712010-07-14 17:59:35 -07007692// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007693sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007694 const sp<AudioFlinger::Client>& client,
7695 const sp<IEffectClient>& effectClient,
7696 int32_t priority,
7697 int sessionId,
7698 effect_descriptor_t *desc,
7699 int *enabled,
7700 status_t *status
7701 )
7702{
7703 sp<EffectModule> effect;
7704 sp<EffectHandle> handle;
7705 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007706 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007707 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007708 bool effectCreated = false;
7709 bool effectRegistered = false;
7710
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007711 lStatus = initCheck();
7712 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007713 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007714 goto Exit;
7715 }
7716
7717 // Do not allow effects with session ID 0 on direct output or duplicating threads
7718 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007719 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007720 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007721 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007722 lStatus = BAD_VALUE;
7723 goto Exit;
7724 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007725 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007726 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007727 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007728 desc->name, desc->flags, mType);
7729 lStatus = BAD_VALUE;
7730 goto Exit;
7731 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007732
Steve Block3856b092011-10-20 11:56:00 +01007733 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007734
7735 { // scope for mLock
7736 Mutex::Autolock _l(mLock);
7737
7738 // check for existing effect chain with the requested audio session
7739 chain = getEffectChain_l(sessionId);
7740 if (chain == 0) {
7741 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007742 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007743 chain = new EffectChain(this, sessionId);
7744 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007745 chain->setStrategy(getStrategyForSession_l(sessionId));
7746 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007747 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007748 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007749 }
7750
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007751 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007752
7753 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007754 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007755 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007756 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007757 if (lStatus != NO_ERROR) {
7758 goto Exit;
7759 }
7760 effectRegistered = true;
7761 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007762 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007763 lStatus = effect->status();
7764 if (lStatus != NO_ERROR) {
7765 goto Exit;
7766 }
Eric Laurentcab11242010-07-15 12:50:15 -07007767 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007768 if (lStatus != NO_ERROR) {
7769 goto Exit;
7770 }
7771 effectCreated = true;
7772
Eric Laurentf1c04f92012-08-28 14:26:53 -07007773 effect->setDevice(mOutDevice);
7774 effect->setDevice(mInDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007775 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07007776 effect->setAudioSource(mAudioSource);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007777 }
7778 // create effect handle and connect it to effect module
7779 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007780 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007781 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007782 *enabled = (int)effect->isEnabled();
7783 }
7784 }
7785
7786Exit:
7787 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007788 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007789 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007790 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007791 }
7792 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007793 AudioSystem::unregisterEffect(effect->id());
7794 }
7795 if (chainCreated) {
7796 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007797 }
7798 handle.clear();
7799 }
7800
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007801 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007802 *status = lStatus;
7803 }
7804 return handle;
7805}
7806
Eric Laurent717e1282012-06-29 16:36:52 -07007807sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7808{
7809 Mutex::Autolock _l(mLock);
7810 return getEffect_l(sessionId, effectId);
7811}
7812
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007813sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7814{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007815 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007816 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007817}
7818
Eric Laurentde070132010-07-13 04:45:46 -07007819// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7820// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007821status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007822{
7823 // check for existing effect chain with the requested audio session
7824 int sessionId = effect->sessionId();
7825 sp<EffectChain> chain = getEffectChain_l(sessionId);
7826 bool chainCreated = false;
7827
7828 if (chain == 0) {
7829 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007830 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007831 chain = new EffectChain(this, sessionId);
7832 addEffectChain_l(chain);
7833 chain->setStrategy(getStrategyForSession_l(sessionId));
7834 chainCreated = true;
7835 }
Steve Block3856b092011-10-20 11:56:00 +01007836 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007837
7838 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007839 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007840 this, effect->desc().name, chain.get());
7841 return BAD_VALUE;
7842 }
7843
7844 status_t status = chain->addEffect_l(effect);
7845 if (status != NO_ERROR) {
7846 if (chainCreated) {
7847 removeEffectChain_l(chain);
7848 }
7849 return status;
7850 }
7851
Eric Laurentf1c04f92012-08-28 14:26:53 -07007852 effect->setDevice(mOutDevice);
7853 effect->setDevice(mInDevice);
Eric Laurentde070132010-07-13 04:45:46 -07007854 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07007855 effect->setAudioSource(mAudioSource);
Eric Laurentde070132010-07-13 04:45:46 -07007856 return NO_ERROR;
7857}
7858
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007859void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007860
Steve Block3856b092011-10-20 11:56:00 +01007861 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007862 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007863 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7864 detachAuxEffect_l(effect->id());
7865 }
7866
7867 sp<EffectChain> chain = effect->chain().promote();
7868 if (chain != 0) {
7869 // remove effect chain if removing last effect
7870 if (chain->removeEffect_l(effect) == 0) {
7871 removeEffectChain_l(chain);
7872 }
7873 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007874 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007875 }
7876}
7877
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007878void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007879 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007880{
7881 effectChains = mEffectChains;
7882 for (size_t i = 0; i < mEffectChains.size(); i++) {
7883 mEffectChains[i]->lock();
7884 }
7885}
7886
7887void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007888 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007889{
7890 for (size_t i = 0; i < effectChains.size(); i++) {
7891 effectChains[i]->unlock();
7892 }
7893}
7894
7895sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7896{
7897 Mutex::Autolock _l(mLock);
7898 return getEffectChain_l(sessionId);
7899}
7900
Glenn Kasten106e8a42012-08-02 13:37:12 -07007901sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007902{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007903 size_t size = mEffectChains.size();
7904 for (size_t i = 0; i < size; i++) {
7905 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007906 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007907 }
7908 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007909 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007910}
7911
Glenn Kastenf78aee72012-01-04 11:00:47 -08007912void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007913{
7914 Mutex::Autolock _l(mLock);
7915 size_t size = mEffectChains.size();
7916 for (size_t i = 0; i < size; i++) {
7917 mEffectChains[i]->setMode_l(mode);
7918 }
7919}
7920
7921void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007922 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007923 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007924
Mathias Agopian65ab4712010-07-14 17:59:35 -07007925 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007926 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007927 // delete the effect module if removing last handle on it
7928 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007929 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007930 removeEffect_l(effect);
7931 AudioSystem::unregisterEffect(effect->id());
7932 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007933 }
7934}
7935
7936status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7937{
7938 int session = chain->sessionId();
7939 int16_t *buffer = mMixBuffer;
7940 bool ownsBuffer = false;
7941
Steve Block3856b092011-10-20 11:56:00 +01007942 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007943 if (session > 0) {
7944 // Only one effect chain can be present in direct output thread and it uses
7945 // the mix buffer as input
7946 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007947 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007948 buffer = new int16_t[numSamples];
7949 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007950 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007951 ownsBuffer = true;
7952 }
7953
7954 // Attach all tracks with same session ID to this chain.
7955 for (size_t i = 0; i < mTracks.size(); ++i) {
7956 sp<Track> track = mTracks[i];
7957 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007958 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007959 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007960 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007961 }
7962 }
7963
7964 // indicate all active tracks in the chain
7965 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7966 sp<Track> track = mActiveTracks[i].promote();
7967 if (track == 0) continue;
7968 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007969 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007970 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007971 }
7972 }
7973 }
7974
7975 chain->setInBuffer(buffer, ownsBuffer);
7976 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007977 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007978 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007979 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7980 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007981 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007982 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7983 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007984 // Effect chain for other sessions are inserted at beginning of effect
7985 // chains list to be processed before output mix effects. Relative order between other
7986 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007987 size_t size = mEffectChains.size();
7988 size_t i = 0;
7989 for (i = 0; i < size; i++) {
7990 if (mEffectChains[i]->sessionId() < session) break;
7991 }
7992 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007993 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007994
7995 return NO_ERROR;
7996}
7997
7998size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7999{
8000 int session = chain->sessionId();
8001
Steve Block3856b092011-10-20 11:56:00 +01008002 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008003
8004 for (size_t i = 0; i < mEffectChains.size(); i++) {
8005 if (chain == mEffectChains[i]) {
8006 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07008007 // detach all active tracks from the chain
8008 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8009 sp<Track> track = mActiveTracks[i].promote();
8010 if (track == 0) continue;
8011 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008012 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07008013 chain.get(), session);
8014 chain->decActiveTrackCnt();
8015 }
8016 }
8017
Mathias Agopian65ab4712010-07-14 17:59:35 -07008018 // detach all tracks with same session ID from this chain
8019 for (size_t i = 0; i < mTracks.size(); ++i) {
8020 sp<Track> track = mTracks[i];
8021 if (session == track->sessionId()) {
8022 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008023 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008024 }
8025 }
Eric Laurentde070132010-07-13 04:45:46 -07008026 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008027 }
8028 }
8029 return mEffectChains.size();
8030}
8031
Eric Laurentde070132010-07-13 04:45:46 -07008032status_t AudioFlinger::PlaybackThread::attachAuxEffect(
8033 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008034{
8035 Mutex::Autolock _l(mLock);
8036 return attachAuxEffect_l(track, EffectId);
8037}
8038
Eric Laurentde070132010-07-13 04:45:46 -07008039status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
8040 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008041{
8042 status_t status = NO_ERROR;
8043
8044 if (EffectId == 0) {
8045 track->setAuxBuffer(0, NULL);
8046 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07008047 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
8048 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008049 if (effect != 0) {
8050 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8051 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
8052 } else {
8053 status = INVALID_OPERATION;
8054 }
8055 } else {
8056 status = BAD_VALUE;
8057 }
8058 }
8059 return status;
8060}
8061
8062void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
8063{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008064 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008065 sp<Track> track = mTracks[i];
8066 if (track->auxEffectId() == effectId) {
8067 attachAuxEffect_l(track, 0);
8068 }
8069 }
8070}
8071
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008072status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8073{
8074 // only one chain per input thread
8075 if (mEffectChains.size() != 0) {
8076 return INVALID_OPERATION;
8077 }
Steve Block3856b092011-10-20 11:56:00 +01008078 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008079
8080 chain->setInBuffer(NULL);
8081 chain->setOutBuffer(NULL);
8082
Eric Laurent59255e42011-07-27 19:49:51 -07008083 checkSuspendOnAddEffectChain_l(chain);
8084
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008085 mEffectChains.add(chain);
8086
8087 return NO_ERROR;
8088}
8089
8090size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8091{
Steve Block3856b092011-10-20 11:56:00 +01008092 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00008093 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008094 "removeEffectChain_l() %p invalid chain size %d on thread %p",
8095 chain.get(), mEffectChains.size(), this);
8096 if (mEffectChains.size() == 1) {
8097 mEffectChains.removeAt(0);
8098 }
8099 return 0;
8100}
8101
Mathias Agopian65ab4712010-07-14 17:59:35 -07008102// ----------------------------------------------------------------------------
8103// EffectModule implementation
8104// ----------------------------------------------------------------------------
8105
8106#undef LOG_TAG
8107#define LOG_TAG "AudioFlinger::EffectModule"
8108
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008109AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008110 const wp<AudioFlinger::EffectChain>& chain,
8111 effect_descriptor_t *desc,
8112 int id,
8113 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07008114 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
8115 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07008116 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07008117 // mConfig is set by configure() and not used before then
8118 mEffectInterface(NULL),
8119 mStatus(NO_INIT), mState(IDLE),
8120 // mMaxDisableWaitCnt is set by configure() and not used before then
8121 // mDisableWaitCnt is set by process() and updateState() and not used before then
8122 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008123{
Steve Block3856b092011-10-20 11:56:00 +01008124 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008125 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008126
8127 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008128 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008129
8130 if (mStatus != NO_ERROR) {
8131 return;
8132 }
8133 lStatus = init();
8134 if (lStatus < 0) {
8135 mStatus = lStatus;
8136 goto Error;
8137 }
8138
Steve Block3856b092011-10-20 11:56:00 +01008139 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008140 return;
8141Error:
8142 EffectRelease(mEffectInterface);
8143 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008144 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008145}
8146
8147AudioFlinger::EffectModule::~EffectModule()
8148{
Steve Block3856b092011-10-20 11:56:00 +01008149 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008150 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008151 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8152 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8153 sp<ThreadBase> thread = mThread.promote();
8154 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008155 audio_stream_t *stream = thread->stream();
8156 if (stream != NULL) {
8157 stream->remove_audio_effect(stream, mEffectInterface);
8158 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008159 }
8160 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008161 // release effect engine
8162 EffectRelease(mEffectInterface);
8163 }
8164}
8165
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008166status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008167{
8168 status_t status;
8169
8170 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008171 int priority = handle->priority();
8172 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008173 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008174 size_t i;
8175 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008176 EffectHandle *h = mHandles[i];
8177 if (h == NULL || h->destroyed_l()) continue;
8178 // first non destroyed handle is considered in control
8179 if (controlHandle == NULL)
8180 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008181 if (h->priority() <= priority) break;
8182 }
8183 // if inserted in first place, move effect control from previous owner to this handle
8184 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008185 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008186 if (controlHandle != NULL) {
8187 enabled = controlHandle->enabled();
8188 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008189 }
Eric Laurent59255e42011-07-27 19:49:51 -07008190 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008191 status = NO_ERROR;
8192 } else {
8193 status = ALREADY_EXISTS;
8194 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008195 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008196 mHandles.insertAt(handle, i);
8197 return status;
8198}
8199
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008200size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008201{
8202 Mutex::Autolock _l(mLock);
8203 size_t size = mHandles.size();
8204 size_t i;
8205 for (i = 0; i < size; i++) {
8206 if (mHandles[i] == handle) break;
8207 }
8208 if (i == size) {
8209 return size;
8210 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008211 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008212
Mathias Agopian65ab4712010-07-14 17:59:35 -07008213 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008214 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008215 if (i == 0) {
8216 EffectHandle *h = controlHandle_l();
8217 if (h != NULL) {
8218 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008219 }
8220 }
8221
Eric Laurentec437d82011-07-26 20:54:46 -07008222 // Prevent calls to process() and other functions on effect interface from now on.
8223 // The effect engine will be released by the destructor when the last strong reference on
8224 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008225 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008226 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008227 }
8228
Eric Laurente65c8912012-07-20 15:57:23 -07008229 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008230}
8231
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008232// must be called with EffectModule::mLock held
8233AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008234{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008235 // the first valid handle in the list has control over the module
8236 for (size_t i = 0; i < mHandles.size(); i++) {
8237 EffectHandle *h = mHandles[i];
8238 if (h != NULL && !h->destroyed_l()) {
8239 return h;
8240 }
8241 }
8242
8243 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008244}
8245
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008246size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008247{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008248 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008249 // keep a strong reference on this EffectModule to avoid calling the
8250 // destructor before we exit
8251 sp<EffectModule> keep(this);
8252 {
8253 sp<ThreadBase> thread = mThread.promote();
8254 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008255 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008256 }
8257 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008258 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008259}
8260
8261void AudioFlinger::EffectModule::updateState() {
8262 Mutex::Autolock _l(mLock);
8263
8264 switch (mState) {
8265 case RESTART:
8266 reset_l();
8267 // FALL THROUGH
8268
8269 case STARTING:
8270 // clear auxiliary effect input buffer for next accumulation
8271 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8272 memset(mConfig.inputCfg.buffer.raw,
8273 0,
8274 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8275 }
8276 start_l();
8277 mState = ACTIVE;
8278 break;
8279 case STOPPING:
8280 stop_l();
8281 mDisableWaitCnt = mMaxDisableWaitCnt;
8282 mState = STOPPED;
8283 break;
8284 case STOPPED:
8285 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8286 // turn off sequence.
8287 if (--mDisableWaitCnt == 0) {
8288 reset_l();
8289 mState = IDLE;
8290 }
8291 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008292 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008293 break;
8294 }
8295}
8296
8297void AudioFlinger::EffectModule::process()
8298{
8299 Mutex::Autolock _l(mLock);
8300
Eric Laurentec437d82011-07-26 20:54:46 -07008301 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008302 mConfig.inputCfg.buffer.raw == NULL ||
8303 mConfig.outputCfg.buffer.raw == NULL) {
8304 return;
8305 }
8306
Eric Laurent8f45bd72010-08-31 13:50:07 -07008307 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008308 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8309 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008310 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008311 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008312 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008313 }
8314
8315 // do the actual processing in the effect engine
8316 int ret = (*mEffectInterface)->process(mEffectInterface,
8317 &mConfig.inputCfg.buffer,
8318 &mConfig.outputCfg.buffer);
8319
8320 // force transition to IDLE state when engine is ready
8321 if (mState == STOPPED && ret == -ENODATA) {
8322 mDisableWaitCnt = 1;
8323 }
8324
8325 // clear auxiliary effect input buffer for next accumulation
8326 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008327 memset(mConfig.inputCfg.buffer.raw, 0,
8328 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008329 }
8330 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008331 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8332 // If an insert effect is idle and input buffer is different from output buffer,
8333 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008334 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008335 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008336 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8337 int16_t *in = mConfig.inputCfg.buffer.s16;
8338 int16_t *out = mConfig.outputCfg.buffer.s16;
8339 for (size_t i = 0; i < frameCnt; i++) {
8340 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008341 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008342 }
8343 }
8344}
8345
8346void AudioFlinger::EffectModule::reset_l()
8347{
8348 if (mEffectInterface == NULL) {
8349 return;
8350 }
8351 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8352}
8353
8354status_t AudioFlinger::EffectModule::configure()
8355{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008356 if (mEffectInterface == NULL) {
8357 return NO_INIT;
8358 }
8359
8360 sp<ThreadBase> thread = mThread.promote();
8361 if (thread == 0) {
8362 return DEAD_OBJECT;
8363 }
8364
8365 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07008366 audio_channel_mask_t channelMask = thread->channelMask();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008367
8368 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008369 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008370 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07008371 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008372 }
Glenn Kasten254af182012-07-03 14:59:05 -07008373 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07008374 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8375 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008376 mConfig.inputCfg.samplingRate = thread->sampleRate();
8377 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8378 mConfig.inputCfg.bufferProvider.cookie = NULL;
8379 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8380 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8381 mConfig.outputCfg.bufferProvider.cookie = NULL;
8382 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8383 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8384 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8385 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008386 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008387 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008388 // - in other sessions:
8389 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8390 // other effect: overwrites output buffer: input buffer == output buffer
8391 // Auxiliary effect:
8392 // accumulates in output buffer: input buffer != output buffer
8393 // Therefore: accumulate <=> input buffer != output buffer
8394 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8395 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8396 } else {
8397 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8398 }
8399 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8400 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8401 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8402 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8403
Steve Block3856b092011-10-20 11:56:00 +01008404 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008405 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8406
Mathias Agopian65ab4712010-07-14 17:59:35 -07008407 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008408 uint32_t size = sizeof(int);
8409 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008410 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008411 sizeof(effect_config_t),
8412 &mConfig,
8413 &size,
8414 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008415 if (status == 0) {
8416 status = cmdStatus;
8417 }
8418
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008419 if (status == 0 &&
8420 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8421 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8422 effect_param_t *p = (effect_param_t *)buf32;
8423
8424 p->psize = sizeof(uint32_t);
8425 p->vsize = sizeof(uint32_t);
8426 size = sizeof(int);
8427 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8428
8429 uint32_t latency = 0;
8430 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8431 if (pbt != NULL) {
8432 latency = pbt->latency_l();
8433 }
8434
8435 *((int32_t *)p->data + 1)= latency;
8436 (*mEffectInterface)->command(mEffectInterface,
8437 EFFECT_CMD_SET_PARAM,
8438 sizeof(effect_param_t) + 8,
8439 &buf32,
8440 &size,
8441 &cmdStatus);
8442 }
8443
Mathias Agopian65ab4712010-07-14 17:59:35 -07008444 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8445 (1000 * mConfig.outputCfg.buffer.frameCount);
8446
8447 return status;
8448}
8449
8450status_t AudioFlinger::EffectModule::init()
8451{
8452 Mutex::Autolock _l(mLock);
8453 if (mEffectInterface == NULL) {
8454 return NO_INIT;
8455 }
8456 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008457 uint32_t size = sizeof(status_t);
8458 status_t status = (*mEffectInterface)->command(mEffectInterface,
8459 EFFECT_CMD_INIT,
8460 0,
8461 NULL,
8462 &size,
8463 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008464 if (status == 0) {
8465 status = cmdStatus;
8466 }
8467 return status;
8468}
8469
Eric Laurentec35a142011-10-05 17:42:25 -07008470status_t AudioFlinger::EffectModule::start()
8471{
8472 Mutex::Autolock _l(mLock);
8473 return start_l();
8474}
8475
Mathias Agopian65ab4712010-07-14 17:59:35 -07008476status_t AudioFlinger::EffectModule::start_l()
8477{
8478 if (mEffectInterface == NULL) {
8479 return NO_INIT;
8480 }
8481 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008482 uint32_t size = sizeof(status_t);
8483 status_t status = (*mEffectInterface)->command(mEffectInterface,
8484 EFFECT_CMD_ENABLE,
8485 0,
8486 NULL,
8487 &size,
8488 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008489 if (status == 0) {
8490 status = cmdStatus;
8491 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008492 if (status == 0 &&
8493 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8494 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8495 sp<ThreadBase> thread = mThread.promote();
8496 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008497 audio_stream_t *stream = thread->stream();
8498 if (stream != NULL) {
8499 stream->add_audio_effect(stream, mEffectInterface);
8500 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008501 }
8502 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008503 return status;
8504}
8505
Eric Laurentec437d82011-07-26 20:54:46 -07008506status_t AudioFlinger::EffectModule::stop()
8507{
8508 Mutex::Autolock _l(mLock);
8509 return stop_l();
8510}
8511
Mathias Agopian65ab4712010-07-14 17:59:35 -07008512status_t AudioFlinger::EffectModule::stop_l()
8513{
8514 if (mEffectInterface == NULL) {
8515 return NO_INIT;
8516 }
8517 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008518 uint32_t size = sizeof(status_t);
8519 status_t status = (*mEffectInterface)->command(mEffectInterface,
8520 EFFECT_CMD_DISABLE,
8521 0,
8522 NULL,
8523 &size,
8524 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008525 if (status == 0) {
8526 status = cmdStatus;
8527 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008528 if (status == 0 &&
8529 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8530 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8531 sp<ThreadBase> thread = mThread.promote();
8532 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008533 audio_stream_t *stream = thread->stream();
8534 if (stream != NULL) {
8535 stream->remove_audio_effect(stream, mEffectInterface);
8536 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008537 }
8538 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008539 return status;
8540}
8541
Eric Laurent25f43952010-07-28 05:40:18 -07008542status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8543 uint32_t cmdSize,
8544 void *pCmdData,
8545 uint32_t *replySize,
8546 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008547{
8548 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008549// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008550
Eric Laurentec437d82011-07-26 20:54:46 -07008551 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008552 return NO_INIT;
8553 }
Eric Laurent25f43952010-07-28 05:40:18 -07008554 status_t status = (*mEffectInterface)->command(mEffectInterface,
8555 cmdCode,
8556 cmdSize,
8557 pCmdData,
8558 replySize,
8559 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008560 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008561 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008562 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008563 EffectHandle *h = mHandles[i];
8564 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008565 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8566 }
8567 }
8568 }
8569 return status;
8570}
8571
8572status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8573{
8574 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008575 return setEnabled_l(enabled);
8576}
8577
8578// must be called with EffectModule::mLock held
8579status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8580{
8581
Steve Block3856b092011-10-20 11:56:00 +01008582 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008583
8584 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008585 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8586 if (enabled && status != NO_ERROR) {
8587 return status;
8588 }
8589
Mathias Agopian65ab4712010-07-14 17:59:35 -07008590 switch (mState) {
8591 // going from disabled to enabled
8592 case IDLE:
8593 mState = STARTING;
8594 break;
8595 case STOPPED:
8596 mState = RESTART;
8597 break;
8598 case STOPPING:
8599 mState = ACTIVE;
8600 break;
8601
8602 // going from enabled to disabled
8603 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008604 mState = STOPPED;
8605 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008606 case STARTING:
8607 mState = IDLE;
8608 break;
8609 case ACTIVE:
8610 mState = STOPPING;
8611 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008612 case DESTROYED:
8613 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008614 }
8615 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008616 EffectHandle *h = mHandles[i];
8617 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008618 h->setEnabled(enabled);
8619 }
8620 }
8621 }
8622 return NO_ERROR;
8623}
8624
Glenn Kastenc59c0042012-02-02 14:06:11 -08008625bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008626{
8627 switch (mState) {
8628 case RESTART:
8629 case STARTING:
8630 case ACTIVE:
8631 return true;
8632 case IDLE:
8633 case STOPPING:
8634 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008635 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008636 default:
8637 return false;
8638 }
8639}
8640
Glenn Kastenc59c0042012-02-02 14:06:11 -08008641bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008642{
8643 switch (mState) {
8644 case RESTART:
8645 case ACTIVE:
8646 case STOPPING:
8647 case STOPPED:
8648 return true;
8649 case IDLE:
8650 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008651 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008652 default:
8653 return false;
8654 }
8655}
8656
Mathias Agopian65ab4712010-07-14 17:59:35 -07008657status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8658{
8659 Mutex::Autolock _l(mLock);
8660 status_t status = NO_ERROR;
8661
8662 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8663 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008664 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008665 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8666 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008667 status_t cmdStatus;
8668 uint32_t volume[2];
8669 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008670 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008671 volume[0] = *left;
8672 volume[1] = *right;
8673 if (controller) {
8674 pVolume = volume;
8675 }
Eric Laurent25f43952010-07-28 05:40:18 -07008676 status = (*mEffectInterface)->command(mEffectInterface,
8677 EFFECT_CMD_SET_VOLUME,
8678 size,
8679 volume,
8680 &size,
8681 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008682 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8683 *left = volume[0];
8684 *right = volume[1];
8685 }
8686 }
8687 return status;
8688}
8689
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008690status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008691{
Eric Laurentf1c04f92012-08-28 14:26:53 -07008692 if (device == AUDIO_DEVICE_NONE) {
8693 return NO_ERROR;
8694 }
8695
Mathias Agopian65ab4712010-07-14 17:59:35 -07008696 Mutex::Autolock _l(mLock);
8697 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008698 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07008699 status_t cmdStatus;
8700 uint32_t size = sizeof(status_t);
8701 uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE :
8702 EFFECT_CMD_SET_INPUT_DEVICE;
8703 status = (*mEffectInterface)->command(mEffectInterface,
8704 cmd,
8705 sizeof(uint32_t),
8706 &device,
8707 &size,
8708 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008709 }
8710 return status;
8711}
8712
Glenn Kastenf78aee72012-01-04 11:00:47 -08008713status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008714{
8715 Mutex::Autolock _l(mLock);
8716 status_t status = NO_ERROR;
8717 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008718 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008719 uint32_t size = sizeof(status_t);
8720 status = (*mEffectInterface)->command(mEffectInterface,
8721 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008722 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008723 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008724 &size,
8725 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008726 if (status == NO_ERROR) {
8727 status = cmdStatus;
8728 }
8729 }
8730 return status;
8731}
8732
Eric Laurent57b2dd12012-08-31 17:44:06 -07008733status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
8734{
8735 Mutex::Autolock _l(mLock);
8736 status_t status = NO_ERROR;
8737 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
8738 uint32_t size = 0;
8739 status = (*mEffectInterface)->command(mEffectInterface,
8740 EFFECT_CMD_SET_AUDIO_SOURCE,
8741 sizeof(audio_source_t),
8742 &source,
8743 &size,
8744 NULL);
8745 }
8746 return status;
8747}
8748
Eric Laurent59255e42011-07-27 19:49:51 -07008749void AudioFlinger::EffectModule::setSuspended(bool suspended)
8750{
8751 Mutex::Autolock _l(mLock);
8752 mSuspended = suspended;
8753}
Glenn Kastena3a85482012-01-04 11:01:11 -08008754
8755bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008756{
8757 Mutex::Autolock _l(mLock);
8758 return mSuspended;
8759}
8760
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008761bool AudioFlinger::EffectModule::purgeHandles()
8762{
8763 bool enabled = false;
8764 Mutex::Autolock _l(mLock);
8765 for (size_t i = 0; i < mHandles.size(); i++) {
8766 EffectHandle *handle = mHandles[i];
8767 if (handle != NULL && !handle->destroyed_l()) {
8768 handle->effect().clear();
8769 if (handle->hasControl()) {
8770 enabled = handle->enabled();
8771 }
8772 }
8773 }
8774 return enabled;
8775}
8776
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07008777void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008778{
8779 const size_t SIZE = 256;
8780 char buffer[SIZE];
8781 String8 result;
8782
8783 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8784 result.append(buffer);
8785
8786 bool locked = tryLock(mLock);
8787 // failed to lock - AudioFlinger is probably deadlocked
8788 if (!locked) {
8789 result.append("\t\tCould not lock Fx mutex:\n");
8790 }
8791
8792 result.append("\t\tSession Status State Engine:\n");
8793 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8794 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8795 result.append(buffer);
8796
8797 result.append("\t\tDescriptor:\n");
8798 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8799 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8800 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8801 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8802 result.append(buffer);
8803 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8804 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8805 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8806 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8807 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008808 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008809 mDescriptor.apiVersion,
8810 mDescriptor.flags);
8811 result.append(buffer);
8812 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8813 mDescriptor.name);
8814 result.append(buffer);
8815 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8816 mDescriptor.implementor);
8817 result.append(buffer);
8818
8819 result.append("\t\t- Input configuration:\n");
8820 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8821 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8822 (uint32_t)mConfig.inputCfg.buffer.raw,
8823 mConfig.inputCfg.buffer.frameCount,
8824 mConfig.inputCfg.samplingRate,
8825 mConfig.inputCfg.channels,
8826 mConfig.inputCfg.format);
8827 result.append(buffer);
8828
8829 result.append("\t\t- Output configuration:\n");
8830 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8831 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8832 (uint32_t)mConfig.outputCfg.buffer.raw,
8833 mConfig.outputCfg.buffer.frameCount,
8834 mConfig.outputCfg.samplingRate,
8835 mConfig.outputCfg.channels,
8836 mConfig.outputCfg.format);
8837 result.append(buffer);
8838
8839 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8840 result.append(buffer);
8841 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8842 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008843 EffectHandle *handle = mHandles[i];
8844 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008845 handle->dump(buffer, SIZE);
8846 result.append(buffer);
8847 }
8848 }
8849
8850 result.append("\n");
8851
8852 write(fd, result.string(), result.length());
8853
8854 if (locked) {
8855 mLock.unlock();
8856 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008857}
8858
8859// ----------------------------------------------------------------------------
8860// EffectHandle implementation
8861// ----------------------------------------------------------------------------
8862
8863#undef LOG_TAG
8864#define LOG_TAG "AudioFlinger::EffectHandle"
8865
8866AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8867 const sp<AudioFlinger::Client>& client,
8868 const sp<IEffectClient>& effectClient,
8869 int32_t priority)
8870 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008871 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008872 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008873{
Steve Block3856b092011-10-20 11:56:00 +01008874 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008875
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008876 if (client == 0) {
8877 return;
8878 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008879 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8880 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8881 if (mCblkMemory != 0) {
8882 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8883
Glenn Kastena0d68332012-01-27 16:47:15 -08008884 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008885 new(mCblk) effect_param_cblk_t();
8886 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008887 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008888 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008889 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008890 return;
8891 }
8892}
8893
8894AudioFlinger::EffectHandle::~EffectHandle()
8895{
Steve Block3856b092011-10-20 11:56:00 +01008896 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008897
8898 if (mEffect == 0) {
8899 mDestroyed = true;
8900 return;
8901 }
8902 mEffect->lock();
8903 mDestroyed = true;
8904 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008905 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008906}
8907
8908status_t AudioFlinger::EffectHandle::enable()
8909{
Steve Block3856b092011-10-20 11:56:00 +01008910 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008911 if (!mHasControl) return INVALID_OPERATION;
8912 if (mEffect == 0) return DEAD_OBJECT;
8913
Eric Laurentdb7c0792011-08-10 10:37:50 -07008914 if (mEnabled) {
8915 return NO_ERROR;
8916 }
8917
Eric Laurent59255e42011-07-27 19:49:51 -07008918 mEnabled = true;
8919
8920 sp<ThreadBase> thread = mEffect->thread().promote();
8921 if (thread != 0) {
8922 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8923 }
8924
8925 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8926 if (mEffect->suspended()) {
8927 return NO_ERROR;
8928 }
8929
Eric Laurentdb7c0792011-08-10 10:37:50 -07008930 status_t status = mEffect->setEnabled(true);
8931 if (status != NO_ERROR) {
8932 if (thread != 0) {
8933 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8934 }
8935 mEnabled = false;
8936 }
8937 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008938}
8939
8940status_t AudioFlinger::EffectHandle::disable()
8941{
Steve Block3856b092011-10-20 11:56:00 +01008942 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008943 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008944 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008945
Eric Laurentdb7c0792011-08-10 10:37:50 -07008946 if (!mEnabled) {
8947 return NO_ERROR;
8948 }
Eric Laurent59255e42011-07-27 19:49:51 -07008949 mEnabled = false;
8950
8951 if (mEffect->suspended()) {
8952 return NO_ERROR;
8953 }
8954
8955 status_t status = mEffect->setEnabled(false);
8956
8957 sp<ThreadBase> thread = mEffect->thread().promote();
8958 if (thread != 0) {
8959 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8960 }
8961
8962 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008963}
8964
8965void AudioFlinger::EffectHandle::disconnect()
8966{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008967 disconnect(true);
8968}
8969
Glenn Kasten58123c32012-02-03 10:32:24 -08008970void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008971{
Glenn Kasten58123c32012-02-03 10:32:24 -08008972 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008973 if (mEffect == 0) {
8974 return;
8975 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008976 // restore suspended effects if the disconnected handle was enabled and the last one.
8977 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008978 sp<ThreadBase> thread = mEffect->thread().promote();
8979 if (thread != 0) {
8980 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8981 }
Eric Laurent59255e42011-07-27 19:49:51 -07008982 }
8983
Mathias Agopian65ab4712010-07-14 17:59:35 -07008984 // release sp on module => module destructor can be called now
8985 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008986 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008987 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008988 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008989 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8990 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008991 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008992 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008993 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8994 mClient.clear();
8995 }
8996}
8997
Eric Laurent25f43952010-07-28 05:40:18 -07008998status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8999 uint32_t cmdSize,
9000 void *pCmdData,
9001 uint32_t *replySize,
9002 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009003{
Steve Block3856b092011-10-20 11:56:00 +01009004// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07009005// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07009006
9007 // only get parameter command is permitted for applications not controlling the effect
9008 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
9009 return INVALID_OPERATION;
9010 }
9011 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009012 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009013
9014 // handle commands that are not forwarded transparently to effect engine
9015 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
9016 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
9017 // no risk to block the whole media server process or mixer threads is we are stuck here
9018 Mutex::Autolock _l(mCblk->lock);
9019 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
9020 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
9021 mCblk->serverIndex = 0;
9022 mCblk->clientIndex = 0;
9023 return BAD_VALUE;
9024 }
9025 status_t status = NO_ERROR;
9026 while (mCblk->serverIndex < mCblk->clientIndex) {
9027 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07009028 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009029 int *p = (int *)(mBuffer + mCblk->serverIndex);
9030 int size = *p++;
9031 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009032 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009033 break;
9034 }
9035 effect_param_t *param = (effect_param_t *)p;
9036 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009037 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009038 mCblk->serverIndex += size;
9039 continue;
9040 }
Eric Laurent25f43952010-07-28 05:40:18 -07009041 uint32_t psize = sizeof(effect_param_t) +
9042 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
9043 param->vsize;
9044 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
9045 psize,
9046 p,
9047 &rsize,
9048 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07009049 // stop at first error encountered
9050 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009051 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07009052 *(int *)pReplyData = reply;
9053 break;
9054 } else if (reply != NO_ERROR) {
9055 *(int *)pReplyData = reply;
9056 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009057 }
9058 mCblk->serverIndex += size;
9059 }
9060 mCblk->serverIndex = 0;
9061 mCblk->clientIndex = 0;
9062 return status;
9063 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009064 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009065 return enable();
9066 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009067 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009068 return disable();
9069 }
9070
9071 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9072}
9073
Eric Laurent59255e42011-07-27 19:49:51 -07009074void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009075{
Steve Block3856b092011-10-20 11:56:00 +01009076 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009077
9078 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07009079 mEnabled = enabled;
9080
Mathias Agopian65ab4712010-07-14 17:59:35 -07009081 if (signal && mEffectClient != 0) {
9082 mEffectClient->controlStatusChanged(hasControl);
9083 }
9084}
9085
Eric Laurent25f43952010-07-28 05:40:18 -07009086void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
9087 uint32_t cmdSize,
9088 void *pCmdData,
9089 uint32_t replySize,
9090 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009091{
9092 if (mEffectClient != 0) {
9093 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9094 }
9095}
9096
9097
9098
9099void AudioFlinger::EffectHandle::setEnabled(bool enabled)
9100{
9101 if (mEffectClient != 0) {
9102 mEffectClient->enableStatusChanged(enabled);
9103 }
9104}
9105
9106status_t AudioFlinger::EffectHandle::onTransact(
9107 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9108{
9109 return BnEffect::onTransact(code, data, reply, flags);
9110}
9111
9112
9113void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
9114{
Glenn Kastena0d68332012-01-27 16:47:15 -08009115 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009116
9117 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08009118 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07009119 mPriority,
9120 mHasControl,
9121 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009122 mCblk ? mCblk->clientIndex : 0,
9123 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07009124 );
9125
9126 if (locked) {
9127 mCblk->lock.unlock();
9128 }
9129}
9130
9131#undef LOG_TAG
9132#define LOG_TAG "AudioFlinger::EffectChain"
9133
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009134AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009135 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009136 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07009137 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9138 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009139{
Dima Zavinfce7a472011-04-19 22:30:36 -07009140 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009141 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009142 return;
9143 }
9144 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9145 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009146}
9147
9148AudioFlinger::EffectChain::~EffectChain()
9149{
9150 if (mOwnInBuffer) {
9151 delete mInBuffer;
9152 }
9153
9154}
9155
Eric Laurent59255e42011-07-27 19:49:51 -07009156// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009157sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009158{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009159 size_t size = mEffects.size();
9160
9161 for (size_t i = 0; i < size; i++) {
9162 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009163 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009164 }
9165 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009166 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009167}
9168
Eric Laurent59255e42011-07-27 19:49:51 -07009169// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009170sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009171{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009172 size_t size = mEffects.size();
9173
9174 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009175 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9176 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009177 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009178 }
9179 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009180 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009181}
9182
Eric Laurent59255e42011-07-27 19:49:51 -07009183// getEffectFromType_l() must be called with ThreadBase::mLock held
9184sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9185 const effect_uuid_t *type)
9186{
Eric Laurent59255e42011-07-27 19:49:51 -07009187 size_t size = mEffects.size();
9188
9189 for (size_t i = 0; i < size; i++) {
9190 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009191 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009192 }
9193 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009194 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009195}
9196
Eric Laurent91b14c42012-05-30 12:30:29 -07009197void AudioFlinger::EffectChain::clearInputBuffer()
9198{
9199 Mutex::Autolock _l(mLock);
9200 sp<ThreadBase> thread = mThread.promote();
9201 if (thread == 0) {
9202 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9203 return;
9204 }
9205 clearInputBuffer_l(thread);
9206}
9207
9208// Must be called with EffectChain::mLock locked
9209void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9210{
9211 size_t numSamples = thread->frameCount() * thread->channelCount();
9212 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9213
9214}
9215
Mathias Agopian65ab4712010-07-14 17:59:35 -07009216// Must be called with EffectChain::mLock locked
9217void AudioFlinger::EffectChain::process_l()
9218{
Eric Laurentdac69112010-09-28 14:09:57 -07009219 sp<ThreadBase> thread = mThread.promote();
9220 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009221 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009222 return;
9223 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009224 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9225 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009226 // always process effects unless no more tracks are on the session and the effect tail
9227 // has been rendered
9228 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009229 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009230 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009231
Eric Laurent544fe9b2011-11-11 15:42:52 -08009232 if (!tracksOnSession && mTailBufferCount == 0) {
9233 doProcess = false;
9234 }
9235
9236 if (activeTrackCnt() == 0) {
9237 // if no track is active and the effect tail has not been rendered,
9238 // the input buffer must be cleared here as the mixer process will not do it
9239 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009240 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009241 if (mTailBufferCount > 0) {
9242 mTailBufferCount--;
9243 }
9244 }
9245 }
Eric Laurentdac69112010-09-28 14:09:57 -07009246 }
9247
Mathias Agopian65ab4712010-07-14 17:59:35 -07009248 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009249 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009250 for (size_t i = 0; i < size; i++) {
9251 mEffects[i]->process();
9252 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009253 }
9254 for (size_t i = 0; i < size; i++) {
9255 mEffects[i]->updateState();
9256 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009257}
9258
Eric Laurentcab11242010-07-15 12:50:15 -07009259// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009260status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009261{
9262 effect_descriptor_t desc = effect->desc();
9263 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9264
9265 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009266 effect->setChain(this);
9267 sp<ThreadBase> thread = mThread.promote();
9268 if (thread == 0) {
9269 return NO_INIT;
9270 }
9271 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009272
9273 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9274 // Auxiliary effects are inserted at the beginning of mEffects vector as
9275 // they are processed first and accumulated in chain input buffer
9276 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009277
Mathias Agopian65ab4712010-07-14 17:59:35 -07009278 // the input buffer for auxiliary effect contains mono samples in
9279 // 32 bit format. This is to avoid saturation in AudoMixer
9280 // accumulation stage. Saturation is done in EffectModule::process() before
9281 // calling the process in effect engine
9282 size_t numSamples = thread->frameCount();
9283 int32_t *buffer = new int32_t[numSamples];
9284 memset(buffer, 0, numSamples * sizeof(int32_t));
9285 effect->setInBuffer((int16_t *)buffer);
9286 // auxiliary effects output samples to chain input buffer for further processing
9287 // by insert effects
9288 effect->setOutBuffer(mInBuffer);
9289 } else {
9290 // Insert effects are inserted at the end of mEffects vector as they are processed
9291 // after track and auxiliary effects.
9292 // Insert effect order as a function of indicated preference:
9293 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9294 // another effect is present
9295 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9296 // last effect claiming first position
9297 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9298 // first effect claiming last position
9299 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9300 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9301 // already present
9302
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009303 size_t size = mEffects.size();
9304 size_t idx_insert = size;
9305 ssize_t idx_insert_first = -1;
9306 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009307
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009308 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009309 effect_descriptor_t d = mEffects[i]->desc();
9310 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9311 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9312 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9313 // check invalid effect chaining combinations
9314 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9315 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009316 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009317 return INVALID_OPERATION;
9318 }
9319 // remember position of first insert effect and by default
9320 // select this as insert position for new effect
9321 if (idx_insert == size) {
9322 idx_insert = i;
9323 }
9324 // remember position of last insert effect claiming
9325 // first position
9326 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9327 idx_insert_first = i;
9328 }
9329 // remember position of first insert effect claiming
9330 // last position
9331 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9332 idx_insert_last == -1) {
9333 idx_insert_last = i;
9334 }
9335 }
9336 }
9337
9338 // modify idx_insert from first position if needed
9339 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9340 if (idx_insert_last != -1) {
9341 idx_insert = idx_insert_last;
9342 } else {
9343 idx_insert = size;
9344 }
9345 } else {
9346 if (idx_insert_first != -1) {
9347 idx_insert = idx_insert_first + 1;
9348 }
9349 }
9350
9351 // always read samples from chain input buffer
9352 effect->setInBuffer(mInBuffer);
9353
9354 // if last effect in the chain, output samples to chain
9355 // output buffer, otherwise to chain input buffer
9356 if (idx_insert == size) {
9357 if (idx_insert != 0) {
9358 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9359 mEffects[idx_insert-1]->configure();
9360 }
9361 effect->setOutBuffer(mOutBuffer);
9362 } else {
9363 effect->setOutBuffer(mInBuffer);
9364 }
9365 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009366
Steve Block3856b092011-10-20 11:56:00 +01009367 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009368 }
9369 effect->configure();
9370 return NO_ERROR;
9371}
9372
Eric Laurentcab11242010-07-15 12:50:15 -07009373// removeEffect_l() must be called with PlaybackThread::mLock held
9374size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009375{
9376 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009377 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009378 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9379
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009380 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009381 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009382 // calling stop here will remove pre-processing effect from the audio HAL.
9383 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9384 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009385 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9386 mEffects[i]->state() == EffectModule::STOPPING) {
9387 mEffects[i]->stop();
9388 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009389 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9390 delete[] effect->inBuffer();
9391 } else {
9392 if (i == size - 1 && i != 0) {
9393 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9394 mEffects[i - 1]->configure();
9395 }
9396 }
9397 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009398 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009399 break;
9400 }
9401 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009402
9403 return mEffects.size();
9404}
9405
Eric Laurentcab11242010-07-15 12:50:15 -07009406// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009407void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009408{
9409 size_t size = mEffects.size();
9410 for (size_t i = 0; i < size; i++) {
9411 mEffects[i]->setDevice(device);
9412 }
9413}
9414
Eric Laurentcab11242010-07-15 12:50:15 -07009415// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009416void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009417{
9418 size_t size = mEffects.size();
9419 for (size_t i = 0; i < size; i++) {
9420 mEffects[i]->setMode(mode);
9421 }
9422}
9423
Eric Laurent57b2dd12012-08-31 17:44:06 -07009424// setAudioSource_l() must be called with PlaybackThread::mLock held
9425void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
9426{
9427 size_t size = mEffects.size();
9428 for (size_t i = 0; i < size; i++) {
9429 mEffects[i]->setAudioSource(source);
9430 }
9431}
9432
Eric Laurentcab11242010-07-15 12:50:15 -07009433// setVolume_l() must be called with PlaybackThread::mLock held
9434bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009435{
9436 uint32_t newLeft = *left;
9437 uint32_t newRight = *right;
9438 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009439 int ctrlIdx = -1;
9440 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009441
Eric Laurentcab11242010-07-15 12:50:15 -07009442 // first update volume controller
9443 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009444 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009445 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9446 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009447 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009448 break;
9449 }
9450 }
9451
9452 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009453 if (hasControl) {
9454 *left = mNewLeftVolume;
9455 *right = mNewRightVolume;
9456 }
9457 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009458 }
9459
9460 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009461 mLeftVolume = newLeft;
9462 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009463
9464 // second get volume update from volume controller
9465 if (ctrlIdx >= 0) {
9466 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009467 mNewLeftVolume = newLeft;
9468 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009469 }
9470 // then indicate volume to all other effects in chain.
9471 // Pass altered volume to effects before volume controller
9472 // and requested volume to effects after controller
9473 uint32_t lVol = newLeft;
9474 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009475
Mathias Agopian65ab4712010-07-14 17:59:35 -07009476 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009477 if ((int)i == ctrlIdx) continue;
9478 // this also works for ctrlIdx == -1 when there is no volume controller
9479 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009480 lVol = *left;
9481 rVol = *right;
9482 }
9483 mEffects[i]->setVolume(&lVol, &rVol, false);
9484 }
9485 *left = newLeft;
9486 *right = newRight;
9487
9488 return hasControl;
9489}
9490
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009491void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009492{
9493 const size_t SIZE = 256;
9494 char buffer[SIZE];
9495 String8 result;
9496
9497 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9498 result.append(buffer);
9499
9500 bool locked = tryLock(mLock);
9501 // failed to lock - AudioFlinger is probably deadlocked
9502 if (!locked) {
9503 result.append("\tCould not lock mutex:\n");
9504 }
9505
Eric Laurentcab11242010-07-15 12:50:15 -07009506 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9507 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009508 mEffects.size(),
9509 (uint32_t)mInBuffer,
9510 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009511 mActiveTrackCnt);
9512 result.append(buffer);
9513 write(fd, result.string(), result.size());
9514
9515 for (size_t i = 0; i < mEffects.size(); ++i) {
9516 sp<EffectModule> effect = mEffects[i];
9517 if (effect != 0) {
9518 effect->dump(fd, args);
9519 }
9520 }
9521
9522 if (locked) {
9523 mLock.unlock();
9524 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009525}
9526
Eric Laurent59255e42011-07-27 19:49:51 -07009527// must be called with ThreadBase::mLock held
9528void AudioFlinger::EffectChain::setEffectSuspended_l(
9529 const effect_uuid_t *type, bool suspend)
9530{
9531 sp<SuspendedEffectDesc> desc;
9532 // use effect type UUID timelow as key as there is no real risk of identical
9533 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009534 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009535 if (suspend) {
9536 if (index >= 0) {
9537 desc = mSuspendedEffects.valueAt(index);
9538 } else {
9539 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -08009540 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07009541 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009542 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009543 }
9544 if (desc->mRefCount++ == 0) {
9545 sp<EffectModule> effect = getEffectIfEnabled(type);
9546 if (effect != 0) {
9547 desc->mEffect = effect;
9548 effect->setSuspended(true);
9549 effect->setEnabled(false);
9550 }
9551 }
9552 } else {
9553 if (index < 0) {
9554 return;
9555 }
9556 desc = mSuspendedEffects.valueAt(index);
9557 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009558 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009559 desc->mRefCount = 1;
9560 }
9561 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009562 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009563 if (desc->mEffect != 0) {
9564 sp<EffectModule> effect = desc->mEffect.promote();
9565 if (effect != 0) {
9566 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009567 effect->lock();
9568 EffectHandle *handle = effect->controlHandle_l();
9569 if (handle != NULL && !handle->destroyed_l()) {
9570 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009571 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009572 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009573 }
9574 desc->mEffect.clear();
9575 }
9576 mSuspendedEffects.removeItemsAt(index);
9577 }
9578 }
9579}
9580
9581// must be called with ThreadBase::mLock held
9582void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9583{
9584 sp<SuspendedEffectDesc> desc;
9585
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009586 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009587 if (suspend) {
9588 if (index >= 0) {
9589 desc = mSuspendedEffects.valueAt(index);
9590 } else {
9591 desc = new SuspendedEffectDesc();
9592 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009593 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009594 }
9595 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009596 Vector< sp<EffectModule> > effects;
9597 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009598 for (size_t i = 0; i < effects.size(); i++) {
9599 setEffectSuspended_l(&effects[i]->desc().type, true);
9600 }
9601 }
9602 } else {
9603 if (index < 0) {
9604 return;
9605 }
9606 desc = mSuspendedEffects.valueAt(index);
9607 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009608 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009609 desc->mRefCount = 1;
9610 }
9611 if (--desc->mRefCount == 0) {
9612 Vector<const effect_uuid_t *> types;
9613 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9614 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9615 continue;
9616 }
9617 types.add(&mSuspendedEffects.valueAt(i)->mType);
9618 }
9619 for (size_t i = 0; i < types.size(); i++) {
9620 setEffectSuspended_l(types[i], false);
9621 }
Steve Block3856b092011-10-20 11:56:00 +01009622 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009623 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9624 }
9625 }
9626}
9627
Eric Laurent6bffdb82011-09-23 08:40:41 -07009628
9629// The volume effect is used for automated tests only
9630#ifndef OPENSL_ES_H_
9631static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9632 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9633const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9634#endif //OPENSL_ES_H_
9635
Eric Laurentdb7c0792011-08-10 10:37:50 -07009636bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9637{
9638 // auxiliary effects and visualizer are never suspended on output mix
9639 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9640 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009641 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9642 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009643 return false;
9644 }
9645 return true;
9646}
9647
Glenn Kastend0539712012-01-30 12:56:03 -08009648void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009649{
Glenn Kastend0539712012-01-30 12:56:03 -08009650 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009651 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009652 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9653 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009654 }
Eric Laurent59255e42011-07-27 19:49:51 -07009655 }
Eric Laurent59255e42011-07-27 19:49:51 -07009656}
9657
9658sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9659 const effect_uuid_t *type)
9660{
Glenn Kasten090f0192012-01-30 13:00:02 -08009661 sp<EffectModule> effect = getEffectFromType_l(type);
9662 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009663}
9664
9665void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9666 bool enabled)
9667{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009668 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009669 if (enabled) {
9670 if (index < 0) {
9671 // if the effect is not suspend check if all effects are suspended
9672 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9673 if (index < 0) {
9674 return;
9675 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009676 if (!isEffectEligibleForSuspend(effect->desc())) {
9677 return;
9678 }
Eric Laurent59255e42011-07-27 19:49:51 -07009679 setEffectSuspended_l(&effect->desc().type, enabled);
9680 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009681 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009682 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009683 return;
9684 }
Eric Laurent59255e42011-07-27 19:49:51 -07009685 }
Steve Block3856b092011-10-20 11:56:00 +01009686 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009687 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009688 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9689 // if effect is requested to suspended but was not yet enabled, supend it now.
9690 if (desc->mEffect == 0) {
9691 desc->mEffect = effect;
9692 effect->setEnabled(false);
9693 effect->setSuspended(true);
9694 }
9695 } else {
9696 if (index < 0) {
9697 return;
9698 }
Steve Block3856b092011-10-20 11:56:00 +01009699 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009700 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009701 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9702 desc->mEffect.clear();
9703 effect->setSuspended(false);
9704 }
9705}
9706
Mathias Agopian65ab4712010-07-14 17:59:35 -07009707#undef LOG_TAG
9708#define LOG_TAG "AudioFlinger"
9709
9710// ----------------------------------------------------------------------------
9711
9712status_t AudioFlinger::onTransact(
9713 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9714{
9715 return BnAudioFlinger::onTransact(code, data, reply, flags);
9716}
9717
Mathias Agopian65ab4712010-07-14 17:59:35 -07009718}; // namespace android