blob: 9bdab2fee5a2130f1b6022cb6eec4125fbf28018 [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 Kastenfc7992b2012-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 Kasten2662ac92012-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 Kasten2662ac92012-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 Kasten2662ac92012-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 Laurent88959252012-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 }
Glenn Kasten8c327342012-09-30 12:29:28 -0700420
421 // dump the serially shared record tee sink
422 if (mRecordTeeSource != 0) {
423 dumpTee(fd, mRecordTeeSource);
424 }
425
Mathias Agopian65ab4712010-07-14 17:59:35 -0700426 if (locked) mLock.unlock();
427 }
428 return NO_ERROR;
429}
430
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800431sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
432{
433 // If pid is already in the mClients wp<> map, then use that entry
434 // (for which promote() is always != 0), otherwise create a new entry and Client.
435 sp<Client> client = mClients.valueFor(pid).promote();
436 if (client == 0) {
437 client = new Client(this, pid);
438 mClients.add(pid, client);
439 }
440
441 return client;
442}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700443
444// IAudioFlinger interface
445
446
447sp<IAudioTrack> AudioFlinger::createTrack(
448 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800449 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700450 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800451 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700452 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700453 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800454 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700455 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800456 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800457 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700458 int *sessionId,
459 status_t *status)
460{
461 sp<PlaybackThread::Track> track;
462 sp<TrackHandle> trackHandle;
463 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700464 status_t lStatus;
465 int lSessionId;
466
Glenn Kasten263709e2012-01-06 08:40:01 -0800467 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
468 // but if someone uses binder directly they could bypass that and cause us to crash
469 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000470 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700471 lStatus = BAD_VALUE;
472 goto Exit;
473 }
474
475 {
476 Mutex::Autolock _l(mLock);
477 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700478 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700479 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000480 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700481 lStatus = BAD_VALUE;
482 goto Exit;
483 }
484
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800485 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700486
Steve Block3856b092011-10-20 11:56:00 +0100487 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700488 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700489 // check if an effect chain with the same session ID is present on another
490 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700491 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700492 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
493 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700494 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700495 if (sessions & PlaybackThread::EFFECT_SESSION) {
496 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700497 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700498 }
Eric Laurentde070132010-07-13 04:45:46 -0700499 }
500 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700501 lSessionId = *sessionId;
502 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700503 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700504 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700505 if (sessionId != NULL) {
506 *sessionId = lSessionId;
507 }
508 }
Steve Block3856b092011-10-20 11:56:00 +0100509 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700510
511 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800512 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700513
514 // move effect chain to this output thread if an effect on same session was waiting
515 // for a track to be created
516 if (lStatus == NO_ERROR && effectThread != NULL) {
517 Mutex::Autolock _dl(thread->mLock);
518 Mutex::Autolock _sl(effectThread->mLock);
519 moveEffectChain_l(lSessionId, effectThread, thread, true);
520 }
Eric Laurenta011e352012-03-29 15:51:43 -0700521
522 // Look for sync events awaiting for a session to be used.
523 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
524 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
525 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700526 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700527 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700528 } else {
529 mPendingSyncEvents[i]->cancel();
530 }
Eric Laurenta011e352012-03-29 15:51:43 -0700531 mPendingSyncEvents.removeAt(i);
532 i--;
533 }
534 }
535 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700536 }
537 if (lStatus == NO_ERROR) {
538 trackHandle = new TrackHandle(track);
539 } else {
540 // remove local strong reference to Client before deleting the Track so that the Client
541 // destructor is called by the TrackBase destructor with mLock held
542 client.clear();
543 track.clear();
544 }
545
546Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700547 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700548 *status = lStatus;
549 }
550 return trackHandle;
551}
552
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800553uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700554{
555 Mutex::Autolock _l(mLock);
556 PlaybackThread *thread = checkPlaybackThread_l(output);
557 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000558 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700559 return 0;
560 }
561 return thread->sampleRate();
562}
563
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800564int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700565{
566 Mutex::Autolock _l(mLock);
567 PlaybackThread *thread = checkPlaybackThread_l(output);
568 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000569 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700570 return 0;
571 }
572 return thread->channelCount();
573}
574
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800575audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700576{
577 Mutex::Autolock _l(mLock);
578 PlaybackThread *thread = checkPlaybackThread_l(output);
579 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000580 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800581 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700582 }
583 return thread->format();
584}
585
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800586size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700587{
588 Mutex::Autolock _l(mLock);
589 PlaybackThread *thread = checkPlaybackThread_l(output);
590 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000591 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700592 return 0;
593 }
Glenn Kasten58912562012-04-03 10:45:00 -0700594 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
595 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700596 return thread->frameCount();
597}
598
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800599uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700600{
601 Mutex::Autolock _l(mLock);
602 PlaybackThread *thread = checkPlaybackThread_l(output);
603 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000604 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700605 return 0;
606 }
607 return thread->latency();
608}
609
610status_t AudioFlinger::setMasterVolume(float value)
611{
Eric Laurenta1884f92011-08-23 08:25:03 -0700612 status_t ret = initCheck();
613 if (ret != NO_ERROR) {
614 return ret;
615 }
616
Mathias Agopian65ab4712010-07-14 17:59:35 -0700617 // check calling permissions
618 if (!settingsAllowed()) {
619 return PERMISSION_DENIED;
620 }
621
Eric Laurenta4c5a552012-03-29 10:12:40 -0700622 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700623 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700624
John Grossmanee578c02012-07-23 17:05:46 -0700625 // Set master volume in the HALs which support it.
626 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
627 AutoMutex lock(mHardwareLock);
628 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800629
John Grossmanee578c02012-07-23 17:05:46 -0700630 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
631 if (dev->canSetMasterVolume()) {
632 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800633 }
John Grossmanee578c02012-07-23 17:05:46 -0700634 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700635 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700636
John Grossmanee578c02012-07-23 17:05:46 -0700637 // Now set the master volume in each playback thread. Playback threads
638 // assigned to HALs which do not have master volume support will apply
639 // master volume during the mix operation. Threads with HALs which do
640 // support master volume will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800641 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700642 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700643
644 return NO_ERROR;
645}
646
Glenn Kastenf78aee72012-01-04 11:00:47 -0800647status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700648{
Eric Laurenta1884f92011-08-23 08:25:03 -0700649 status_t ret = initCheck();
650 if (ret != NO_ERROR) {
651 return ret;
652 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700653
654 // check calling permissions
655 if (!settingsAllowed()) {
656 return PERMISSION_DENIED;
657 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800658 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000659 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700660 return BAD_VALUE;
661 }
662
663 { // scope for the lock
664 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700665 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700666 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700667 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700668 mHardwareStatus = AUDIO_HW_IDLE;
669 }
670
671 if (NO_ERROR == ret) {
672 Mutex::Autolock _l(mLock);
673 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800674 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700675 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700676 }
677
678 return ret;
679}
680
681status_t AudioFlinger::setMicMute(bool state)
682{
Eric Laurenta1884f92011-08-23 08:25:03 -0700683 status_t ret = initCheck();
684 if (ret != NO_ERROR) {
685 return ret;
686 }
687
Mathias Agopian65ab4712010-07-14 17:59:35 -0700688 // check calling permissions
689 if (!settingsAllowed()) {
690 return PERMISSION_DENIED;
691 }
692
693 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700694 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700695 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700696 ret = dev->set_mic_mute(dev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700697 mHardwareStatus = AUDIO_HW_IDLE;
698 return ret;
699}
700
701bool AudioFlinger::getMicMute() const
702{
Eric Laurenta1884f92011-08-23 08:25:03 -0700703 status_t ret = initCheck();
704 if (ret != NO_ERROR) {
705 return false;
706 }
707
Dima Zavinfce7a472011-04-19 22:30:36 -0700708 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800709 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700710 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700711 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700712 dev->get_mic_mute(dev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700713 mHardwareStatus = AUDIO_HW_IDLE;
714 return state;
715}
716
717status_t AudioFlinger::setMasterMute(bool muted)
718{
John Grossmand8f178d2012-07-20 14:51:35 -0700719 status_t ret = initCheck();
720 if (ret != NO_ERROR) {
721 return ret;
722 }
723
Mathias Agopian65ab4712010-07-14 17:59:35 -0700724 // check calling permissions
725 if (!settingsAllowed()) {
726 return PERMISSION_DENIED;
727 }
728
John Grossmanee578c02012-07-23 17:05:46 -0700729 Mutex::Autolock _l(mLock);
730 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700731
John Grossmanee578c02012-07-23 17:05:46 -0700732 // Set master mute in the HALs which support it.
733 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
734 AutoMutex lock(mHardwareLock);
735 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700736
John Grossmanee578c02012-07-23 17:05:46 -0700737 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
738 if (dev->canSetMasterMute()) {
739 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700740 }
John Grossmanee578c02012-07-23 17:05:46 -0700741 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700742 }
743
John Grossmanee578c02012-07-23 17:05:46 -0700744 // Now set the master mute in each playback thread. Playback threads
745 // assigned to HALs which do not have master mute support will apply master
746 // mute during the mix operation. Threads with HALs which do support master
747 // mute will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800748 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700749 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700750
751 return NO_ERROR;
752}
753
754float AudioFlinger::masterVolume() const
755{
Glenn Kasten98067102011-12-13 11:47:54 -0800756 Mutex::Autolock _l(mLock);
757 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700758}
759
760bool AudioFlinger::masterMute() const
761{
Glenn Kasten98067102011-12-13 11:47:54 -0800762 Mutex::Autolock _l(mLock);
763 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700764}
765
John Grossman4ff14ba2012-02-08 16:37:41 -0800766float AudioFlinger::masterVolume_l() const
767{
John Grossman4ff14ba2012-02-08 16:37:41 -0800768 return mMasterVolume;
769}
770
John Grossmand8f178d2012-07-20 14:51:35 -0700771bool AudioFlinger::masterMute_l() const
772{
John Grossmanee578c02012-07-23 17:05:46 -0700773 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700774}
775
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800776status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
777 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700778{
779 // check calling permissions
780 if (!settingsAllowed()) {
781 return PERMISSION_DENIED;
782 }
783
Glenn Kasten263709e2012-01-06 08:40:01 -0800784 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000785 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700786 return BAD_VALUE;
787 }
788
789 AutoMutex lock(mLock);
790 PlaybackThread *thread = NULL;
791 if (output) {
792 thread = checkPlaybackThread_l(output);
793 if (thread == NULL) {
794 return BAD_VALUE;
795 }
796 }
797
798 mStreamTypes[stream].volume = value;
799
800 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800801 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700802 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700803 }
804 } else {
805 thread->setStreamVolume(stream, value);
806 }
807
808 return NO_ERROR;
809}
810
Glenn Kastenfff6d712012-01-12 16:38:12 -0800811status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700812{
813 // check calling permissions
814 if (!settingsAllowed()) {
815 return PERMISSION_DENIED;
816 }
817
Glenn Kasten263709e2012-01-06 08:40:01 -0800818 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700819 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000820 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821 return BAD_VALUE;
822 }
823
Eric Laurent93575202011-01-18 18:39:02 -0800824 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825 mStreamTypes[stream].mute = muted;
826 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700827 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828
829 return NO_ERROR;
830}
831
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800832float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833{
Glenn Kasten263709e2012-01-06 08:40:01 -0800834 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835 return 0.0f;
836 }
837
838 AutoMutex lock(mLock);
839 float volume;
840 if (output) {
841 PlaybackThread *thread = checkPlaybackThread_l(output);
842 if (thread == NULL) {
843 return 0.0f;
844 }
845 volume = thread->streamVolume(stream);
846 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800847 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700848 }
849
850 return volume;
851}
852
Glenn Kastenfff6d712012-01-12 16:38:12 -0800853bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700854{
Glenn Kasten263709e2012-01-06 08:40:01 -0800855 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700856 return true;
857 }
858
Glenn Kasten6637baa2012-01-09 09:40:36 -0800859 AutoMutex lock(mLock);
860 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700861}
862
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800863status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700864{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800865 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700866 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
867 // check calling permissions
868 if (!settingsAllowed()) {
869 return PERMISSION_DENIED;
870 }
871
Mathias Agopian65ab4712010-07-14 17:59:35 -0700872 // ioHandle == 0 means the parameters are global to the audio hardware interface
873 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700874 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700875 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800876 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700877 AutoMutex lock(mHardwareLock);
878 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
879 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
880 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
881 status_t result = dev->set_parameters(dev, keyValuePairs.string());
882 final_result = result ?: final_result;
883 }
884 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800885 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700886 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
887 AudioParameter param = AudioParameter(keyValuePairs);
888 String8 value;
889 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700890 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
891 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700892 for (size_t i = 0; i < mRecordThreads.size(); i++) {
893 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurent88959252012-08-28 14:26:53 -0700894 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -0700895 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
896 // collect all of the thread's session IDs
897 KeyedVector<int, bool> ids = thread->sessionIds();
898 // suspend effects associated with those session IDs
899 for (size_t j = 0; j < ids.size(); ++j) {
900 int sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700901 thread->setEffectSuspended(FX_IID_AEC,
902 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700903 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700904 thread->setEffectSuspended(FX_IID_NS,
905 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700906 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700907 }
908 }
Eric Laurentbee53372011-08-29 12:42:48 -0700909 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700910 }
911 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700912 String8 screenState;
913 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
914 bool isOff = screenState == "off";
915 if (isOff != (gScreenState & 1)) {
916 gScreenState = ((gScreenState & ~1) + 2) | isOff;
917 }
918 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700919 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700920 }
921
922 // hold a strong ref on thread in case closeOutput() or closeInput() is called
923 // and the thread is exited once the lock is released
924 sp<ThreadBase> thread;
925 {
926 Mutex::Autolock _l(mLock);
927 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -0700928 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700929 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800930 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700931 // indicate output device change to all input threads for pre processing
932 AudioParameter param = AudioParameter(keyValuePairs);
933 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700934 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
935 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700936 for (size_t i = 0; i < mRecordThreads.size(); i++) {
937 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
938 }
939 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700940 }
941 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800942 if (thread != 0) {
943 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700944 }
945 return BAD_VALUE;
946}
947
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800948String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700949{
Glenn Kastencbe4b362012-10-18 15:51:03 -0700950 ALOGVV("getParameters() io %d, keys %s, tid %d, calling pid %d",
951 ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700952
Eric Laurenta4c5a552012-03-29 10:12:40 -0700953 Mutex::Autolock _l(mLock);
954
Mathias Agopian65ab4712010-07-14 17:59:35 -0700955 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700956 String8 out_s8;
957
Dima Zavin799a70e2011-04-18 16:57:27 -0700958 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800959 char *s;
960 {
961 AutoMutex lock(mHardwareLock);
962 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700963 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800964 s = dev->get_parameters(dev, keys.string());
965 mHardwareStatus = AUDIO_HW_IDLE;
966 }
John Grossmanef7740b2012-02-09 11:28:36 -0800967 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700968 free(s);
969 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700970 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700971 }
972
Mathias Agopian65ab4712010-07-14 17:59:35 -0700973 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
974 if (playbackThread != NULL) {
975 return playbackThread->getParameters(keys);
976 }
977 RecordThread *recordThread = checkRecordThread_l(ioHandle);
978 if (recordThread != NULL) {
979 return recordThread->getParameters(keys);
980 }
981 return String8("");
982}
983
Glenn Kastendd8104c2012-07-02 12:42:44 -0700984size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
985 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700986{
Eric Laurenta1884f92011-08-23 08:25:03 -0700987 status_t ret = initCheck();
988 if (ret != NO_ERROR) {
989 return 0;
990 }
991
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800992 AutoMutex lock(mHardwareLock);
993 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700994 struct audio_config config = {
995 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -0700996 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700997 format: format,
998 };
John Grossmanee578c02012-07-23 17:05:46 -0700999 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1000 size_t size = dev->get_input_buffer_size(dev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001001 mHardwareStatus = AUDIO_HW_IDLE;
1002 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001003}
1004
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001005unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001006{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001007 Mutex::Autolock _l(mLock);
1008
1009 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1010 if (recordThread != NULL) {
1011 return recordThread->getInputFramesLost();
1012 }
1013 return 0;
1014}
1015
1016status_t AudioFlinger::setVoiceVolume(float value)
1017{
Eric Laurenta1884f92011-08-23 08:25:03 -07001018 status_t ret = initCheck();
1019 if (ret != NO_ERROR) {
1020 return ret;
1021 }
1022
Mathias Agopian65ab4712010-07-14 17:59:35 -07001023 // check calling permissions
1024 if (!settingsAllowed()) {
1025 return PERMISSION_DENIED;
1026 }
1027
1028 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001029 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001030 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001031 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001032 mHardwareStatus = AUDIO_HW_IDLE;
1033
1034 return ret;
1035}
1036
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001037status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1038 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001039{
1040 status_t status;
1041
1042 Mutex::Autolock _l(mLock);
1043
1044 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1045 if (playbackThread != NULL) {
1046 return playbackThread->getRenderPosition(halFrames, dspFrames);
1047 }
1048
1049 return BAD_VALUE;
1050}
1051
1052void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1053{
1054
1055 Mutex::Autolock _l(mLock);
1056
Glenn Kastenbb001922012-02-03 11:10:26 -08001057 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058 if (mNotificationClients.indexOfKey(pid) < 0) {
1059 sp<NotificationClient> notificationClient = new NotificationClient(this,
1060 client,
1061 pid);
Steve Block3856b092011-10-20 11:56:00 +01001062 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001063
1064 mNotificationClients.add(pid, notificationClient);
1065
1066 sp<IBinder> binder = client->asBinder();
1067 binder->linkToDeath(notificationClient);
1068
1069 // the config change is always sent from playback or record threads to avoid deadlock
1070 // with AudioSystem::gLock
1071 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentef6be0b2012-09-13 11:18:23 -07001072 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001073 }
1074
1075 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentef6be0b2012-09-13 11:18:23 -07001076 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001077 }
1078 }
1079}
1080
1081void AudioFlinger::removeNotificationClient(pid_t pid)
1082{
1083 Mutex::Autolock _l(mLock);
1084
Glenn Kastena3b09252012-01-20 09:19:01 -08001085 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001086
Steve Block3856b092011-10-20 11:56:00 +01001087 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001088 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001089 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001090 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001091 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001092 ALOGV(" pid %d @ %d", ref->mPid, i);
1093 if (ref->mPid == pid) {
1094 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001095 mAudioSessionRefs.removeAt(i);
1096 delete ref;
1097 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001098 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001099 } else {
1100 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001101 }
1102 }
1103 if (removed) {
1104 purgeStaleEffects_l();
1105 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001106}
1107
1108// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001109void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001110{
1111 size_t size = mNotificationClients.size();
1112 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001113 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1114 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001115 }
1116}
1117
1118// removeClient_l() must be called with AudioFlinger::mLock held
1119void AudioFlinger::removeClient_l(pid_t pid)
1120{
Steve Block3856b092011-10-20 11:56:00 +01001121 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001122 mClients.removeItem(pid);
1123}
1124
Eric Laurent717e1282012-06-29 16:36:52 -07001125// getEffectThread_l() must be called with AudioFlinger::mLock held
1126sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1127{
1128 sp<PlaybackThread> thread;
1129
1130 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1131 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1132 ALOG_ASSERT(thread == 0);
1133 thread = mPlaybackThreads.valueAt(i);
1134 }
1135 }
1136
1137 return thread;
1138}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001139
1140// ----------------------------------------------------------------------------
1141
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001142AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent88959252012-08-28 14:26:53 -07001143 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
Glenn Kasten2662ac92012-07-30 10:59:30 -07001144 : Thread(false /*canCallJava*/),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001145 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001146 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001147 // mChannelMask
1148 mChannelCount(0),
1149 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1150 mParamStatus(NO_ERROR),
Eric Laurent88959252012-08-28 14:26:53 -07001151 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
1152 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Glenn Kasten2662ac92012-07-30 10:59:30 -07001153 // mName will be set by concrete (non-virtual) subclass
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001154 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001155{
1156}
1157
1158AudioFlinger::ThreadBase::~ThreadBase()
1159{
1160 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001161 // do not lock the mutex in destructor
1162 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001163 if (mPowerManager != 0) {
1164 sp<IBinder> binder = mPowerManager->asBinder();
1165 binder->unlinkToDeath(mDeathRecipient);
1166 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001167}
1168
1169void AudioFlinger::ThreadBase::exit()
1170{
Steve Block3856b092011-10-20 11:56:00 +01001171 ALOGV("ThreadBase::exit");
Jean-Michel Trivi2fa114d2012-09-28 14:49:39 -07001172 // do any cleanup required for exit to succeed
1173 preExit();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001174 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001175 // This lock prevents the following race in thread (uniprocessor for illustration):
1176 // if (!exitPending()) {
1177 // // context switch from here to exit()
1178 // // exit() calls requestExit(), what exitPending() observes
1179 // // exit() calls signal(), which is dropped since no waiters
1180 // // context switch back from exit() to here
1181 // mWaitWorkCV.wait(...);
1182 // // now thread is hung
1183 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001184 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001185 requestExit();
Eric Laurent67d8ac32012-09-24 15:02:17 -07001186 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001187 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001188 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1189 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001190 requestExitAndWait();
1191}
1192
Mathias Agopian65ab4712010-07-14 17:59:35 -07001193status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1194{
1195 status_t status;
1196
Steve Block3856b092011-10-20 11:56:00 +01001197 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001198 Mutex::Autolock _l(mLock);
1199
1200 mNewParameters.add(keyValuePairs);
1201 mWaitWorkCV.signal();
1202 // wait condition with timeout in case the thread loop has exited
1203 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001204 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001205 status = mParamStatus;
1206 mWaitWorkCV.signal();
1207 } else {
1208 status = TIMED_OUT;
1209 }
1210 return status;
1211}
1212
Eric Laurentef6be0b2012-09-13 11:18:23 -07001213void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001214{
1215 Mutex::Autolock _l(mLock);
Eric Laurentef6be0b2012-09-13 11:18:23 -07001216 sendIoConfigEvent_l(event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001217}
1218
Eric Laurentef6be0b2012-09-13 11:18:23 -07001219// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
1220void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001221{
Eric Laurentef6be0b2012-09-13 11:18:23 -07001222 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
1223 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
1224 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1225 mWaitWorkCV.signal();
1226}
1227
1228// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
1229void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
1230{
1231 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
1232 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
1233 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
1234 mConfigEvents.size(), pid, tid, prio);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001235 mWaitWorkCV.signal();
1236}
1237
1238void AudioFlinger::ThreadBase::processConfigEvents()
1239{
1240 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001241 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001242 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Eric Laurentef6be0b2012-09-13 11:18:23 -07001243 ConfigEvent *event = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001244 mConfigEvents.removeAt(0);
1245 // release mLock before locking AudioFlinger mLock: lock order is always
1246 // AudioFlinger then ThreadBase to avoid cross deadlock
1247 mLock.unlock();
Eric Laurentef6be0b2012-09-13 11:18:23 -07001248 switch(event->type()) {
1249 case CFG_EVENT_PRIO: {
1250 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
1251 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio());
1252 if (err != 0) {
1253 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1254 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
1255 }
1256 } break;
1257 case CFG_EVENT_IO: {
1258 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
1259 mAudioFlinger->mLock.lock();
1260 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
1261 mAudioFlinger->mLock.unlock();
1262 } break;
1263 default:
1264 ALOGE("processConfigEvents() unknown event type %d", event->type());
1265 break;
1266 }
1267 delete event;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001268 mLock.lock();
1269 }
1270 mLock.unlock();
1271}
1272
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001273void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001274{
1275 const size_t SIZE = 256;
1276 char buffer[SIZE];
1277 String8 result;
1278
1279 bool locked = tryLock(mLock);
1280 if (!locked) {
1281 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1282 write(fd, buffer, strlen(buffer));
1283 }
1284
Eric Laurent612bbb52012-03-14 15:03:26 -07001285 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1286 result.append(buffer);
1287 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1288 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001289 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1290 result.append(buffer);
1291 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1292 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001293 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1294 result.append(buffer);
1295 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001296 result.append(buffer);
1297 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1298 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001299 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1300 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001301 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1302 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001303 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001304 result.append(buffer);
1305
1306 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1307 result.append(buffer);
1308 result.append(" Index Command");
1309 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1310 snprintf(buffer, SIZE, "\n %02d ", i);
1311 result.append(buffer);
1312 result.append(mNewParameters[i]);
1313 }
1314
1315 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1316 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001317 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Eric Laurentef6be0b2012-09-13 11:18:23 -07001318 mConfigEvents[i]->dump(buffer, SIZE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001319 result.append(buffer);
1320 }
1321 result.append("\n");
1322
1323 write(fd, result.string(), result.size());
1324
1325 if (locked) {
1326 mLock.unlock();
1327 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001328}
1329
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001330void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001331{
1332 const size_t SIZE = 256;
1333 char buffer[SIZE];
1334 String8 result;
1335
1336 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1337 write(fd, buffer, strlen(buffer));
1338
1339 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1340 sp<EffectChain> chain = mEffectChains[i];
1341 if (chain != 0) {
1342 chain->dump(fd, args);
1343 }
1344 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001345}
1346
Eric Laurentfeb0db62011-07-22 09:04:31 -07001347void AudioFlinger::ThreadBase::acquireWakeLock()
1348{
1349 Mutex::Autolock _l(mLock);
1350 acquireWakeLock_l();
1351}
1352
1353void AudioFlinger::ThreadBase::acquireWakeLock_l()
1354{
1355 if (mPowerManager == 0) {
1356 // use checkService() to avoid blocking if power service is not up yet
1357 sp<IBinder> binder =
1358 defaultServiceManager()->checkService(String16("power"));
1359 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001360 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001361 } else {
1362 mPowerManager = interface_cast<IPowerManager>(binder);
1363 binder->linkToDeath(mDeathRecipient);
1364 }
1365 }
1366 if (mPowerManager != 0) {
1367 sp<IBinder> binder = new BBinder();
1368 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1369 binder,
1370 String16(mName));
1371 if (status == NO_ERROR) {
1372 mWakeLockToken = binder;
1373 }
Steve Block3856b092011-10-20 11:56:00 +01001374 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001375 }
1376}
1377
1378void AudioFlinger::ThreadBase::releaseWakeLock()
1379{
1380 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001381 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001382}
1383
1384void AudioFlinger::ThreadBase::releaseWakeLock_l()
1385{
1386 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001387 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001388 if (mPowerManager != 0) {
1389 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1390 }
1391 mWakeLockToken.clear();
1392 }
1393}
1394
1395void AudioFlinger::ThreadBase::clearPowerManager()
1396{
1397 Mutex::Autolock _l(mLock);
1398 releaseWakeLock_l();
1399 mPowerManager.clear();
1400}
1401
1402void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1403{
1404 sp<ThreadBase> thread = mThread.promote();
1405 if (thread != 0) {
1406 thread->clearPowerManager();
1407 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001408 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001409}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001410
Eric Laurent59255e42011-07-27 19:49:51 -07001411void AudioFlinger::ThreadBase::setEffectSuspended(
1412 const effect_uuid_t *type, bool suspend, int sessionId)
1413{
1414 Mutex::Autolock _l(mLock);
1415 setEffectSuspended_l(type, suspend, sessionId);
1416}
1417
1418void AudioFlinger::ThreadBase::setEffectSuspended_l(
1419 const effect_uuid_t *type, bool suspend, int sessionId)
1420{
Glenn Kasten090f0192012-01-30 13:00:02 -08001421 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001422 if (chain != 0) {
1423 if (type != NULL) {
1424 chain->setEffectSuspended_l(type, suspend);
1425 } else {
1426 chain->setEffectSuspendedAll_l(suspend);
1427 }
1428 }
1429
1430 updateSuspendedSessions_l(type, suspend, sessionId);
1431}
1432
1433void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1434{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001435 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001436 if (index < 0) {
1437 return;
1438 }
1439
Glenn Kasten0a7af182012-07-09 16:09:19 -07001440 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1441 mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001442
1443 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001444 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001445 for (int j = 0; j < desc->mRefCount; j++) {
1446 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1447 chain->setEffectSuspendedAll_l(true);
1448 } else {
Steve Block3856b092011-10-20 11:56:00 +01001449 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001450 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001451 chain->setEffectSuspended_l(&desc->mType, true);
1452 }
1453 }
1454 }
1455}
1456
Eric Laurent59255e42011-07-27 19:49:51 -07001457void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1458 bool suspend,
1459 int sessionId)
1460{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001461 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001462
1463 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1464
1465 if (suspend) {
1466 if (index >= 0) {
Glenn Kasten0a7af182012-07-09 16:09:19 -07001467 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001468 } else {
1469 mSuspendedSessions.add(sessionId, sessionEffects);
1470 }
1471 } else {
1472 if (index < 0) {
1473 return;
1474 }
Glenn Kasten0a7af182012-07-09 16:09:19 -07001475 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001476 }
1477
1478
1479 int key = EffectChain::kKeyForSuspendAll;
1480 if (type != NULL) {
1481 key = type->timeLow;
1482 }
1483 index = sessionEffects.indexOfKey(key);
1484
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001485 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001486 if (suspend) {
1487 if (index >= 0) {
1488 desc = sessionEffects.valueAt(index);
1489 } else {
1490 desc = new SuspendedSessionDesc();
1491 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001492 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001493 }
1494 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001495 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001496 }
1497 desc->mRefCount++;
1498 } else {
1499 if (index < 0) {
1500 return;
1501 }
1502 desc = sessionEffects.valueAt(index);
1503 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001504 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001505 sessionEffects.removeItemsAt(index);
1506 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001507 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001508 sessionId);
1509 mSuspendedSessions.removeItem(sessionId);
1510 }
1511 }
1512 }
1513 if (!sessionEffects.isEmpty()) {
1514 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1515 }
1516}
1517
1518void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1519 bool enabled,
1520 int sessionId)
1521{
1522 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001523 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1524}
Eric Laurent59255e42011-07-27 19:49:51 -07001525
Eric Laurenta85a74a2011-10-19 11:44:54 -07001526void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1527 bool enabled,
1528 int sessionId)
1529{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001530 if (mType != RECORD) {
1531 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1532 // another session. This gives the priority to well behaved effect control panels
1533 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001534 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1535 // global effects
1536 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001537 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1538 }
1539 }
Eric Laurent59255e42011-07-27 19:49:51 -07001540
1541 sp<EffectChain> chain = getEffectChain_l(sessionId);
1542 if (chain != 0) {
1543 chain->checkSuspendOnEffectEnabled(effect, enabled);
1544 }
1545}
1546
Mathias Agopian65ab4712010-07-14 17:59:35 -07001547// ----------------------------------------------------------------------------
1548
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001549AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1550 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001551 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001552 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001553 type_t type)
Eric Laurent88959252012-08-28 14:26:53 -07001554 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001555 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001556 // mStreamTypes[] initialized in constructor body
1557 mOutput(output),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001558 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001559 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001560 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001561 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001562 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001563 // index 0 is reserved for normal mixer's submix
1564 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001565{
Glenn Kasten480b4682012-02-28 12:30:08 -08001566 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001567
John Grossmanee578c02012-07-23 17:05:46 -07001568 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1569 // it would be safer to explicitly pass initial masterVolume/masterMute as
1570 // parameter.
1571 //
1572 // If the HAL we are using has support for master volume or master mute,
1573 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1574 // and the mute set to false).
1575 mMasterVolume = audioFlinger->masterVolume_l();
1576 mMasterMute = audioFlinger->masterMute_l();
1577 if (mOutput && mOutput->audioHwDev) {
1578 if (mOutput->audioHwDev->canSetMasterVolume()) {
1579 mMasterVolume = 1.0;
1580 }
1581
1582 if (mOutput->audioHwDev->canSetMasterMute()) {
1583 mMasterMute = false;
1584 }
1585 }
1586
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587 readOutputParameters();
1588
Glenn Kasten263709e2012-01-06 08:40:01 -08001589 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001590 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1591 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1592 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001593 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1594 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001595 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001596 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1597 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598}
1599
1600AudioFlinger::PlaybackThread::~PlaybackThread()
1601{
1602 delete [] mMixBuffer;
1603}
1604
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001605void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001606{
1607 dumpInternals(fd, args);
1608 dumpTracks(fd, args);
1609 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610}
1611
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001612void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001613{
1614 const size_t SIZE = 256;
1615 char buffer[SIZE];
1616 String8 result;
1617
Glenn Kasten58912562012-04-03 10:45:00 -07001618 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1619 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1620 const stream_type_t *st = &mStreamTypes[i];
1621 if (i > 0) {
1622 result.appendFormat(", ");
1623 }
1624 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1625 if (st->mute) {
1626 result.append("M");
1627 }
1628 }
1629 result.append("\n");
1630 write(fd, result.string(), result.length());
1631 result.clear();
1632
Mathias Agopian65ab4712010-07-14 17:59:35 -07001633 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1634 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001635 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001636 for (size_t i = 0; i < mTracks.size(); ++i) {
1637 sp<Track> track = mTracks[i];
1638 if (track != 0) {
1639 track->dump(buffer, SIZE);
1640 result.append(buffer);
1641 }
1642 }
1643
1644 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1645 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001646 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001647 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001648 sp<Track> track = mActiveTracks[i].promote();
1649 if (track != 0) {
1650 track->dump(buffer, SIZE);
1651 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001652 }
1653 }
1654 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001655
1656 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1657 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1658 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1659 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001660}
1661
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001662void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001663{
1664 const size_t SIZE = 256;
1665 char buffer[SIZE];
1666 String8 result;
1667
1668 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1669 result.append(buffer);
1670 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1671 result.append(buffer);
1672 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1673 result.append(buffer);
1674 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1675 result.append(buffer);
1676 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1677 result.append(buffer);
1678 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1679 result.append(buffer);
1680 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1681 result.append(buffer);
1682 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001683 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001684
1685 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001686}
1687
1688// Thread virtuals
1689status_t AudioFlinger::PlaybackThread::readyToRun()
1690{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001691 status_t status = initCheck();
1692 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001693 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001694 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001695 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001696 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001697 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698}
1699
1700void AudioFlinger::PlaybackThread::onFirstRef()
1701{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001702 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001703}
1704
Jean-Michel Trivi2fa114d2012-09-28 14:49:39 -07001705// ThreadBase virtuals
1706void AudioFlinger::PlaybackThread::preExit()
1707{
1708 ALOGV(" preExit()");
1709 // FIXME this is using hard-coded strings but in the future, this functionality will be
1710 // converted to use audio HAL extensions required to support tunneling
1711 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1712}
1713
Mathias Agopian65ab4712010-07-14 17:59:35 -07001714// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001715sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001716 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001717 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001718 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001719 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001720 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001721 int frameCount,
1722 const sp<IMemory>& sharedBuffer,
1723 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001724 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001725 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001726 status_t *status)
1727{
1728 sp<Track> track;
1729 status_t lStatus;
1730
Glenn Kasten73d22752012-03-19 13:38:30 -07001731 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1732
1733 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001734 if (flags & IAudioFlinger::TRACK_FAST) {
1735 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001736 // not timed
1737 (!isTimed) &&
1738 // either of these use cases:
1739 (
1740 // use case 1: shared buffer with any frame count
1741 (
1742 (sharedBuffer != 0)
1743 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001744 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001745 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001746 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001747 ((frameCount == 0) ||
Glenn Kasten3ed29202012-08-07 15:24:44 -07001748 (frameCount >= (int) (mFrameCount * kFastTrackMultiplier)))
Glenn Kasten73d22752012-03-19 13:38:30 -07001749 )
1750 ) &&
1751 // PCM data
1752 audio_is_linear_pcm(format) &&
1753 // mono or stereo
1754 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1755 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001756#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001757 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001758 (sampleRate == mSampleRate) &&
1759#endif
1760 // normal mixer has an associated fast mixer
1761 hasFastMixer() &&
1762 // there are sufficient fast track slots available
1763 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001764 // FIXME test that MixerThread for this fast track has a capable output HAL
1765 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001766 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001767 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1768 if (frameCount == 0) {
Glenn Kasten3ed29202012-08-07 15:24:44 -07001769 frameCount = mFrameCount * kFastTrackMultiplier;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001770 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001771 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001772 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001773 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001774 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07001775 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001776 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1777 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1778 audio_is_linear_pcm(format),
1779 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001780 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001781 // For compatibility with AudioTrack calculation, buffer depth is forced
1782 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1783 // This is probably too conservative, but legacy application code may depend on it.
1784 // If you change this calculation, also review the start threshold which is related.
1785 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1786 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1787 if (minBufCount < 2) {
1788 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001789 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001790 int minFrameCount = mNormalFrameCount * minBufCount;
1791 if (frameCount < minFrameCount) {
1792 frameCount = minFrameCount;
1793 }
1794 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001795 }
1796
Mathias Agopian65ab4712010-07-14 17:59:35 -07001797 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001798 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1799 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001800 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001801 "for output %p with format %d",
1802 sampleRate, format, channelMask, mOutput, mFormat);
1803 lStatus = BAD_VALUE;
1804 goto Exit;
1805 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001806 }
1807 } else {
1808 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1809 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001810 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001811 lStatus = BAD_VALUE;
1812 goto Exit;
1813 }
1814 }
1815
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001816 lStatus = initCheck();
1817 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001818 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001819 goto Exit;
1820 }
1821
1822 { // scope for mLock
1823 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001824
1825 // all tracks in same audio session must share the same routing strategy otherwise
1826 // conflicts will happen when tracks are moved from one output to another by audio policy
1827 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001828 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001829 for (size_t i = 0; i < mTracks.size(); ++i) {
1830 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001831 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001832 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001833 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001834 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001835 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001836 lStatus = BAD_VALUE;
1837 goto Exit;
1838 }
1839 }
1840 }
1841
John Grossman4ff14ba2012-02-08 16:37:41 -08001842 if (!isTimed) {
1843 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001844 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001845 } else {
1846 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1847 channelMask, frameCount, sharedBuffer, sessionId);
1848 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001849 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850 lStatus = NO_MEMORY;
1851 goto Exit;
1852 }
1853 mTracks.add(track);
1854
1855 sp<EffectChain> chain = getEffectChain_l(sessionId);
1856 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001857 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001858 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001859 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001860 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001862
Eric Laurentef6be0b2012-09-13 11:18:23 -07001863 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1864 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1865 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1866 // so ask activity manager to do this on our behalf
1867 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001868 }
1869 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001870
Mathias Agopian65ab4712010-07-14 17:59:35 -07001871 lStatus = NO_ERROR;
1872
1873Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001874 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001875 *status = lStatus;
1876 }
1877 return track;
1878}
1879
Eric Laurente737cda2012-05-22 18:55:44 -07001880uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1881{
1882 if (mFastMixer != NULL) {
1883 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1884 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1885 }
1886 return latency;
1887}
1888
1889uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1890{
1891 return latency;
1892}
1893
Mathias Agopian65ab4712010-07-14 17:59:35 -07001894uint32_t AudioFlinger::PlaybackThread::latency() const
1895{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001896 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001897 return latency_l();
1898}
1899uint32_t AudioFlinger::PlaybackThread::latency_l() const
1900{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001901 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001902 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001903 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001904 return 0;
1905 }
1906}
1907
Glenn Kasten6637baa2012-01-09 09:40:36 -08001908void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001909{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001910 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001911 // Don't apply master volume in SW if our HAL can do it for us.
1912 if (mOutput && mOutput->audioHwDev &&
1913 mOutput->audioHwDev->canSetMasterVolume()) {
1914 mMasterVolume = 1.0;
1915 } else {
1916 mMasterVolume = value;
1917 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918}
1919
Glenn Kasten6637baa2012-01-09 09:40:36 -08001920void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001921{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001922 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001923 // Don't apply master mute in SW if our HAL can do it for us.
1924 if (mOutput && mOutput->audioHwDev &&
1925 mOutput->audioHwDev->canSetMasterMute()) {
1926 mMasterMute = false;
1927 } else {
1928 mMasterMute = muted;
1929 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001930}
1931
Glenn Kasten6637baa2012-01-09 09:40:36 -08001932void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001933{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001934 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001935 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001936}
1937
Glenn Kasten6637baa2012-01-09 09:40:36 -08001938void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001940 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001941 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001942}
1943
Glenn Kastenfff6d712012-01-12 16:38:12 -08001944float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001945{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001946 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001947 return mStreamTypes[stream].volume;
1948}
1949
Mathias Agopian65ab4712010-07-14 17:59:35 -07001950// addTrack_l() must be called with ThreadBase::mLock held
1951status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1952{
1953 status_t status = ALREADY_EXISTS;
1954
1955 // set retry count for buffer fill
1956 track->mRetryCount = kMaxTrackStartupRetries;
1957 if (mActiveTracks.indexOf(track) < 0) {
1958 // the track is newly added, make sure it fills up all its
1959 // buffers before playing. This is to ensure the client will
1960 // effectively get the latency it requested.
1961 track->mFillingUpStatus = Track::FS_FILLING;
1962 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001963 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001964 mActiveTracks.add(track);
1965 if (track->mainBuffer() != mMixBuffer) {
1966 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1967 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001968 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001969 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970 }
1971 }
1972
1973 status = NO_ERROR;
1974 }
1975
Steve Block3856b092011-10-20 11:56:00 +01001976 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001977 mWaitWorkCV.broadcast();
1978
1979 return status;
1980}
1981
1982// destroyTrack_l() must be called with ThreadBase::mLock held
1983void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1984{
1985 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001986 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001987 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001988 removeTrack_l(track);
1989 }
1990}
1991
1992void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1993{
Eric Laurent29864602012-05-08 18:57:51 -07001994 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001995 mTracks.remove(track);
1996 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001997 // redundant as track is about to be destroyed, for dumpsys only
1998 track->mName = -1;
1999 if (track->isFastTrack()) {
2000 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07002001 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07002002 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2003 mFastTrackAvailMask |= 1 << index;
2004 // redundant as track is about to be destroyed, for dumpsys only
2005 track->mFastIndex = -1;
2006 }
Eric Laurentb469b942011-05-09 12:09:06 -07002007 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2008 if (chain != 0) {
2009 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002010 }
2011}
2012
2013String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2014{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002015 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07002016 char *s;
2017
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002018 Mutex::Autolock _l(mLock);
2019 if (initCheck() != NO_ERROR) {
2020 return out_s8;
2021 }
2022
Dima Zavin799a70e2011-04-18 16:57:27 -07002023 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07002024 out_s8 = String8(s);
2025 free(s);
2026 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002027}
2028
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002029// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
2031 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08002032 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002033
Steve Block3856b092011-10-20 11:56:00 +01002034 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002035
2036 switch (event) {
2037 case AudioSystem::OUTPUT_OPENED:
2038 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002039 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002040 desc.samplingRate = mSampleRate;
2041 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07002042 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002043 desc.latency = latency();
2044 param2 = &desc;
2045 break;
2046
2047 case AudioSystem::STREAM_CONFIG_CHANGED:
2048 param2 = &param;
2049 case AudioSystem::OUTPUT_CLOSED:
2050 default:
2051 break;
2052 }
2053 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2054}
2055
2056void AudioFlinger::PlaybackThread::readOutputParameters()
2057{
Dima Zavin799a70e2011-04-18 16:57:27 -07002058 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002059 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2060 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07002061 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002062 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002063 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002064 if (mFrameCount & 15) {
2065 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2066 mFrameCount);
2067 }
2068
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002069 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002070 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002071 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002072 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002073 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2074 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2075 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2076 maxNormalFrameCount = maxNormalFrameCount & ~15;
2077 if (maxNormalFrameCount < minNormalFrameCount) {
2078 maxNormalFrameCount = minNormalFrameCount;
2079 }
2080 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2081 if (multiplier <= 1.0) {
2082 multiplier = 1.0;
2083 } else if (multiplier <= 2.0) {
2084 if (2 * mFrameCount <= maxNormalFrameCount) {
2085 multiplier = 2.0;
2086 } else {
2087 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2088 }
2089 } else {
2090 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2091 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2092 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2093 // FIXME this rounding up should not be done if no HAL SRC
2094 uint32_t truncMult = (uint32_t) multiplier;
2095 if ((truncMult & 1)) {
2096 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2097 ++truncMult;
2098 }
2099 }
2100 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002101 }
Glenn Kasten58912562012-04-03 10:45:00 -07002102 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002103 mNormalFrameCount = multiplier * mFrameCount;
2104 // round up to nearest 16 frames to satisfy AudioMixer
2105 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002106 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002107
Glenn Kastene9dd0172012-01-27 18:08:45 -08002108 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002109 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2110 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002111
Eric Laurentde070132010-07-13 04:45:46 -07002112 // force reconfiguration of effect chains and engines to take new buffer size and audio
2113 // parameters into account
2114 // Note that mLock is not held when readOutputParameters() is called from the constructor
2115 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2116 // matter.
2117 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2118 Vector< sp<EffectChain> > effectChains = mEffectChains;
2119 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002120 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002121 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002122}
2123
Eric Laurente737cda2012-05-22 18:55:44 -07002124
Mathias Agopian65ab4712010-07-14 17:59:35 -07002125status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2126{
Glenn Kastena0d68332012-01-27 16:47:15 -08002127 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002128 return BAD_VALUE;
2129 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002130 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002131 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002132 return INVALID_OPERATION;
2133 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002134 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002135
Eric Laurent6090a172012-09-23 15:20:50 -07002136 if (isSuspended()) {
2137 // return an estimation of rendered frames when the output is suspended
2138 int32_t frames = mBytesWritten - latency_l();
2139 if (frames < 0) {
2140 frames = 0;
2141 }
2142 *dspFrames = (uint32_t)frames;
2143 return NO_ERROR;
2144 } else {
2145 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
2146 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002147}
2148
Glenn Kasten106e8a42012-08-02 13:37:12 -07002149uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002150{
2151 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002152 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002153 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002154 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002155 }
2156
2157 for (size_t i = 0; i < mTracks.size(); ++i) {
2158 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002159 if (sessionId == track->sessionId() &&
2160 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002161 result |= TRACK_SESSION;
2162 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002163 }
2164 }
2165
Eric Laurent39e94f82010-07-28 01:32:47 -07002166 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002167}
2168
Eric Laurentde070132010-07-13 04:45:46 -07002169uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2170{
Dima Zavinfce7a472011-04-19 22:30:36 -07002171 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002172 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002173 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2174 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002175 }
2176 for (size_t i = 0; i < mTracks.size(); i++) {
2177 sp<Track> track = mTracks[i];
2178 if (sessionId == track->sessionId() &&
2179 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002180 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002181 }
2182 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002183 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002184}
2185
Mathias Agopian65ab4712010-07-14 17:59:35 -07002186
Glenn Kastenaed850d2012-01-26 09:46:34 -08002187AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002188{
2189 Mutex::Autolock _l(mLock);
2190 return mOutput;
2191}
2192
2193AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2194{
2195 Mutex::Autolock _l(mLock);
2196 AudioStreamOut *output = mOutput;
2197 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002198 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2199 // must push a NULL and wait for ack
2200 mOutputSink.clear();
2201 mPipeSink.clear();
2202 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002203 return output;
2204}
2205
2206// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002207audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002208{
2209 if (mOutput == NULL) {
2210 return NULL;
2211 }
2212 return &mOutput->stream->common;
2213}
2214
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002215uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002216{
Eric Laurentab9071b2012-06-04 13:45:29 -07002217 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002218}
2219
Eric Laurenta011e352012-03-29 15:51:43 -07002220status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2221{
2222 if (!isValidSyncEvent(event)) {
2223 return BAD_VALUE;
2224 }
2225
2226 Mutex::Autolock _l(mLock);
2227
2228 for (size_t i = 0; i < mTracks.size(); ++i) {
2229 sp<Track> track = mTracks[i];
2230 if (event->triggerSession() == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07002231 (void) track->setSyncEvent(event);
Eric Laurenta011e352012-03-29 15:51:43 -07002232 return NO_ERROR;
2233 }
2234 }
2235
2236 return NAME_NOT_FOUND;
2237}
2238
Glenn Kasten106e8a42012-08-02 13:37:12 -07002239bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07002240{
Glenn Kasten0dbb3562012-08-02 16:36:50 -07002241 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
Eric Laurenta011e352012-03-29 15:51:43 -07002242}
2243
Eric Laurent44a957f2012-05-15 15:26:05 -07002244void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2245{
2246 size_t count = tracksToRemove.size();
2247 if (CC_UNLIKELY(count)) {
2248 for (size_t i = 0 ; i < count ; i++) {
2249 const sp<Track>& track = tracksToRemove.itemAt(i);
2250 if ((track->sharedBuffer() != 0) &&
2251 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2252 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2253 }
2254 }
2255 }
2256
2257}
2258
Mathias Agopian65ab4712010-07-14 17:59:35 -07002259// ----------------------------------------------------------------------------
2260
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002261AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002262 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002263 : PlaybackThread(audioFlinger, output, id, device, type),
2264 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002265 // mFastMixer below
2266 mFastMixerFutex(0)
2267 // mOutputSink below
2268 // mPipeSink below
2269 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002270{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002271 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002272 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002273 "mFrameCount=%d, mNormalFrameCount=%d",
2274 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2275 mNormalFrameCount);
2276 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2277
Mathias Agopian65ab4712010-07-14 17:59:35 -07002278 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002279 if (mChannelCount != FCC_2) {
2280 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002281 }
Glenn Kasten58912562012-04-03 10:45:00 -07002282
2283 // create an NBAIO sink for the HAL output stream, and negotiate
2284 mOutputSink = new AudioStreamOutSink(output->stream);
2285 size_t numCounterOffers = 0;
2286 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2287 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2288 ALOG_ASSERT(index == 0);
2289
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002290 // initialize fast mixer depending on configuration
2291 bool initFastMixer;
2292 switch (kUseFastMixer) {
2293 case FastMixer_Never:
2294 initFastMixer = false;
2295 break;
2296 case FastMixer_Always:
2297 initFastMixer = true;
2298 break;
2299 case FastMixer_Static:
2300 case FastMixer_Dynamic:
2301 initFastMixer = mFrameCount < mNormalFrameCount;
2302 break;
2303 }
2304 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002305
2306 // create a MonoPipe to connect our submix to FastMixer
2307 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002308 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2309 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2310 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2311 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002312 const NBAIO_Format offers[1] = {format};
2313 size_t numCounterOffers = 0;
2314 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2315 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002316 monoPipe->setAvgFrames((mScreenState & 1) ?
2317 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002318 mPipeSink = monoPipe;
2319
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002320#ifdef TEE_SINK_FRAMES
2321 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2322 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2323 numCounterOffers = 0;
2324 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2325 ALOG_ASSERT(index == 0);
2326 mTeeSink = teeSink;
2327 PipeReader *teeSource = new PipeReader(*teeSink);
2328 numCounterOffers = 0;
2329 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2330 ALOG_ASSERT(index == 0);
2331 mTeeSource = teeSource;
2332#endif
2333
Glenn Kasten58912562012-04-03 10:45:00 -07002334 // create fast mixer and configure it initially with just one fast track for our submix
2335 mFastMixer = new FastMixer();
2336 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002337#ifdef STATE_QUEUE_DUMP
2338 sq->setObserverDump(&mStateQueueObserverDump);
2339 sq->setMutatorDump(&mStateQueueMutatorDump);
2340#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002341 FastMixerState *state = sq->begin();
2342 FastTrack *fastTrack = &state->mFastTracks[0];
2343 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2344 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2345 fastTrack->mVolumeProvider = NULL;
2346 fastTrack->mGeneration++;
2347 state->mFastTracksGen++;
2348 state->mTrackMask = 1;
2349 // fast mixer will use the HAL output sink
2350 state->mOutputSink = mOutputSink.get();
2351 state->mOutputSinkGen++;
2352 state->mFrameCount = mFrameCount;
2353 state->mCommand = FastMixerState::COLD_IDLE;
2354 // already done in constructor initialization list
2355 //mFastMixerFutex = 0;
2356 state->mColdFutexAddr = &mFastMixerFutex;
2357 state->mColdGen++;
2358 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002359 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002360 sq->end();
2361 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2362
2363 // start the fast mixer
2364 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002365 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002366 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002367 if (err != 0) {
2368 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002369 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002370 }
Glenn Kasten58912562012-04-03 10:45:00 -07002371
Glenn Kastenc15d6652012-05-30 14:52:57 -07002372#ifdef AUDIO_WATCHDOG
2373 // create and start the watchdog
2374 mAudioWatchdog = new AudioWatchdog();
2375 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2376 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2377 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002378 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002379 if (err != 0) {
2380 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002381 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002382 }
2383#endif
2384
Glenn Kasten58912562012-04-03 10:45:00 -07002385 } else {
2386 mFastMixer = NULL;
2387 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002388
2389 switch (kUseFastMixer) {
2390 case FastMixer_Never:
2391 case FastMixer_Dynamic:
2392 mNormalSink = mOutputSink;
2393 break;
2394 case FastMixer_Always:
2395 mNormalSink = mPipeSink;
2396 break;
2397 case FastMixer_Static:
2398 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2399 break;
2400 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002401}
2402
2403AudioFlinger::MixerThread::~MixerThread()
2404{
Glenn Kasten58912562012-04-03 10:45:00 -07002405 if (mFastMixer != NULL) {
2406 FastMixerStateQueue *sq = mFastMixer->sq();
2407 FastMixerState *state = sq->begin();
2408 if (state->mCommand == FastMixerState::COLD_IDLE) {
2409 int32_t old = android_atomic_inc(&mFastMixerFutex);
2410 if (old == -1) {
2411 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2412 }
2413 }
2414 state->mCommand = FastMixerState::EXIT;
2415 sq->end();
2416 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2417 mFastMixer->join();
2418 // Though the fast mixer thread has exited, it's state queue is still valid.
2419 // We'll use that extract the final state which contains one remaining fast track
2420 // corresponding to our sub-mix.
2421 state = sq->begin();
2422 ALOG_ASSERT(state->mTrackMask == 1);
2423 FastTrack *fastTrack = &state->mFastTracks[0];
2424 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2425 delete fastTrack->mBufferProvider;
2426 sq->end(false /*didModify*/);
2427 delete mFastMixer;
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07002428#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002429 if (mAudioWatchdog != 0) {
2430 mAudioWatchdog->requestExit();
2431 mAudioWatchdog->requestExitAndWait();
2432 mAudioWatchdog.clear();
2433 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07002434#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002435 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002436 delete mAudioMixer;
2437}
2438
Glenn Kasten83efdd02012-02-24 07:21:32 -08002439class CpuStats {
2440public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002441 CpuStats();
2442 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002443#ifdef DEBUG_CPU_USAGE
2444private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002445 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2446 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2447
2448 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2449
2450 int mCpuNum; // thread's current CPU number
2451 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002452#endif
2453};
2454
Glenn Kasten190a46f2012-03-06 11:27:10 -08002455CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002456#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002457 : mCpuNum(-1), mCpukHz(-1)
2458#endif
2459{
2460}
2461
2462void CpuStats::sample(const String8 &title) {
2463#ifdef DEBUG_CPU_USAGE
2464 // get current thread's delta CPU time in wall clock ns
2465 double wcNs;
2466 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2467
2468 // record sample for wall clock statistics
2469 if (valid) {
2470 mWcStats.sample(wcNs);
2471 }
2472
2473 // get the current CPU number
2474 int cpuNum = sched_getcpu();
2475
2476 // get the current CPU frequency in kHz
2477 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2478
2479 // check if either CPU number or frequency changed
2480 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2481 mCpuNum = cpuNum;
2482 mCpukHz = cpukHz;
2483 // ignore sample for purposes of cycles
2484 valid = false;
2485 }
2486
2487 // if no change in CPU number or frequency, then record sample for cycle statistics
2488 if (valid && mCpukHz > 0) {
2489 double cycles = wcNs * cpukHz * 0.000001;
2490 mHzStats.sample(cycles);
2491 }
2492
2493 unsigned n = mWcStats.n();
2494 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002495 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002496 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002497 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2498 double perLoop = elapsed / (double) n;
2499 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002500 double perLoop1k = perLoop * 0.001;
2501 double mean = mWcStats.mean();
2502 double stddev = mWcStats.stddev();
2503 double minimum = mWcStats.minimum();
2504 double maximum = mWcStats.maximum();
2505 double meanCycles = mHzStats.mean();
2506 double stddevCycles = mHzStats.stddev();
2507 double minCycles = mHzStats.minimum();
2508 double maxCycles = mHzStats.maximum();
2509 mCpuUsage.resetElapsed();
2510 mWcStats.reset();
2511 mHzStats.reset();
2512 ALOGD("CPU usage for %s over past %.1f secs\n"
2513 " (%u mixer loops at %.1f mean ms per loop):\n"
2514 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2515 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2516 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2517 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002518 elapsed * .000000001, n, perLoop * .000001,
2519 mean * .001,
2520 stddev * .001,
2521 minimum * .001,
2522 maximum * .001,
2523 mean / perLoop100,
2524 stddev / perLoop100,
2525 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002526 maximum / perLoop100,
2527 meanCycles / perLoop1k,
2528 stddevCycles / perLoop1k,
2529 minCycles / perLoop1k,
2530 maxCycles / perLoop1k);
2531
Glenn Kasten83efdd02012-02-24 07:21:32 -08002532 }
2533 }
2534#endif
2535};
2536
Glenn Kasten37d825e2012-02-24 07:21:48 -08002537void AudioFlinger::PlaybackThread::checkSilentMode_l()
2538{
2539 if (!mMasterMute) {
2540 char value[PROPERTY_VALUE_MAX];
2541 if (property_get("ro.audio.silent", value, "0") > 0) {
2542 char *endptr;
2543 unsigned long ul = strtoul(value, &endptr, 0);
2544 if (*endptr == '\0' && ul != 0) {
2545 ALOGD("Silence is golden");
2546 // The setprop command will not allow a property to be changed after
2547 // the first time it is set, so we don't have to worry about un-muting.
2548 setMasterMute_l(true);
2549 }
2550 }
2551 }
2552}
2553
Glenn Kasten000f0e32012-03-01 17:10:56 -08002554bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002555{
2556 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002557
Glenn Kasten000f0e32012-03-01 17:10:56 -08002558 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002559
2560 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002561 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002562
Glenn Kasten000f0e32012-03-01 17:10:56 -08002563 // DUPLICATING
2564 // FIXME could this be made local to while loop?
2565 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002566
Glenn Kasten66fcab92012-02-24 14:59:21 -08002567 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002568 sleepTime = idleSleepTime;
2569
Glenn Kasten9f34a362012-03-20 16:46:41 -07002570 if (mType == MIXER) {
2571 sleepTimeShift = 0;
2572 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002573
Glenn Kasten83efdd02012-02-24 07:21:32 -08002574 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002575 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002576
Eric Laurentfeb0db62011-07-22 09:04:31 -07002577 acquireWakeLock();
2578
Mathias Agopian65ab4712010-07-14 17:59:35 -07002579 while (!exitPending())
2580 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002581 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002582
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002583 Vector< sp<EffectChain> > effectChains;
2584
Mathias Agopian65ab4712010-07-14 17:59:35 -07002585 processConfigEvents();
2586
Mathias Agopian65ab4712010-07-14 17:59:35 -07002587 { // scope for mLock
2588
2589 Mutex::Autolock _l(mLock);
2590
2591 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002592 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002593 }
2594
Glenn Kastenfa26a852012-03-06 11:28:04 -08002595 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002596
Mathias Agopian65ab4712010-07-14 17:59:35 -07002597 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002598 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002599 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002600 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002601
2602 threadLoop_standby();
2603
Mathias Agopian65ab4712010-07-14 17:59:35 -07002604 mStandby = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002605 }
2606
Glenn Kasten3e074702012-02-28 18:40:35 -08002607 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002608 // we're about to wait, flush the binder command buffer
2609 IPCThreadState::self()->flushCommands();
2610
Glenn Kastenfa26a852012-03-06 11:28:04 -08002611 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002612
Mathias Agopian65ab4712010-07-14 17:59:35 -07002613 if (exitPending()) break;
2614
Eric Laurentfeb0db62011-07-22 09:04:31 -07002615 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002616 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002617 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002618 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002619 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002620 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621
Eric Laurentda747442012-04-25 18:53:13 -07002622 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002623 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Eric Laurent6090a172012-09-23 15:20:50 -07002624 mBytesWritten = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002625
Glenn Kasten37d825e2012-02-24 07:21:48 -08002626 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002627
Glenn Kasten000f0e32012-03-01 17:10:56 -08002628 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002629 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002630 if (mType == MIXER) {
2631 sleepTimeShift = 0;
2632 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002633
Mathias Agopian65ab4712010-07-14 17:59:35 -07002634 continue;
2635 }
2636 }
2637
Glenn Kasten81028042012-04-30 18:15:12 -07002638 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002639 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002640
2641 // prevent any changes in effect chain list and in each effect chain
2642 // during mixing and effect process as the audio buffers could be deleted
2643 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002644 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002645 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002646
Glenn Kastenfec279f2012-03-08 07:47:15 -08002647 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002648 threadLoop_mix();
2649 } else {
2650 threadLoop_sleepTime();
2651 }
2652
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002653 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002654 sleepTime = suspendSleepTimeUs();
Eric Laurent6090a172012-09-23 15:20:50 -07002655 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002656 }
2657
2658 // only process effects if we're going to write
2659 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002660 for (size_t i = 0; i < effectChains.size(); i ++) {
2661 effectChains[i]->process_l();
2662 }
2663 }
2664
2665 // enable changes in effect chain
2666 unlockEffectChains(effectChains);
2667
2668 // sleepTime == 0 means we must write to audio hardware
2669 if (sleepTime == 0) {
2670
2671 threadLoop_write();
2672
2673if (mType == MIXER) {
2674 // write blocked detection
2675 nsecs_t now = systemTime();
2676 nsecs_t delta = now - mLastWriteTime;
2677 if (!mStandby && delta > maxPeriod) {
2678 mNumDelayedWrites++;
2679 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002680#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002681 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002682#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002683 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2684 ns2ms(delta), mNumDelayedWrites, this);
2685 lastWarning = now;
2686 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002687 }
2688}
2689
2690 mStandby = false;
2691 } else {
2692 usleep(sleepTime);
2693 }
2694
Glenn Kasten58912562012-04-03 10:45:00 -07002695 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002696 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002697 // same lock. This will also mutate and push a new fast mixer state.
2698 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002699 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002700
Glenn Kastenfa26a852012-03-06 11:28:04 -08002701 // FIXME I don't understand the need for this here;
2702 // it was in the original code but maybe the
2703 // assignment in saveOutputTracks() makes this unnecessary?
2704 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002705
2706 // Effect chains will be actually deleted here if they were removed from
2707 // mEffectChains list during mixing or effects processing
2708 effectChains.clear();
2709
2710 // FIXME Note that the above .clear() is no longer necessary since effectChains
2711 // is now local to this block, but will keep it for now (at least until merge done).
2712 }
2713
Glenn Kasten9f34a362012-03-20 16:46:41 -07002714 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2715 if (mType == MIXER || mType == DIRECT) {
2716 // put output stream into standby mode
2717 if (!mStandby) {
2718 mOutput->stream->common.standby(&mOutput->stream->common);
2719 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002720 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002721
2722 releaseWakeLock();
2723
2724 ALOGV("Thread %p type %d exiting", this, mType);
2725 return false;
2726}
2727
Glenn Kasten58912562012-04-03 10:45:00 -07002728void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2729{
Glenn Kasten58912562012-04-03 10:45:00 -07002730 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2731}
2732
2733void AudioFlinger::MixerThread::threadLoop_write()
2734{
2735 // FIXME we should only do one push per cycle; confirm this is true
2736 // Start the fast mixer if it's not already running
2737 if (mFastMixer != NULL) {
2738 FastMixerStateQueue *sq = mFastMixer->sq();
2739 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002740 if (state->mCommand != FastMixerState::MIX_WRITE &&
2741 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002742 if (state->mCommand == FastMixerState::COLD_IDLE) {
2743 int32_t old = android_atomic_inc(&mFastMixerFutex);
2744 if (old == -1) {
2745 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2746 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07002747#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002748 if (mAudioWatchdog != 0) {
2749 mAudioWatchdog->resume();
2750 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07002751#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002752 }
2753 state->mCommand = FastMixerState::MIX_WRITE;
2754 sq->end();
2755 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002756 if (kUseFastMixer == FastMixer_Dynamic) {
2757 mNormalSink = mPipeSink;
2758 }
Glenn Kasten58912562012-04-03 10:45:00 -07002759 } else {
2760 sq->end(false /*didModify*/);
2761 }
2762 }
2763 PlaybackThread::threadLoop_write();
2764}
2765
Glenn Kasten000f0e32012-03-01 17:10:56 -08002766// shared by MIXER and DIRECT, overridden by DUPLICATING
2767void AudioFlinger::PlaybackThread::threadLoop_write()
2768{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002769 // FIXME rewrite to reduce number of system calls
2770 mLastWriteTime = systemTime();
2771 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002772 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002773
Eric Laurent67c0a582012-05-01 19:31:12 -07002774 // If an NBAIO sink is present, use it to write the normal mixer's submix
2775 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002776#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002777 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002778#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002779 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002780#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002781 // update the setpoint when gScreenState changes
2782 uint32_t screenState = gScreenState;
2783 if (screenState != mScreenState) {
2784 mScreenState = screenState;
2785 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2786 if (pipe != NULL) {
2787 pipe->setAvgFrames((mScreenState & 1) ?
2788 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2789 }
2790 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002791 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002792#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002793 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002794#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002795 if (framesWritten > 0) {
2796 bytesWritten = framesWritten << mBitShift;
2797 } else {
2798 bytesWritten = framesWritten;
2799 }
2800 // otherwise use the HAL / AudioStreamOut directly
2801 } else {
2802 // Direct output thread.
2803 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002804 }
2805
Eric Laurent67c0a582012-05-01 19:31:12 -07002806 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002807 mNumWrites++;
2808 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002809}
2810
Glenn Kasten58912562012-04-03 10:45:00 -07002811void AudioFlinger::MixerThread::threadLoop_standby()
2812{
2813 // Idle the fast mixer if it's currently running
2814 if (mFastMixer != NULL) {
2815 FastMixerStateQueue *sq = mFastMixer->sq();
2816 FastMixerState *state = sq->begin();
2817 if (!(state->mCommand & FastMixerState::IDLE)) {
2818 state->mCommand = FastMixerState::COLD_IDLE;
2819 state->mColdFutexAddr = &mFastMixerFutex;
2820 state->mColdGen++;
2821 mFastMixerFutex = 0;
2822 sq->end();
2823 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2824 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002825 if (kUseFastMixer == FastMixer_Dynamic) {
2826 mNormalSink = mOutputSink;
2827 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07002828#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002829 if (mAudioWatchdog != 0) {
2830 mAudioWatchdog->pause();
2831 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07002832#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002833 } else {
2834 sq->end(false /*didModify*/);
2835 }
2836 }
2837 PlaybackThread::threadLoop_standby();
2838}
2839
Glenn Kasten000f0e32012-03-01 17:10:56 -08002840// shared by MIXER and DIRECT, overridden by DUPLICATING
2841void AudioFlinger::PlaybackThread::threadLoop_standby()
2842{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002843 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002844 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002845}
2846
2847void AudioFlinger::MixerThread::threadLoop_mix()
2848{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002849 // obtain the presentation timestamp of the next output buffer
2850 int64_t pts;
2851 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002852
John Grossman2c3b2da2012-08-02 17:08:54 -07002853 if (mNormalSink != 0) {
2854 status = mNormalSink->getNextWriteTimestamp(&pts);
2855 } else {
2856 status = mOutputSink->getNextWriteTimestamp(&pts);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002857 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002858
Glenn Kasten952eeb22012-03-06 11:30:57 -08002859 if (status != NO_ERROR) {
2860 pts = AudioBufferProvider::kInvalidPTS;
2861 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002862
Glenn Kasten952eeb22012-03-06 11:30:57 -08002863 // mix buffers...
2864 mAudioMixer->process(pts);
2865 // increase sleep time progressively when application underrun condition clears.
2866 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2867 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2868 // such that we would underrun the audio HAL.
2869 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2870 sleepTimeShift--;
2871 }
2872 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002873 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002874 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002875}
2876
2877void AudioFlinger::MixerThread::threadLoop_sleepTime()
2878{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002879 // If no tracks are ready, sleep once for the duration of an output
2880 // buffer size, then write 0s to the output
2881 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002882 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002883 sleepTime = activeSleepTime >> sleepTimeShift;
2884 if (sleepTime < kMinThreadSleepTimeUs) {
2885 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002886 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002887 // reduce sleep time in case of consecutive application underruns to avoid
2888 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2889 // duration we would end up writing less data than needed by the audio HAL if
2890 // the condition persists.
2891 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2892 sleepTimeShift++;
2893 }
2894 } else {
2895 sleepTime = idleSleepTime;
2896 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002897 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002898 memset (mMixBuffer, 0, mixBufferSize);
2899 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002900 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002901 }
2902 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002903}
2904
2905// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002906AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002907 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002908{
2909
Glenn Kasten29c23c32012-01-26 13:37:52 -08002910 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002911 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002912 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002913 size_t mixedTracks = 0;
2914 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002915 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002916 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002917 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002918
2919 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002920 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002921
Eric Laurent571d49c2010-08-11 05:20:11 -07002922 if (masterMute) {
2923 masterVolume = 0;
2924 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002925 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002926 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002927 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002928 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002929 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002930 masterVolume = (float)((v + (1 << 23)) >> 24);
2931 chain.clear();
2932 }
2933
Glenn Kasten288ed212012-04-25 17:52:27 -07002934 // prepare a new state to push
2935 FastMixerStateQueue *sq = NULL;
2936 FastMixerState *state = NULL;
2937 bool didModify = false;
2938 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2939 if (mFastMixer != NULL) {
2940 sq = mFastMixer->sq();
2941 state = sq->begin();
2942 }
2943
Mathias Agopian65ab4712010-07-14 17:59:35 -07002944 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002945 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002946 if (t == 0) continue;
2947
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002948 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002949 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002950
Glenn Kasten288ed212012-04-25 17:52:27 -07002951 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002952 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002953
2954 // It's theoretically possible (though unlikely) for a fast track to be created
2955 // and then removed within the same normal mix cycle. This is not a problem, as
2956 // the track never becomes active so it's fast mixer slot is never touched.
2957 // The converse, of removing an (active) track and then creating a new track
2958 // at the identical fast mixer slot within the same normal mix cycle,
2959 // is impossible because the slot isn't marked available until the end of each cycle.
2960 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002961 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2962 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002963 FastTrack *fastTrack = &state->mFastTracks[j];
2964
2965 // Determine whether the track is currently in underrun condition,
2966 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002967 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2968 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002969 uint32_t recentFull = (underruns.mBitFields.mFull -
2970 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2971 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2972 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2973 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2974 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2975 uint32_t recentUnderruns = recentPartial + recentEmpty;
2976 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002977 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002978 // or stopped which can occur when flush() is called while active
2979 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002980 track->mUnderrunCount += recentUnderruns;
2981 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002982
Glenn Kastend08f48c2012-05-01 18:14:02 -07002983 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002984 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002985 bool isActive = true;
2986 switch (track->mState) {
2987 case TrackBase::STOPPING_1:
2988 // track stays active in STOPPING_1 state until first underrun
2989 if (recentUnderruns > 0) {
2990 track->mState = TrackBase::STOPPING_2;
2991 }
2992 break;
2993 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002994 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002995 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002996 break;
2997 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002998 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002999 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003000 break;
3001 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07003002 if (recentFull > 0 || recentPartial > 0) {
3003 // track has provided at least some frames recently: reset retry count
3004 track->mRetryCount = kMaxTrackRetries;
3005 }
3006 if (recentUnderruns == 0) {
3007 // no recent underruns: stay active
3008 break;
3009 }
3010 // there has recently been an underrun of some kind
3011 if (track->sharedBuffer() == 0) {
3012 // were any of the recent underruns "empty" (no frames available)?
3013 if (recentEmpty == 0) {
3014 // no, then ignore the partial underruns as they are allowed indefinitely
3015 break;
3016 }
3017 // there has recently been an "empty" underrun: decrement the retry counter
3018 if (--(track->mRetryCount) > 0) {
3019 break;
3020 }
3021 // indicate to client process that the track was disabled because of underrun;
3022 // it will then automatically call start() when data is available
3023 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
3024 // remove from active list, but state remains ACTIVE [confusing but true]
3025 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003026 break;
3027 }
3028 // fall through
3029 case TrackBase::STOPPING_2:
3030 case TrackBase::PAUSED:
3031 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07003032 case TrackBase::STOPPED:
3033 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07003034 // Check for presentation complete if track is inactive
3035 // We have consumed all the buffers of this track.
3036 // This would be incomplete if we auto-paused on underrun
3037 {
3038 size_t audioHALFrames =
3039 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3040 size_t framesWritten =
3041 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten126c9102012-10-18 15:51:31 -07003042 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
Glenn Kastend08f48c2012-05-01 18:14:02 -07003043 // track stays in active list until presentation is complete
3044 break;
3045 }
3046 }
3047 if (track->isStopping_2()) {
3048 track->mState = TrackBase::STOPPED;
3049 }
3050 if (track->isStopped()) {
3051 // Can't reset directly, as fast mixer is still polling this track
3052 // track->reset();
3053 // So instead mark this track as needing to be reset after push with ack
3054 resetMask |= 1 << i;
3055 }
3056 isActive = false;
3057 break;
3058 case TrackBase::IDLE:
3059 default:
3060 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003061 }
3062
3063 if (isActive) {
3064 // was it previously inactive?
3065 if (!(state->mTrackMask & (1 << j))) {
3066 ExtendedAudioBufferProvider *eabp = track;
3067 VolumeProvider *vp = track;
3068 fastTrack->mBufferProvider = eabp;
3069 fastTrack->mVolumeProvider = vp;
3070 fastTrack->mSampleRate = track->mSampleRate;
3071 fastTrack->mChannelMask = track->mChannelMask;
3072 fastTrack->mGeneration++;
3073 state->mTrackMask |= 1 << j;
3074 didModify = true;
3075 // no acknowledgement required for newly active tracks
3076 }
3077 // cache the combined master volume and stream type volume for fast mixer; this
3078 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3079 track->mCachedVolume = track->isMuted() ?
3080 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3081 ++fastTracks;
3082 } else {
3083 // was it previously active?
3084 if (state->mTrackMask & (1 << j)) {
3085 fastTrack->mBufferProvider = NULL;
3086 fastTrack->mGeneration++;
3087 state->mTrackMask &= ~(1 << j);
3088 didModify = true;
3089 // If any fast tracks were removed, we must wait for acknowledgement
3090 // because we're about to decrement the last sp<> on those tracks.
3091 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003092 } else {
3093 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003094 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003095 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003096 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003097 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003098 }
3099 continue;
3100 }
3101
3102 { // local variable scope to avoid goto warning
3103
Mathias Agopian65ab4712010-07-14 17:59:35 -07003104 audio_track_cblk_t* cblk = track->cblk();
3105
3106 // The first time a track is added we wait
3107 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003108 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003109 // make sure that we have enough frames to mix one full buffer.
3110 // enforce this condition only once to enable draining the buffer in case the client
3111 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003112 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003113 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003114 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003115 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003116 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003117 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003118 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003119 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003120 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003121 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003122 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003123 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003124 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3125 // the minimum track buffer size is normally twice the number of frames necessary
3126 // to fill one buffer and the resampler should not leave more than one buffer worth
3127 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003128 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003129 }
3130 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003131 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003132 !track->isPaused() && !track->isTerminated())
3133 {
Glenn Kastencbe4b362012-10-18 15:51:03 -07003134 ALOGVV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003135
3136 mixedTracks++;
3137
3138 // track->mainBuffer() != mMixBuffer means there is an effect chain
3139 // connected to the track
3140 chain.clear();
3141 if (track->mainBuffer() != mMixBuffer) {
3142 chain = getEffectChain_l(track->sessionId());
3143 // Delegate volume control to effect in track effect chain if needed
3144 if (chain != 0) {
3145 tracksWithEffect++;
3146 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003147 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003148 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003149 }
3150 }
3151
3152
3153 int param = AudioMixer::VOLUME;
3154 if (track->mFillingUpStatus == Track::FS_FILLED) {
3155 // no ramp for the first volume setting
3156 track->mFillingUpStatus = Track::FS_ACTIVE;
3157 if (track->mState == TrackBase::RESUMING) {
3158 track->mState = TrackBase::ACTIVE;
3159 param = AudioMixer::RAMP_VOLUME;
3160 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003161 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003162 } else if (cblk->server != 0) {
3163 // If the track is stopped before the first frame was mixed,
3164 // do not apply ramp
3165 param = AudioMixer::RAMP_VOLUME;
3166 }
3167
3168 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003169 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003170 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003171 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003172 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003173 if (track->isPausing()) {
3174 track->setPaused();
3175 }
3176 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003177
Mathias Agopian65ab4712010-07-14 17:59:35 -07003178 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003179 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003180 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003181 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003182 vl = vlr & 0xFFFF;
3183 vr = vlr >> 16;
3184 // track volumes come from shared memory, so can't be trusted and must be clamped
3185 if (vl > MAX_GAIN_INT) {
3186 ALOGV("Track left volume out of range: %04X", vl);
3187 vl = MAX_GAIN_INT;
3188 }
3189 if (vr > MAX_GAIN_INT) {
3190 ALOGV("Track right volume out of range: %04X", vr);
3191 vr = MAX_GAIN_INT;
3192 }
3193 // now apply the master volume and stream type volume
3194 vl = (uint32_t)(v * vl) << 12;
3195 vr = (uint32_t)(v * vr) << 12;
3196 // assuming master volume and stream type volume each go up to 1.0,
3197 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003198
Glenn Kasten05632a52012-01-03 14:22:33 -08003199 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3200 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003201 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003202 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003203 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003204 }
3205 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003206 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003207 // Delegate volume control to effect in track effect chain if needed
3208 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3209 // Do not ramp volume if volume is controlled by effect
3210 param = AudioMixer::VOLUME;
3211 track->mHasVolumeController = true;
3212 } else {
3213 // force no volume ramp when volume controller was just disabled or removed
3214 // from effect chain to avoid volume spike
3215 if (track->mHasVolumeController) {
3216 param = AudioMixer::VOLUME;
3217 }
3218 track->mHasVolumeController = false;
3219 }
3220
3221 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003222 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003223 vl = (vl + (1 << 11)) >> 12;
3224 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3225 vr = (vr + (1 << 11)) >> 12;
3226 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003227
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003228 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 -07003229
Mathias Agopian65ab4712010-07-14 17:59:35 -07003230 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003231 mAudioMixer->setBufferProvider(name, track);
3232 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003233
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003234 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3235 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3236 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003237 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003238 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003239 AudioMixer::TRACK,
3240 AudioMixer::FORMAT, (void *)track->format());
3241 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003242 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003243 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003244 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003245 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003246 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003247 AudioMixer::RESAMPLE,
3248 AudioMixer::SAMPLE_RATE,
3249 (void *)(cblk->sampleRate));
3250 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003251 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003252 AudioMixer::TRACK,
3253 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3254 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003255 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003256 AudioMixer::TRACK,
3257 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3258
3259 // reset retry count
3260 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003261
Eric Laurent27741442012-01-17 19:20:12 -08003262 // If one track is ready, set the mixer ready if:
3263 // - the mixer was not ready during previous round OR
3264 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003265 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003266 mixerStatus != MIXER_TRACKS_ENABLED) {
3267 mixerStatus = MIXER_TRACKS_READY;
3268 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003269 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003270 // clear effect chain input buffer if an active track underruns to avoid sending
3271 // previous audio buffer again to effects
3272 chain = getEffectChain_l(track->sessionId());
3273 if (chain != 0) {
3274 chain->clearInputBuffer();
3275 }
3276
Glenn Kastencbe4b362012-10-18 15:51:03 -07003277 ALOGVV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Glenn Kasten52013e72012-09-26 08:34:10 -07003278 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent83faee02012-04-27 18:24:29 -07003279 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003280 // We have consumed all the buffers of this track.
3281 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003282 // TODO: use actual buffer filling status instead of latency when available from
3283 // audio HAL
Jean-Michel Trivi115b87e2012-10-16 10:29:01 -07003284 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07003285 size_t framesWritten =
3286 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten126c9102012-10-18 15:51:31 -07003287 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003288 if (track->isStopped()) {
3289 track->reset();
3290 }
Eric Laurenta011e352012-03-29 15:51:43 -07003291 tracksToRemove->add(track);
3292 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003293 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003294 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003295 // No buffers for this track. Give it a few chances to
3296 // fill a buffer, then remove it from active list.
Glenn Kasten52013e72012-09-26 08:34:10 -07003297 if (--(track->mRetryCount) <= 0) {
3298 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003299 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003300 // indicate to client process that the track was disabled because of underrun;
3301 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003302 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003303 // If one track is not ready, mark the mixer also not ready if:
3304 // - the mixer was ready during previous round OR
3305 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003306 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003307 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003308 mixerStatus = MIXER_TRACKS_ENABLED;
3309 }
3310 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003311 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003312 }
Glenn Kasten58912562012-04-03 10:45:00 -07003313
3314 } // local variable scope to avoid goto warning
3315track_is_ready: ;
3316
Mathias Agopian65ab4712010-07-14 17:59:35 -07003317 }
3318
Glenn Kasten288ed212012-04-25 17:52:27 -07003319 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003320 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003321 if (didModify) {
3322 state->mFastTracksGen++;
3323 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3324 if (kUseFastMixer == FastMixer_Dynamic &&
3325 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3326 state->mCommand = FastMixerState::COLD_IDLE;
3327 state->mColdFutexAddr = &mFastMixerFutex;
3328 state->mColdGen++;
3329 mFastMixerFutex = 0;
3330 if (kUseFastMixer == FastMixer_Dynamic) {
3331 mNormalSink = mOutputSink;
3332 }
3333 // If we go into cold idle, need to wait for acknowledgement
3334 // so that fast mixer stops doing I/O.
3335 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003336 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003337 }
3338 sq->end();
3339 }
3340 if (sq != NULL) {
3341 sq->end(didModify);
3342 sq->push(block);
3343 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07003344#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003345 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3346 mAudioWatchdog->pause();
3347 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07003348#endif
Glenn Kasten288ed212012-04-25 17:52:27 -07003349
3350 // Now perform the deferred reset on fast tracks that have stopped
3351 while (resetMask != 0) {
3352 size_t i = __builtin_ctz(resetMask);
3353 ALOG_ASSERT(i < count);
3354 resetMask &= ~(1 << i);
3355 sp<Track> t = mActiveTracks[i].promote();
3356 if (t == 0) continue;
3357 Track* track = t.get();
3358 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3359 track->reset();
3360 }
Glenn Kasten58912562012-04-03 10:45:00 -07003361
Mathias Agopian65ab4712010-07-14 17:59:35 -07003362 // remove all the tracks that need to be...
3363 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003364 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003365 for (size_t i=0 ; i<count ; i++) {
3366 const sp<Track>& track = tracksToRemove->itemAt(i);
3367 mActiveTracks.remove(track);
3368 if (track->mainBuffer() != mMixBuffer) {
3369 chain = getEffectChain_l(track->sessionId());
3370 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003371 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003372 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003373 }
3374 }
3375 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003376 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003377 }
3378 }
3379 }
3380
3381 // mix buffer must be cleared if all tracks are connected to an
3382 // effect chain as in this case the mixer will not write to
3383 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003384 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3385 // FIXME as a performance optimization, should remember previous zero status
3386 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003387 }
3388
Glenn Kasten58912562012-04-03 10:45:00 -07003389 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003390 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003391 if (fastTracks > 0) {
3392 mixerStatus = MIXER_TRACKS_READY;
3393 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003394 return mixerStatus;
3395}
3396
Glenn Kasten66fcab92012-02-24 14:59:21 -08003397/*
3398The derived values that are cached:
3399 - mixBufferSize from frame count * frame size
3400 - activeSleepTime from activeSleepTimeUs()
3401 - idleSleepTime from idleSleepTimeUs()
3402 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3403 - maxPeriod from frame count and sample rate (MIXER only)
3404
3405The parameters that affect these derived values are:
3406 - frame count
3407 - frame size
3408 - sample rate
3409 - device type: A2DP or not
3410 - device latency
3411 - format: PCM or not
3412 - active sleep time
3413 - idle sleep time
3414*/
3415
3416void AudioFlinger::PlaybackThread::cacheParameters_l()
3417{
Glenn Kasten58912562012-04-03 10:45:00 -07003418 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003419 activeSleepTime = activeSleepTimeUs();
3420 idleSleepTime = idleSleepTimeUs();
3421}
3422
Eric Laurent22167852012-06-20 12:26:32 -07003423void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003424{
Steve Block3856b092011-10-20 11:56:00 +01003425 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003426 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003427 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003428
Mathias Agopian65ab4712010-07-14 17:59:35 -07003429 size_t size = mTracks.size();
3430 for (size_t i = 0; i < size; i++) {
3431 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003432 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003433 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003434 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003435 }
3436 }
3437}
3438
Mathias Agopian65ab4712010-07-14 17:59:35 -07003439// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivicff71372012-09-10 18:58:27 -07003440int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003441{
Jean-Michel Trivicff71372012-09-10 18:58:27 -07003442 return mAudioMixer->getTrackName(channelMask, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003443}
3444
3445// deleteTrackName_l() must be called with ThreadBase::mLock held
3446void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3447{
Steve Block3856b092011-10-20 11:56:00 +01003448 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003449 mAudioMixer->deleteTrackName(name);
3450}
3451
3452// checkForNewParameters_l() must be called with ThreadBase::mLock held
3453bool AudioFlinger::MixerThread::checkForNewParameters_l()
3454{
Glenn Kasten58912562012-04-03 10:45:00 -07003455 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3456 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003457 bool reconfig = false;
3458
3459 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003460
3461 if (mFastMixer != NULL) {
3462 FastMixerStateQueue *sq = mFastMixer->sq();
3463 FastMixerState *state = sq->begin();
3464 if (!(state->mCommand & FastMixerState::IDLE)) {
3465 previousCommand = state->mCommand;
3466 state->mCommand = FastMixerState::HOT_IDLE;
3467 sq->end();
3468 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3469 } else {
3470 sq->end(false /*didModify*/);
3471 }
3472 }
3473
Mathias Agopian65ab4712010-07-14 17:59:35 -07003474 status_t status = NO_ERROR;
3475 String8 keyValuePair = mNewParameters[0];
3476 AudioParameter param = AudioParameter(keyValuePair);
3477 int value;
3478
3479 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3480 reconfig = true;
3481 }
3482 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003483 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003484 status = BAD_VALUE;
3485 } else {
3486 reconfig = true;
3487 }
3488 }
3489 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003490 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003491 status = BAD_VALUE;
3492 } else {
3493 reconfig = true;
3494 }
3495 }
3496 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3497 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003498 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003499 // if frame count is changed after track creation
3500 if (!mTracks.isEmpty()) {
3501 status = INVALID_OPERATION;
3502 } else {
3503 reconfig = true;
3504 }
3505 }
3506 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003507#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003508 // when changing the audio output device, call addBatteryData to notify
3509 // the change
Eric Laurent88959252012-08-28 14:26:53 -07003510 if (mOutDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003511 uint32_t params = 0;
3512 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003513 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003514 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3515 }
3516
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003517 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003518 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003519 // check if any other device (except speaker) is on
3520 if (value & deviceWithoutSpeaker ) {
3521 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3522 }
3523
3524 if (params != 0) {
3525 addBatteryData(params);
3526 }
3527 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003528#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003529
Mathias Agopian65ab4712010-07-14 17:59:35 -07003530 // forward device change to effects that have requested to be
3531 // aware of attached audio device.
Eric Laurent88959252012-08-28 14:26:53 -07003532 mOutDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003533 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent88959252012-08-28 14:26:53 -07003534 mEffectChains[i]->setDevice_l(mOutDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003535 }
3536 }
3537
3538 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003539 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003540 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003541 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003542 mOutput->stream->common.standby(&mOutput->stream->common);
3543 mStandby = true;
3544 mBytesWritten = 0;
3545 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003546 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003547 }
3548 if (status == NO_ERROR && reconfig) {
3549 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003550 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3551 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003552 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003553 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003554 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivicff71372012-09-10 18:58:27 -07003555 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003556 if (name < 0) break;
3557 mTracks[i]->mName = name;
3558 // limit track sample rate to 2 x new output sample rate
3559 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3560 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3561 }
3562 }
Eric Laurentef6be0b2012-09-13 11:18:23 -07003563 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003564 }
3565 }
3566
3567 mNewParameters.removeAt(0);
3568
3569 mParamStatus = status;
3570 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003571 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3572 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003573 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003574 }
Glenn Kasten58912562012-04-03 10:45:00 -07003575
3576 if (!(previousCommand & FastMixerState::IDLE)) {
3577 ALOG_ASSERT(mFastMixer != NULL);
3578 FastMixerStateQueue *sq = mFastMixer->sq();
3579 FastMixerState *state = sq->begin();
3580 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3581 state->mCommand = previousCommand;
3582 sq->end();
3583 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3584 }
3585
Mathias Agopian65ab4712010-07-14 17:59:35 -07003586 return reconfig;
3587}
3588
Glenn Kasten8c327342012-09-30 12:29:28 -07003589void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003590{
Glenn Kasten8c327342012-09-30 12:29:28 -07003591 NBAIO_Source *teeSource = source.get();
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003592 if (teeSource != NULL) {
Glenn Kasten8c327342012-09-30 12:29:28 -07003593 char teeTime[16];
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003594 struct timeval tv;
3595 gettimeofday(&tv, NULL);
3596 struct tm tm;
3597 localtime_r(&tv.tv_sec, &tm);
Glenn Kasten8c327342012-09-30 12:29:28 -07003598 strftime(teeTime, sizeof(teeTime), "%T", &tm);
3599 char teePath[64];
3600 sprintf(teePath, "/data/misc/media/%s_%d.wav", teeTime, id);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003601 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3602 if (teeFd >= 0) {
3603 char wavHeader[44];
3604 memcpy(wavHeader,
3605 "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",
3606 sizeof(wavHeader));
3607 NBAIO_Format format = teeSource->format();
3608 unsigned channelCount = Format_channelCount(format);
3609 ALOG_ASSERT(channelCount <= FCC_2);
3610 unsigned sampleRate = Format_sampleRate(format);
3611 wavHeader[22] = channelCount; // number of channels
3612 wavHeader[24] = sampleRate; // sample rate
3613 wavHeader[25] = sampleRate >> 8;
3614 wavHeader[32] = channelCount * 2; // block alignment
3615 write(teeFd, wavHeader, sizeof(wavHeader));
3616 size_t total = 0;
3617 bool firstRead = true;
3618 for (;;) {
3619#define TEE_SINK_READ 1024
3620 short buffer[TEE_SINK_READ * FCC_2];
3621 size_t count = TEE_SINK_READ;
John Grossman2c3b2da2012-08-02 17:08:54 -07003622 ssize_t actual = teeSource->read(buffer, count,
3623 AudioBufferProvider::kInvalidPTS);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003624 bool wasFirstRead = firstRead;
3625 firstRead = false;
3626 if (actual <= 0) {
3627 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3628 continue;
3629 }
3630 break;
3631 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003632 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003633 write(teeFd, buffer, actual * channelCount * sizeof(short));
3634 total += actual;
3635 }
3636 lseek(teeFd, (off_t) 4, SEEK_SET);
3637 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3638 write(teeFd, &temp, sizeof(temp));
3639 lseek(teeFd, (off_t) 40, SEEK_SET);
3640 temp = total * channelCount * sizeof(short);
3641 write(teeFd, &temp, sizeof(temp));
3642 close(teeFd);
3643 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3644 } else {
3645 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3646 }
3647 }
Glenn Kasten8c327342012-09-30 12:29:28 -07003648}
3649
3650void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3651{
3652 const size_t SIZE = 256;
3653 char buffer[SIZE];
3654 String8 result;
3655
3656 PlaybackThread::dumpInternals(fd, args);
3657
3658 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3659 result.append(buffer);
3660 write(fd, result.string(), result.size());
3661
3662 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3663 FastMixerDumpState copy = mFastMixerDumpState;
3664 copy.dump(fd);
3665
3666#ifdef STATE_QUEUE_DUMP
3667 // Similar for state queue
3668 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3669 observerCopy.dump(fd);
3670 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3671 mutatorCopy.dump(fd);
3672#endif
3673
3674 // Write the tee output to a .wav file
3675 dumpTee(fd, mTeeSource, mId);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003676
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07003677#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003678 if (mAudioWatchdog != 0) {
3679 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3680 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3681 wdCopy.dump(fd);
3682 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07003683#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003684}
3685
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003686uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003687{
Glenn Kasten58912562012-04-03 10:45:00 -07003688 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003689}
3690
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003691uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003692{
Glenn Kasten58912562012-04-03 10:45:00 -07003693 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003694}
3695
Glenn Kasten66fcab92012-02-24 14:59:21 -08003696void AudioFlinger::MixerThread::cacheParameters_l()
3697{
3698 PlaybackThread::cacheParameters_l();
3699
3700 // FIXME: Relaxed timing because of a certain device that can't meet latency
3701 // Should be reduced to 2x after the vendor fixes the driver issue
3702 // increase threshold again due to low power audio mode. The way this warning
3703 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003704 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003705}
3706
Mathias Agopian65ab4712010-07-14 17:59:35 -07003707// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003708AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003709 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003710 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003711 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003712{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003713}
3714
3715AudioFlinger::DirectOutputThread::~DirectOutputThread()
3716{
3717}
3718
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003719AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3720 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003721)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003722{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003723 sp<Track> trackToRemove;
3724
Glenn Kastenfec279f2012-03-08 07:47:15 -08003725 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003726
Glenn Kasten952eeb22012-03-06 11:30:57 -08003727 // find out which tracks need to be processed
3728 if (mActiveTracks.size() != 0) {
3729 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003730 // The track died recently
3731 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003732
Glenn Kasten952eeb22012-03-06 11:30:57 -08003733 Track* const track = t.get();
3734 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003735
Glenn Kasten952eeb22012-03-06 11:30:57 -08003736 // The first time a track is added we wait
3737 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003738 uint32_t minFrames;
3739 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3740 minFrames = mNormalFrameCount;
3741 } else {
3742 minFrames = 1;
3743 }
3744 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003745 !track->isPaused() && !track->isTerminated())
3746 {
Glenn Kastencbe4b362012-10-18 15:51:03 -07003747 ALOGVV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003748
Glenn Kasten952eeb22012-03-06 11:30:57 -08003749 if (track->mFillingUpStatus == Track::FS_FILLED) {
3750 track->mFillingUpStatus = Track::FS_ACTIVE;
3751 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003752 if (track->mState == TrackBase::RESUMING) {
3753 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003754 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003755 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003756
Glenn Kasten952eeb22012-03-06 11:30:57 -08003757 // compute volume for this track
3758 float left, right;
3759 if (track->isMuted() || mMasterMute || track->isPausing() ||
3760 mStreamTypes[track->streamType()].mute) {
3761 left = right = 0;
3762 if (track->isPausing()) {
3763 track->setPaused();
3764 }
3765 } else {
3766 float typeVolume = mStreamTypes[track->streamType()].volume;
3767 float v = mMasterVolume * typeVolume;
3768 uint32_t vlr = cblk->getVolumeLR();
3769 float v_clamped = v * (vlr & 0xFFFF);
3770 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3771 left = v_clamped/MAX_GAIN;
3772 v_clamped = v * (vlr >> 16);
3773 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3774 right = v_clamped/MAX_GAIN;
3775 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003776
Glenn Kasten952eeb22012-03-06 11:30:57 -08003777 if (left != mLeftVolFloat || right != mRightVolFloat) {
3778 mLeftVolFloat = left;
3779 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003780
Glenn Kasten952eeb22012-03-06 11:30:57 -08003781 // Convert volumes from float to 8.24
3782 uint32_t vl = (uint32_t)(left * (1 << 24));
3783 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003784
Glenn Kasten952eeb22012-03-06 11:30:57 -08003785 // Delegate volume control to effect in track effect chain if needed
3786 // only one effect chain can be present on DirectOutputThread, so if
3787 // there is one, the track is connected to it
3788 if (!mEffectChains.isEmpty()) {
3789 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003790 mEffectChains[0]->setVolume_l(&vl, &vr);
3791 left = (float)vl / (1 << 24);
3792 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003793 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003794 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003795 }
3796
3797 // reset retry count
3798 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003799 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003800 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003801 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003802 // clear effect chain input buffer if an active track underruns to avoid sending
3803 // previous audio buffer again to effects
3804 if (!mEffectChains.isEmpty()) {
3805 mEffectChains[0]->clearInputBuffer();
3806 }
3807
Glenn Kastencbe4b362012-10-18 15:51:03 -07003808 ALOGVV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten52013e72012-09-26 08:34:10 -07003809 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent67c0a582012-05-01 19:31:12 -07003810 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003811 // We have consumed all the buffers of this track.
3812 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003813 // TODO: implement behavior for compressed audio
Jean-Michel Trivi115b87e2012-10-16 10:29:01 -07003814 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07003815 size_t framesWritten =
3816 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten126c9102012-10-18 15:51:31 -07003817 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003818 if (track->isStopped()) {
3819 track->reset();
3820 }
Eric Laurenta011e352012-03-29 15:51:43 -07003821 trackToRemove = track;
3822 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003823 } else {
3824 // No buffers for this track. Give it a few chances to
3825 // fill a buffer, then remove it from active list.
Glenn Kasten52013e72012-09-26 08:34:10 -07003826 if (--(track->mRetryCount) <= 0) {
3827 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Glenn Kasten952eeb22012-03-06 11:30:57 -08003828 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003829 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003830 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003831 }
3832 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003833 }
3834 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003835
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003836 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003837 // remove all the tracks that need to be...
3838 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003839 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003840 mActiveTracks.remove(trackToRemove);
3841 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003842 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003843 trackToRemove->sessionId());
3844 mEffectChains[0]->decActiveTrackCnt();
3845 }
3846 if (trackToRemove->isTerminated()) {
3847 removeTrack_l(trackToRemove);
3848 }
3849 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003850
Glenn Kastenfec279f2012-03-08 07:47:15 -08003851 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003852}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003853
Glenn Kasten000f0e32012-03-01 17:10:56 -08003854void AudioFlinger::DirectOutputThread::threadLoop_mix()
3855{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003856 AudioBufferProvider::Buffer buffer;
3857 size_t frameCount = mFrameCount;
3858 int8_t *curBuf = (int8_t *)mMixBuffer;
3859 // output audio to hardware
3860 while (frameCount) {
3861 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003862 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003863 if (CC_UNLIKELY(buffer.raw == NULL)) {
3864 memset(curBuf, 0, frameCount * mFrameSize);
3865 break;
3866 }
3867 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3868 frameCount -= buffer.frameCount;
3869 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003870 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003871 }
3872 sleepTime = 0;
3873 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003874 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003875
Glenn Kasten000f0e32012-03-01 17:10:56 -08003876}
3877
3878void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3879{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003880 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003881 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003882 sleepTime = activeSleepTime;
3883 } else {
3884 sleepTime = idleSleepTime;
3885 }
3886 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003887 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003888 sleepTime = 0;
3889 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003890}
3891
3892// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivicff71372012-09-10 18:58:27 -07003893int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3894 int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003895{
3896 return 0;
3897}
3898
3899// deleteTrackName_l() must be called with ThreadBase::mLock held
3900void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3901{
3902}
3903
3904// checkForNewParameters_l() must be called with ThreadBase::mLock held
3905bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3906{
3907 bool reconfig = false;
3908
3909 while (!mNewParameters.isEmpty()) {
3910 status_t status = NO_ERROR;
3911 String8 keyValuePair = mNewParameters[0];
3912 AudioParameter param = AudioParameter(keyValuePair);
3913 int value;
3914
3915 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3916 // do not accept frame count changes if tracks are open as the track buffer
3917 // size depends on frame count and correct behavior would not be garantied
3918 // if frame count is changed after track creation
3919 if (!mTracks.isEmpty()) {
3920 status = INVALID_OPERATION;
3921 } else {
3922 reconfig = true;
3923 }
3924 }
3925 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003926 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003927 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003928 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003929 mOutput->stream->common.standby(&mOutput->stream->common);
3930 mStandby = true;
3931 mBytesWritten = 0;
3932 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003933 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003934 }
3935 if (status == NO_ERROR && reconfig) {
3936 readOutputParameters();
Eric Laurentef6be0b2012-09-13 11:18:23 -07003937 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003938 }
3939 }
3940
3941 mNewParameters.removeAt(0);
3942
3943 mParamStatus = status;
3944 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003945 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3946 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003947 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003948 }
3949 return reconfig;
3950}
3951
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003952uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003953{
3954 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003955 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003956 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003957 } else {
3958 time = 10000;
3959 }
3960 return time;
3961}
3962
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003963uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003964{
3965 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003966 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003967 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003968 } else {
3969 time = 10000;
3970 }
3971 return time;
3972}
3973
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003974uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003975{
3976 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003977 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003978 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3979 } else {
3980 time = 10000;
3981 }
3982 return time;
3983}
3984
Glenn Kasten66fcab92012-02-24 14:59:21 -08003985void AudioFlinger::DirectOutputThread::cacheParameters_l()
3986{
3987 PlaybackThread::cacheParameters_l();
3988
3989 // use shorter standby delay as on normal output to release
3990 // hardware resources as soon as possible
3991 standbyDelay = microseconds(activeSleepTime*2);
3992}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003993
Mathias Agopian65ab4712010-07-14 17:59:35 -07003994// ----------------------------------------------------------------------------
3995
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003996AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003997 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Eric Laurent88959252012-08-28 14:26:53 -07003998 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), DUPLICATING),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003999 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004000{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004001 addOutputTrack(mainThread);
4002}
4003
4004AudioFlinger::DuplicatingThread::~DuplicatingThread()
4005{
4006 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4007 mOutputTracks[i]->destroy();
4008 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004009}
4010
Glenn Kasten000f0e32012-03-01 17:10:56 -08004011void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004012{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004013 // mix buffers...
4014 if (outputsReady(outputTracks)) {
4015 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4016 } else {
4017 memset(mMixBuffer, 0, mixBufferSize);
4018 }
4019 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07004020 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004021 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004022}
4023
4024void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4025{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004026 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004027 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004028 sleepTime = activeSleepTime;
4029 } else {
4030 sleepTime = idleSleepTime;
4031 }
4032 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004033 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4034 writeFrames = mNormalFrameCount;
4035 memset(mMixBuffer, 0, mixBufferSize);
4036 } else {
4037 // flush remaining overflow buffers in output tracks
4038 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004039 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004040 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004041 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08004042}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004043
Glenn Kasten000f0e32012-03-01 17:10:56 -08004044void AudioFlinger::DuplicatingThread::threadLoop_write()
4045{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004046 for (size_t i = 0; i < outputTracks.size(); i++) {
4047 outputTracks[i]->write(mMixBuffer, writeFrames);
4048 }
4049 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004050}
Glenn Kasten688a6402012-02-29 07:57:06 -08004051
Glenn Kasten000f0e32012-03-01 17:10:56 -08004052void AudioFlinger::DuplicatingThread::threadLoop_standby()
4053{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004054 // DuplicatingThread implements standby by stopping all tracks
4055 for (size_t i = 0; i < outputTracks.size(); i++) {
4056 outputTracks[i]->stop();
4057 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004058}
4059
Glenn Kastenfa26a852012-03-06 11:28:04 -08004060void AudioFlinger::DuplicatingThread::saveOutputTracks()
4061{
4062 outputTracks = mOutputTracks;
4063}
4064
4065void AudioFlinger::DuplicatingThread::clearOutputTracks()
4066{
4067 outputTracks.clear();
4068}
4069
Mathias Agopian65ab4712010-07-14 17:59:35 -07004070void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4071{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004072 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004073 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004074 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004075 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004076 this,
4077 mSampleRate,
4078 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004079 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004080 frameCount);
4081 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004082 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004083 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004084 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004085 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004086 }
4087}
4088
4089void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4090{
4091 Mutex::Autolock _l(mLock);
4092 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004093 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004094 mOutputTracks[i]->destroy();
4095 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004096 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004097 return;
4098 }
4099 }
Steve Block3856b092011-10-20 11:56:00 +01004100 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004101}
4102
Glenn Kasten438b0362012-03-06 11:24:48 -08004103// caller must hold mLock
4104void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004105{
4106 mWaitTimeMs = UINT_MAX;
4107 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4108 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004109 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004110 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4111 if (waitTimeMs < mWaitTimeMs) {
4112 mWaitTimeMs = waitTimeMs;
4113 }
4114 }
4115 }
4116}
4117
4118
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004119bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004120{
4121 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004122 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004123 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004124 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004125 return false;
4126 }
4127 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004128 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004129 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004130 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004131 return false;
4132 }
4133 }
4134 return true;
4135}
4136
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004137uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004138{
4139 return (mWaitTimeMs * 1000) / 2;
4140}
4141
Glenn Kasten66fcab92012-02-24 14:59:21 -08004142void AudioFlinger::DuplicatingThread::cacheParameters_l()
4143{
4144 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4145 updateWaitTime_l();
4146
4147 MixerThread::cacheParameters_l();
4148}
4149
Mathias Agopian65ab4712010-07-14 17:59:35 -07004150// ----------------------------------------------------------------------------
4151
4152// TrackBase constructor must be called with AudioFlinger::mLock held
4153AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004154 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004155 const sp<Client>& client,
4156 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004157 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004158 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004159 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004160 const sp<IMemory>& sharedBuffer,
4161 int sessionId)
4162 : RefBase(),
4163 mThread(thread),
4164 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004165 mCblk(NULL),
4166 // mBuffer
4167 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004168 mFrameCount(0),
4169 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004170 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004171 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004172 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004173 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004174 // mChannelCount
4175 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004176{
Steve Block3856b092011-10-20 11:56:00 +01004177 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004178
Steve Blockb8a80522011-12-20 16:23:08 +00004179 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004180 size_t size = sizeof(audio_track_cblk_t);
4181 uint8_t channelCount = popcount(channelMask);
4182 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4183 if (sharedBuffer == 0) {
4184 size += bufferSize;
4185 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004186
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004187 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004188 mCblkMemory = client->heap()->allocate(size);
4189 if (mCblkMemory != 0) {
4190 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004191 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004192 new(mCblk) audio_track_cblk_t();
4193 // clear all buffers
4194 mCblk->frameCount = frameCount;
4195 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004196// uncomment the following lines to quickly test 32-bit wraparound
4197// mCblk->user = 0xffff0000;
4198// mCblk->server = 0xffff0000;
4199// mCblk->userBase = 0xffff0000;
4200// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004201 mChannelCount = channelCount;
4202 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203 if (sharedBuffer == 0) {
4204 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4205 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4206 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004207 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004208 mCblk->flags = CBLK_UNDERRUN_ON;
4209 } else {
4210 mBuffer = sharedBuffer->pointer();
4211 }
4212 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4213 }
4214 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004215 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004216 client->heap()->dump("AudioTrack");
4217 return;
4218 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004219 } else {
4220 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004221 // construct the shared structure in-place.
4222 new(mCblk) audio_track_cblk_t();
4223 // clear all buffers
4224 mCblk->frameCount = frameCount;
4225 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004226// uncomment the following lines to quickly test 32-bit wraparound
4227// mCblk->user = 0xffff0000;
4228// mCblk->server = 0xffff0000;
4229// mCblk->userBase = 0xffff0000;
4230// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004231 mChannelCount = channelCount;
4232 mChannelMask = channelMask;
4233 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4234 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4235 // Force underrun condition to avoid false underrun callback until first data is
4236 // written to buffer (other flags are cleared)
4237 mCblk->flags = CBLK_UNDERRUN_ON;
4238 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004239 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004240}
4241
4242AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4243{
Glenn Kastena0d68332012-01-27 16:47:15 -08004244 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004245 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004246 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004247 } else {
4248 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004249 }
4250 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004251 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004252 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004253 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004254 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004255 // If the client's reference count drops to zero, the associated destructor
4256 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4257 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004258 mClient.clear();
4259 }
4260}
4261
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004262// AudioBufferProvider interface
4263// getNextBuffer() = 0;
4264// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004265void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4266{
Glenn Kastene0feee32011-12-13 11:53:26 -08004267 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004268 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004269 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004270 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004271 buffer->frameCount = 0;
4272}
4273
4274bool AudioFlinger::ThreadBase::TrackBase::step() {
4275 bool result;
4276 audio_track_cblk_t* cblk = this->cblk();
4277
4278 result = cblk->stepServer(mFrameCount);
4279 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004280 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004281 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004282 }
4283 return result;
4284}
4285
4286void AudioFlinger::ThreadBase::TrackBase::reset() {
4287 audio_track_cblk_t* cblk = this->cblk();
4288
4289 cblk->user = 0;
4290 cblk->server = 0;
4291 cblk->userBase = 0;
4292 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004293 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004294 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004295}
4296
Mathias Agopian65ab4712010-07-14 17:59:35 -07004297int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4298 return (int)mCblk->sampleRate;
4299}
4300
Mathias Agopian65ab4712010-07-14 17:59:35 -07004301void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4302 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004303 size_t frameSize = cblk->frameSize;
4304 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4305 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004306
4307 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004308 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4309 "TrackBase::getBuffer buffer out of range:\n"
4310 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4311 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004312 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004313 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004314
4315 return bufferStart;
4316}
4317
Eric Laurenta011e352012-03-29 15:51:43 -07004318status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4319{
4320 mSyncEvents.add(event);
4321 return NO_ERROR;
4322}
4323
Mathias Agopian65ab4712010-07-14 17:59:35 -07004324// ----------------------------------------------------------------------------
4325
4326// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4327AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004328 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004329 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004330 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004331 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004332 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004333 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004334 int frameCount,
4335 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004336 int sessionId,
4337 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004338 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004339 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004340 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004341 // mRetryCount initialized later when needed
4342 mSharedBuffer(sharedBuffer),
4343 mStreamType(streamType),
4344 mName(-1), // see note below
4345 mMainBuffer(thread->mixBuffer()),
4346 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004347 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004348 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004349 mFlags(flags),
4350 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004351 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004352 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004353{
4354 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004355 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4356 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004357 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004358 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivicff71372012-09-10 18:58:27 -07004359 mName = thread->getTrackName_l(channelMask, sessionId);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004360 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004361 if (mName < 0) {
4362 ALOGE("no more track names available");
4363 return;
4364 }
4365 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004366 if (flags & IAudioFlinger::TRACK_FAST) {
4367 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4368 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4369 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004370 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004371 // FIXME This is too eager. We allocate a fast track index before the
4372 // fast track becomes active. Since fast tracks are a scarce resource,
4373 // this means we are potentially denying other more important fast tracks from
4374 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004375 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004376 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004377 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004378 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004379 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004380 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004381 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004382 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004383}
4384
4385AudioFlinger::PlaybackThread::Track::~Track()
4386{
Steve Block3856b092011-10-20 11:56:00 +01004387 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004388}
4389
4390void AudioFlinger::PlaybackThread::Track::destroy()
4391{
4392 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4393 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004394 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004395 // we must acquire a strong reference on this Track before locking mLock
4396 // here so that the destructor is called only when exiting this function.
4397 // On the other hand, as long as Track::destroy() is only called by
4398 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4399 // this Track with its member mTrack.
4400 sp<Track> keep(this);
4401 { // scope for mLock
4402 sp<ThreadBase> thread = mThread.promote();
4403 if (thread != 0) {
4404 if (!isOutputTrack()) {
4405 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004406 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004407
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004408#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004409 // to track the speaker usage
4410 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004411#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004412 }
4413 AudioSystem::releaseOutput(thread->id());
4414 }
4415 Mutex::Autolock _l(thread->mLock);
4416 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4417 playbackThread->destroyTrack_l(this);
4418 }
4419 }
4420}
4421
Glenn Kasten288ed212012-04-25 17:52:27 -07004422/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4423{
Glenn Kastene213c862012-04-25 13:46:15 -07004424 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 -07004425 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004426}
4427
Mathias Agopian65ab4712010-07-14 17:59:35 -07004428void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4429{
Glenn Kasten83d86532012-01-17 14:39:34 -08004430 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004431 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004432 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004433 } else {
4434 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4435 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004436 track_state state = mState;
4437 char stateChar;
4438 switch (state) {
4439 case IDLE:
4440 stateChar = 'I';
4441 break;
4442 case TERMINATED:
4443 stateChar = 'T';
4444 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004445 case STOPPING_1:
4446 stateChar = 's';
4447 break;
4448 case STOPPING_2:
4449 stateChar = '5';
4450 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004451 case STOPPED:
4452 stateChar = 'S';
4453 break;
4454 case RESUMING:
4455 stateChar = 'R';
4456 break;
4457 case ACTIVE:
4458 stateChar = 'A';
4459 break;
4460 case PAUSING:
4461 stateChar = 'p';
4462 break;
4463 case PAUSED:
4464 stateChar = 'P';
4465 break;
Eric Laurent29864602012-05-08 18:57:51 -07004466 case FLUSHED:
4467 stateChar = 'F';
4468 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004469 default:
4470 stateChar = '?';
4471 break;
4472 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004473 char nowInUnderrun;
4474 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4475 case UNDERRUN_FULL:
4476 nowInUnderrun = ' ';
4477 break;
4478 case UNDERRUN_PARTIAL:
4479 nowInUnderrun = '<';
4480 break;
4481 case UNDERRUN_EMPTY:
4482 nowInUnderrun = '*';
4483 break;
4484 default:
4485 nowInUnderrun = '?';
4486 break;
4487 }
Glenn Kastene213c862012-04-25 13:46:15 -07004488 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4489 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004490 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004491 mStreamType,
4492 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004493 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004494 mSessionId,
4495 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004496 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004497 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004498 mMute,
4499 mFillingUpStatus,
4500 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004501 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4502 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004503 mCblk->server,
4504 mCblk->user,
4505 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004506 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004507 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004508 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004509 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004510}
4511
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004512// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004513status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004514 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004515{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004516 audio_track_cblk_t* cblk = this->cblk();
4517 uint32_t framesReady;
4518 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004519
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004520 // Check if last stepServer failed, try to step now
4521 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004522 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4523 // Since the fast mixer is higher priority than client callback thread,
4524 // it does not result in priority inversion for client.
4525 // But a non-blocking solution would be preferable to avoid
4526 // fast mixer being unable to tryLock(), and
4527 // to avoid the extra context switches if the client wakes up,
4528 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004529 if (!step()) goto getNextBuffer_exit;
4530 ALOGV("stepServer recovered");
4531 mStepServerFailed = false;
4532 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004533
Glenn Kasten288ed212012-04-25 17:52:27 -07004534 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004535 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004536
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004537 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004538 uint32_t s = cblk->server;
4539 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4540
4541 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4542 if (framesReq > framesReady) {
4543 framesReq = framesReady;
4544 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004545 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004546 framesReq = bufferEnd - s;
4547 }
4548
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004549 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004550 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004551 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004552 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004553
4554getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004555 buffer->raw = NULL;
4556 buffer->frameCount = 0;
4557 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4558 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004559}
4560
Glenn Kasten288ed212012-04-25 17:52:27 -07004561// Note that framesReady() takes a mutex on the control block using tryLock().
4562// This could result in priority inversion if framesReady() is called by the normal mixer,
4563// as the normal mixer thread runs at lower
4564// priority than the client's callback thread: there is a short window within framesReady()
4565// during which the normal mixer could be preempted, and the client callback would block.
4566// Another problem can occur if framesReady() is called by the fast mixer:
4567// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4568// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4569size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004570 return mCblk->framesReady();
4571}
4572
Glenn Kasten288ed212012-04-25 17:52:27 -07004573// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004574bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004575 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004576
John Grossman4ff14ba2012-02-08 16:37:41 -08004577 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004578 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4579 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004580 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004581 return true;
4582 }
4583 return false;
4584}
4585
Glenn Kasten3acbd052012-02-28 10:39:56 -08004586status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004587 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004588{
4589 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004590 ALOGV("start(%d), calling pid %d session %d",
4591 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004592
Mathias Agopian65ab4712010-07-14 17:59:35 -07004593 sp<ThreadBase> thread = mThread.promote();
4594 if (thread != 0) {
4595 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004596 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004597 // here the track could be either new, or restarted
4598 // in both cases "unstop" the track
4599 if (mState == PAUSED) {
4600 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004601 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004602 } else {
4603 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004604 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004605 }
4606
4607 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4608 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004609 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004610 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004611
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004612#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004613 // to track the speaker usage
4614 if (status == NO_ERROR) {
4615 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4616 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004617#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004618 }
4619 if (status == NO_ERROR) {
4620 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4621 playbackThread->addTrack_l(this);
4622 } else {
4623 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004624 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004625 }
4626 } else {
4627 status = BAD_VALUE;
4628 }
4629 return status;
4630}
4631
4632void AudioFlinger::PlaybackThread::Track::stop()
4633{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004634 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004635 sp<ThreadBase> thread = mThread.promote();
4636 if (thread != 0) {
4637 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004638 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004639 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004640 // If the track is not active (PAUSED and buffers full), flush buffers
4641 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4642 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4643 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004644 mState = STOPPED;
4645 } else if (!isFastTrack()) {
4646 mState = STOPPED;
4647 } else {
4648 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4649 // and then to STOPPED and reset() when presentation is complete
4650 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004651 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004652 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004653 }
4654 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4655 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004656 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004657 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004658
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004659#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004660 // to track the speaker usage
4661 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004662#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004663 }
4664 }
4665}
4666
4667void AudioFlinger::PlaybackThread::Track::pause()
4668{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004669 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004670 sp<ThreadBase> thread = mThread.promote();
4671 if (thread != 0) {
4672 Mutex::Autolock _l(thread->mLock);
4673 if (mState == ACTIVE || mState == RESUMING) {
4674 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004675 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004676 if (!isOutputTrack()) {
4677 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004678 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004679 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004680
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004681#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004682 // to track the speaker usage
4683 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004684#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004685 }
4686 }
4687 }
4688}
4689
4690void AudioFlinger::PlaybackThread::Track::flush()
4691{
Steve Block3856b092011-10-20 11:56:00 +01004692 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004693 sp<ThreadBase> thread = mThread.promote();
4694 if (thread != 0) {
4695 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004696 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4697 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004698 return;
4699 }
4700 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004701 // FLUSHED state
4702 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004703 // do not reset the track if it is still in the process of being stopped or paused.
4704 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004705 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004706 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004707 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4708 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4709 reset();
4710 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004711 }
4712}
4713
4714void AudioFlinger::PlaybackThread::Track::reset()
4715{
4716 // Do not reset twice to avoid discarding data written just after a flush and before
4717 // the audioflinger thread detects the track is stopped.
4718 if (!mResetDone) {
4719 TrackBase::reset();
4720 // Force underrun condition to avoid false underrun callback until first data is
4721 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004722 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4723 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004724 mFillingUpStatus = FS_FILLING;
4725 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004726 if (mState == FLUSHED) {
4727 mState = IDLE;
4728 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004729 }
4730}
4731
4732void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4733{
4734 mMute = muted;
4735}
4736
Mathias Agopian65ab4712010-07-14 17:59:35 -07004737status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4738{
4739 status_t status = DEAD_OBJECT;
4740 sp<ThreadBase> thread = mThread.promote();
4741 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004742 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004743 sp<AudioFlinger> af = mClient->audioFlinger();
4744
4745 Mutex::Autolock _l(af->mLock);
4746
4747 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004748
Eric Laurent109347d2012-07-02 12:31:03 -07004749 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004750 Mutex::Autolock _dl(playbackThread->mLock);
4751 Mutex::Autolock _sl(srcThread->mLock);
4752 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4753 if (chain == 0) {
4754 return INVALID_OPERATION;
4755 }
4756
4757 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4758 if (effect == 0) {
4759 return INVALID_OPERATION;
4760 }
4761 srcThread->removeEffect_l(effect);
4762 playbackThread->addEffect_l(effect);
4763 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4764 if (effect->state() == EffectModule::ACTIVE ||
4765 effect->state() == EffectModule::STOPPING) {
4766 effect->start();
4767 }
4768
4769 sp<EffectChain> dstChain = effect->chain().promote();
4770 if (dstChain == 0) {
4771 srcThread->addEffect_l(effect);
4772 return INVALID_OPERATION;
4773 }
4774 AudioSystem::unregisterEffect(effect->id());
4775 AudioSystem::registerEffect(&effect->desc(),
4776 srcThread->id(),
4777 dstChain->strategy(),
4778 AUDIO_SESSION_OUTPUT_MIX,
4779 effect->id());
4780 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004781 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004782 }
4783 return status;
4784}
4785
4786void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4787{
4788 mAuxEffectId = EffectId;
4789 mAuxBuffer = buffer;
4790}
4791
Eric Laurenta011e352012-03-29 15:51:43 -07004792bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4793 size_t audioHalFrames)
4794{
4795 // a track is considered presented when the total number of frames written to audio HAL
4796 // corresponds to the number of frames written when presentationComplete() is called for the
4797 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4798 if (mPresentationCompleteFrames == 0) {
4799 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4800 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4801 mPresentationCompleteFrames, audioHalFrames);
4802 }
4803 if (framesWritten >= mPresentationCompleteFrames) {
4804 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4805 mSessionId, framesWritten);
4806 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004807 return true;
4808 }
4809 return false;
4810}
4811
4812void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4813{
4814 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4815 if (mSyncEvents[i]->type() == type) {
4816 mSyncEvents[i]->trigger();
4817 mSyncEvents.removeAt(i);
4818 i--;
4819 }
4820 }
4821}
4822
Glenn Kasten58912562012-04-03 10:45:00 -07004823// implement VolumeBufferProvider interface
4824
4825uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4826{
4827 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4828 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4829 uint32_t vlr = mCblk->getVolumeLR();
4830 uint32_t vl = vlr & 0xFFFF;
4831 uint32_t vr = vlr >> 16;
4832 // track volumes come from shared memory, so can't be trusted and must be clamped
4833 if (vl > MAX_GAIN_INT) {
4834 vl = MAX_GAIN_INT;
4835 }
4836 if (vr > MAX_GAIN_INT) {
4837 vr = MAX_GAIN_INT;
4838 }
4839 // now apply the cached master volume and stream type volume;
4840 // this is trusted but lacks any synchronization or barrier so may be stale
4841 float v = mCachedVolume;
4842 vl *= v;
4843 vr *= v;
4844 // re-combine into U4.16
4845 vlr = (vr << 16) | (vl & 0xFFFF);
4846 // FIXME look at mute, pause, and stop flags
4847 return vlr;
4848}
Eric Laurenta011e352012-03-29 15:51:43 -07004849
Eric Laurent29864602012-05-08 18:57:51 -07004850status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4851{
4852 if (mState == TERMINATED || mState == PAUSED ||
4853 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4854 (mState == STOPPED)))) {
4855 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4856 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4857 event->cancel();
4858 return INVALID_OPERATION;
4859 }
Glenn Kastend23eedc2012-08-02 13:35:47 -07004860 (void) TrackBase::setSyncEvent(event);
Eric Laurent29864602012-05-08 18:57:51 -07004861 return NO_ERROR;
4862}
4863
John Grossman4ff14ba2012-02-08 16:37:41 -08004864// timed audio tracks
4865
4866sp<AudioFlinger::PlaybackThread::TimedTrack>
4867AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004868 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004869 const sp<Client>& client,
4870 audio_stream_type_t streamType,
4871 uint32_t sampleRate,
4872 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004873 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004874 int frameCount,
4875 const sp<IMemory>& sharedBuffer,
4876 int sessionId) {
4877 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004878 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004879
Glenn Kastena0356762012-03-19 10:38:51 -07004880 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004881 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4882 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004883}
4884
4885AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004886 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004887 const sp<Client>& client,
4888 audio_stream_type_t streamType,
4889 uint32_t sampleRate,
4890 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004891 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004892 int frameCount,
4893 const sp<IMemory>& sharedBuffer,
4894 int sessionId)
4895 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004896 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004897 mQueueHeadInFlight(false),
4898 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004899 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004900 mTimedSilenceBuffer(NULL),
4901 mTimedSilenceBufferSize(0),
4902 mTimedAudioOutputOnTime(false),
4903 mMediaTimeTransformValid(false)
4904{
4905 LocalClock lc;
4906 mLocalTimeFreq = lc.getLocalFreq();
4907
4908 mLocalTimeToSampleTransform.a_zero = 0;
4909 mLocalTimeToSampleTransform.b_zero = 0;
4910 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4911 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4912 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4913 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004914
4915 mMediaTimeToSampleTransform.a_zero = 0;
4916 mMediaTimeToSampleTransform.b_zero = 0;
4917 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4918 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4919 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4920 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004921}
4922
4923AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4924 mClient->releaseTimedTrack();
4925 delete [] mTimedSilenceBuffer;
4926}
4927
4928status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4929 size_t size, sp<IMemory>* buffer) {
4930
4931 Mutex::Autolock _l(mTimedBufferQueueLock);
4932
4933 trimTimedBufferQueue_l();
4934
4935 // lazily initialize the shared memory heap for timed buffers
4936 if (mTimedMemoryDealer == NULL) {
4937 const int kTimedBufferHeapSize = 512 << 10;
4938
4939 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4940 "AudioFlingerTimed");
4941 if (mTimedMemoryDealer == NULL)
4942 return NO_MEMORY;
4943 }
4944
4945 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4946 if (newBuffer == NULL) {
4947 newBuffer = mTimedMemoryDealer->allocate(size);
4948 if (newBuffer == NULL)
4949 return NO_MEMORY;
4950 }
4951
4952 *buffer = newBuffer;
4953 return NO_ERROR;
4954}
4955
4956// caller must hold mTimedBufferQueueLock
4957void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4958 int64_t mediaTimeNow;
4959 {
4960 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4961 if (!mMediaTimeTransformValid)
4962 return;
4963
4964 int64_t targetTimeNow;
4965 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4966 ? mCCHelper.getCommonTime(&targetTimeNow)
4967 : mCCHelper.getLocalTime(&targetTimeNow);
4968
4969 if (OK != res)
4970 return;
4971
4972 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4973 &mediaTimeNow)) {
4974 return;
4975 }
4976 }
4977
John Grossman1c345192012-03-27 14:00:17 -07004978 size_t trimEnd;
4979 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004980 int64_t bufEnd;
4981
John Grossmanc95cfbb2012-04-12 11:53:11 -07004982 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4983 // We have a next buffer. Just use its PTS as the PTS of the frame
4984 // following the last frame in this buffer. If the stream is sparse
4985 // (ie, there are deliberate gaps left in the stream which should be
4986 // filled with silence by the TimedAudioTrack), then this can result
4987 // in one extra buffer being left un-trimmed when it could have
4988 // been. In general, this is not typical, and we would rather
4989 // optimized away the TS calculation below for the more common case
4990 // where PTSes are contiguous.
4991 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4992 } else {
4993 // We have no next buffer. Compute the PTS of the frame following
4994 // the last frame in this buffer by computing the duration of of
4995 // this frame in media time units and adding it to the PTS of the
4996 // buffer.
4997 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4998 / mCblk->frameSize;
4999
5000 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
5001 &bufEnd)) {
5002 ALOGE("Failed to convert frame count of %lld to media time"
5003 " duration" " (scale factor %d/%u) in %s",
5004 frameCount,
5005 mMediaTimeToSampleTransform.a_to_b_numer,
5006 mMediaTimeToSampleTransform.a_to_b_denom,
5007 __PRETTY_FUNCTION__);
5008 break;
5009 }
5010 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07005011 }
John Grossman9fbdee12012-03-26 17:51:46 -07005012
5013 if (bufEnd > mediaTimeNow)
5014 break;
5015
5016 // Is the buffer we want to use in the middle of a mix operation right
5017 // now? If so, don't actually trim it. Just wait for the releaseBuffer
5018 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07005019 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07005020 mTrimQueueHeadOnRelease = true;
5021 }
John Grossman4ff14ba2012-02-08 16:37:41 -08005022 }
5023
John Grossman9fbdee12012-03-26 17:51:46 -07005024 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07005025 if (trimStart < trimEnd) {
5026 // Update the bookkeeping for framesReady()
5027 for (size_t i = trimStart; i < trimEnd; ++i) {
5028 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
5029 }
5030
5031 // Now actually remove the buffers from the queue.
5032 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08005033 }
5034}
5035
John Grossman1c345192012-03-27 14:00:17 -07005036void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
5037 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07005038 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
5039 "%s called (reason \"%s\"), but timed buffer queue has no"
5040 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005041
5042 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
5043 mTimedBufferQueue.removeAt(0);
5044}
5045
5046void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
5047 const TimedBuffer& buf,
5048 const char* logTag) {
5049 uint32_t bufBytes = buf.buffer()->size();
5050 uint32_t consumedAlready = buf.position();
5051
Eric Laurentb388e532012-04-14 13:32:48 -07005052 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07005053 "Bad bookkeeping while updating frames pending. Timed buffer is"
5054 " only %u bytes long, but claims to have consumed %u"
5055 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07005056 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005057
5058 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07005059 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5060 "Bad bookkeeping while updating frames pending. Should have at"
5061 " least %u queued frames, but we think we have only %u. (update"
5062 " reason: \"%s\")",
5063 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005064
5065 mFramesPendingInQueue -= bufFrames;
5066}
5067
John Grossman4ff14ba2012-02-08 16:37:41 -08005068status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5069 const sp<IMemory>& buffer, int64_t pts) {
5070
5071 {
5072 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5073 if (!mMediaTimeTransformValid)
5074 return INVALID_OPERATION;
5075 }
5076
5077 Mutex::Autolock _l(mTimedBufferQueueLock);
5078
John Grossman1c345192012-03-27 14:00:17 -07005079 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5080 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005081 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5082
5083 return NO_ERROR;
5084}
5085
5086status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5087 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5088
John Grossman1c345192012-03-27 14:00:17 -07005089 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5090 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5091 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005092
5093 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5094 target == TimedAudioTrack::COMMON_TIME)) {
5095 return BAD_VALUE;
5096 }
5097
5098 Mutex::Autolock lock(mMediaTimeTransformLock);
5099 mMediaTimeTransform = xform;
5100 mMediaTimeTransformTarget = target;
5101 mMediaTimeTransformValid = true;
5102
5103 return NO_ERROR;
5104}
5105
5106#define min(a, b) ((a) < (b) ? (a) : (b))
5107
5108// implementation of getNextBuffer for tracks whose buffers have timestamps
5109status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5110 AudioBufferProvider::Buffer* buffer, int64_t pts)
5111{
5112 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005113 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005114 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005115 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005116 return INVALID_OPERATION;
5117 }
5118
John Grossman4ff14ba2012-02-08 16:37:41 -08005119 Mutex::Autolock _l(mTimedBufferQueueLock);
5120
John Grossman9fbdee12012-03-26 17:51:46 -07005121 ALOG_ASSERT(!mQueueHeadInFlight,
5122 "getNextBuffer called without releaseBuffer!");
5123
John Grossman4ff14ba2012-02-08 16:37:41 -08005124 while (true) {
5125
5126 // if we have no timed buffers, then fail
5127 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005128 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005129 buffer->frameCount = 0;
5130 return NOT_ENOUGH_DATA;
5131 }
5132
5133 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5134
5135 // calculate the PTS of the head of the timed buffer queue expressed in
5136 // local time
5137 int64_t headLocalPTS;
5138 {
5139 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5140
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005141 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005142
5143 if (mMediaTimeTransform.a_to_b_denom == 0) {
5144 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005145 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005146 return NO_ERROR;
5147 }
5148
5149 int64_t transformedPTS;
5150 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5151 &transformedPTS)) {
5152 // the transform failed. this shouldn't happen, but if it does
5153 // then just drop this buffer
5154 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005155 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005156 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005157 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005158 return NO_ERROR;
5159 }
5160
5161 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5162 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5163 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005164 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005165 buffer->frameCount = 0;
5166 return INVALID_OPERATION;
5167 }
5168 } else {
5169 headLocalPTS = transformedPTS;
5170 }
5171 }
5172
5173 // adjust the head buffer's PTS to reflect the portion of the head buffer
5174 // that has already been consumed
5175 int64_t effectivePTS = headLocalPTS +
5176 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5177
5178 // Calculate the delta in samples between the head of the input buffer
5179 // queue and the start of the next output buffer that will be written.
5180 // If the transformation fails because of over or underflow, it means
5181 // that the sample's position in the output stream is so far out of
5182 // whack that it should just be dropped.
5183 int64_t sampleDelta;
5184 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5185 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005186 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5187 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005188 continue;
5189 }
5190 if (!mLocalTimeToSampleTransform.doForwardTransform(
5191 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005192 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005193 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005194 continue;
5195 }
5196
John Grossman1c345192012-03-27 14:00:17 -07005197 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5198 " sampleDelta=[%d.%08x]",
5199 head.pts(), head.position(), pts,
5200 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5201 + (sampleDelta >> 32)),
5202 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005203
5204 // if the delta between the ideal placement for the next input sample and
5205 // the current output position is within this threshold, then we will
5206 // concatenate the next input samples to the previous output
5207 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005208 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005209
5210 // if this is the first buffer of audio that we're emitting from this track
5211 // then it should be almost exactly on time.
5212 const int64_t kSampleStartupThreshold = 1LL << 32;
5213
5214 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005215 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005216 // the next input is close enough to being on time, so concatenate it
5217 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005218 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005219
John Grossman1c345192012-03-27 14:00:17 -07005220 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5221 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005222 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005223 }
5224
5225 // Looks like our output is not on time. Reset our on timed status.
5226 // Next time we mix samples from our input queue, then should be within
5227 // the StartupThreshold.
5228 mTimedAudioOutputOnTime = false;
5229 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005230 // the gap between the current output position and the proper start of
5231 // the next input sample is too big, so fill it with silence
5232 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5233
John Grossman9fbdee12012-03-26 17:51:46 -07005234 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005235 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5236 return NO_ERROR;
5237 } else {
5238 // the next input sample is late
5239 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5240 size_t onTimeSamplePosition =
5241 head.position() + lateFrames * mCblk->frameSize;
5242
5243 if (onTimeSamplePosition > head.buffer()->size()) {
5244 // all the remaining samples in the head are too late, so
5245 // drop it and move on
5246 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005247 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005248 continue;
5249 } else {
5250 // skip over the late samples
5251 head.setPosition(onTimeSamplePosition);
5252
5253 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005254 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005255
5256 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5257 return NO_ERROR;
5258 }
5259 }
5260 }
5261}
5262
5263// Yield samples from the timed buffer queue head up to the given output
5264// buffer's capacity.
5265//
5266// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005267void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005268 AudioBufferProvider::Buffer* buffer) {
5269
5270 const TimedBuffer& head = mTimedBufferQueue[0];
5271
5272 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5273 head.position());
5274
5275 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5276 mCblk->frameSize);
5277 size_t framesRequested = buffer->frameCount;
5278 buffer->frameCount = min(framesLeftInHead, framesRequested);
5279
John Grossman9fbdee12012-03-26 17:51:46 -07005280 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005281 mTimedAudioOutputOnTime = true;
5282}
5283
5284// Yield samples of silence up to the given output buffer's capacity
5285//
5286// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005287void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005288 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5289
5290 // lazily allocate a buffer filled with silence
5291 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5292 delete [] mTimedSilenceBuffer;
5293 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5294 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5295 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5296 }
5297
5298 buffer->raw = mTimedSilenceBuffer;
5299 size_t framesRequested = buffer->frameCount;
5300 buffer->frameCount = min(numFrames, framesRequested);
5301
5302 mTimedAudioOutputOnTime = false;
5303}
5304
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005305// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005306void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5307 AudioBufferProvider::Buffer* buffer) {
5308
5309 Mutex::Autolock _l(mTimedBufferQueueLock);
5310
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005311 // If the buffer which was just released is part of the buffer at the head
5312 // of the queue, be sure to update the amt of the buffer which has been
5313 // consumed. If the buffer being returned is not part of the head of the
5314 // queue, its either because the buffer is part of the silence buffer, or
5315 // because the head of the timed queue was trimmed after the mixer called
5316 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005317 if (buffer->raw == mTimedSilenceBuffer) {
5318 ALOG_ASSERT(!mQueueHeadInFlight,
5319 "Queue head in flight during release of silence buffer!");
5320 goto done;
5321 }
5322
5323 ALOG_ASSERT(mQueueHeadInFlight,
5324 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5325 " head in flight.");
5326
5327 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005328 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005329
5330 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005331 void* end = reinterpret_cast<void*>(
5332 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5333 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005334
John Grossman9fbdee12012-03-26 17:51:46 -07005335 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5336 "released buffer not within the head of the timed buffer"
5337 " queue; qHead = [%p, %p], released buffer = %p",
5338 start, end, buffer->raw);
5339
5340 head.setPosition(head.position() +
5341 (buffer->frameCount * mCblk->frameSize));
5342 mQueueHeadInFlight = false;
5343
John Grossman1c345192012-03-27 14:00:17 -07005344 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5345 "Bad bookkeeping during releaseBuffer! Should have at"
5346 " least %u queued frames, but we think we have only %u",
5347 buffer->frameCount, mFramesPendingInQueue);
5348
5349 mFramesPendingInQueue -= buffer->frameCount;
5350
John Grossman9fbdee12012-03-26 17:51:46 -07005351 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5352 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005353 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005354 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005355 }
John Grossman9fbdee12012-03-26 17:51:46 -07005356 } else {
5357 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5358 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005359 }
5360
John Grossman9fbdee12012-03-26 17:51:46 -07005361done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005362 buffer->raw = 0;
5363 buffer->frameCount = 0;
5364}
5365
Glenn Kasten288ed212012-04-25 17:52:27 -07005366size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005367 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005368 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005369}
5370
5371AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5372 : mPTS(0), mPosition(0) {}
5373
5374AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5375 const sp<IMemory>& buffer, int64_t pts)
5376 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5377
Mathias Agopian65ab4712010-07-14 17:59:35 -07005378// ----------------------------------------------------------------------------
5379
5380// RecordTrack constructor must be called with AudioFlinger::mLock held
5381AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005382 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005383 const sp<Client>& client,
5384 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005385 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005386 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005387 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005388 int sessionId)
5389 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005390 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005391 mOverflow(false)
5392{
5393 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005394 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5395 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5396 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5397 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5398 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5399 } else {
5400 mCblk->frameSize = sizeof(int8_t);
5401 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005402 }
5403}
5404
5405AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5406{
Glenn Kasten510a3d62012-07-16 14:24:34 -07005407 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005408}
5409
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005410// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005411status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005412{
5413 audio_track_cblk_t* cblk = this->cblk();
5414 uint32_t framesAvail;
5415 uint32_t framesReq = buffer->frameCount;
5416
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005417 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005418 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005419 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005420 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005421 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005422 }
5423
5424 framesAvail = cblk->framesAvailable_l();
5425
Glenn Kastenf6b16782011-12-15 09:51:17 -08005426 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005427 uint32_t s = cblk->server;
5428 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5429
5430 if (framesReq > framesAvail) {
5431 framesReq = framesAvail;
5432 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005433 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005434 framesReq = bufferEnd - s;
5435 }
5436
5437 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005438 buffer->frameCount = framesReq;
5439 return NO_ERROR;
5440 }
5441
5442getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005443 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005444 buffer->frameCount = 0;
5445 return NOT_ENOUGH_DATA;
5446}
5447
Glenn Kasten3acbd052012-02-28 10:39:56 -08005448status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005449 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005450{
5451 sp<ThreadBase> thread = mThread.promote();
5452 if (thread != 0) {
5453 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005454 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005455 } else {
5456 return BAD_VALUE;
5457 }
5458}
5459
5460void AudioFlinger::RecordThread::RecordTrack::stop()
5461{
5462 sp<ThreadBase> thread = mThread.promote();
5463 if (thread != 0) {
5464 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005465 recordThread->mLock.lock();
5466 bool doStop = recordThread->stop_l(this);
5467 if (doStop) {
5468 TrackBase::reset();
5469 // Force overrun condition to avoid false overrun callback until first data is
5470 // read from buffer
5471 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5472 }
5473 recordThread->mLock.unlock();
5474 if (doStop) {
5475 AudioSystem::stopInput(recordThread->id());
5476 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005477 }
5478}
5479
Glenn Kasten510a3d62012-07-16 14:24:34 -07005480/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
5481{
Jean-Michel Trivi60736462012-09-12 18:48:33 -07005482 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User FrameCount\n");
Glenn Kasten510a3d62012-07-16 14:24:34 -07005483}
5484
Mathias Agopian65ab4712010-07-14 17:59:35 -07005485void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5486{
Jean-Michel Trivi60736462012-09-12 18:48:33 -07005487 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x %05d\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005488 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005489 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005490 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005491 mSessionId,
5492 mFrameCount,
5493 mState,
5494 mCblk->sampleRate,
5495 mCblk->server,
Jean-Michel Trivi60736462012-09-12 18:48:33 -07005496 mCblk->user,
5497 mCblk->frameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005498}
5499
5500
5501// ----------------------------------------------------------------------------
5502
5503AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005504 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005505 DuplicatingThread *sourceThread,
5506 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005507 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005508 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005509 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005510 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5511 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005512 mActive(false), mSourceThread(sourceThread)
5513{
5514
Mathias Agopian65ab4712010-07-14 17:59:35 -07005515 if (mCblk != NULL) {
5516 mCblk->flags |= CBLK_DIRECTION_OUT;
5517 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005518 mOutBuffer.frameCount = 0;
5519 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005520 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005521 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5522 mCblk, mBuffer, mCblk->buffers,
5523 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005524 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005525 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005526 }
5527}
5528
5529AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5530{
5531 clearBufferQueue();
5532}
5533
Glenn Kasten3acbd052012-02-28 10:39:56 -08005534status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005535 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005536{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005537 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005538 if (status != NO_ERROR) {
5539 return status;
5540 }
5541
5542 mActive = true;
5543 mRetryCount = 127;
5544 return status;
5545}
5546
5547void AudioFlinger::PlaybackThread::OutputTrack::stop()
5548{
5549 Track::stop();
5550 clearBufferQueue();
5551 mOutBuffer.frameCount = 0;
5552 mActive = false;
5553}
5554
5555bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5556{
5557 Buffer *pInBuffer;
5558 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005559 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005560 bool outputBufferFull = false;
5561 inBuffer.frameCount = frames;
5562 inBuffer.i16 = data;
5563
5564 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5565
5566 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005567 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005568 sp<ThreadBase> thread = mThread.promote();
5569 if (thread != 0) {
5570 MixerThread *mixerThread = (MixerThread *)thread.get();
5571 if (mCblk->frameCount > frames){
5572 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5573 uint32_t startFrames = (mCblk->frameCount - frames);
5574 pInBuffer = new Buffer;
5575 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5576 pInBuffer->frameCount = startFrames;
5577 pInBuffer->i16 = pInBuffer->mBuffer;
5578 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5579 mBufferQueue.add(pInBuffer);
5580 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005581 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005582 }
5583 }
5584 }
5585 }
5586
5587 while (waitTimeLeftMs) {
5588 // First write pending buffers, then new data
5589 if (mBufferQueue.size()) {
5590 pInBuffer = mBufferQueue.itemAt(0);
5591 } else {
5592 pInBuffer = &inBuffer;
5593 }
5594
5595 if (pInBuffer->frameCount == 0) {
5596 break;
5597 }
5598
5599 if (mOutBuffer.frameCount == 0) {
5600 mOutBuffer.frameCount = pInBuffer->frameCount;
5601 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005602 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005603 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005604 outputBufferFull = true;
5605 break;
5606 }
5607 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5608 if (waitTimeLeftMs >= waitTimeMs) {
5609 waitTimeLeftMs -= waitTimeMs;
5610 } else {
5611 waitTimeLeftMs = 0;
5612 }
5613 }
5614
5615 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5616 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5617 mCblk->stepUser(outFrames);
5618 pInBuffer->frameCount -= outFrames;
5619 pInBuffer->i16 += outFrames * channelCount;
5620 mOutBuffer.frameCount -= outFrames;
5621 mOutBuffer.i16 += outFrames * channelCount;
5622
5623 if (pInBuffer->frameCount == 0) {
5624 if (mBufferQueue.size()) {
5625 mBufferQueue.removeAt(0);
5626 delete [] pInBuffer->mBuffer;
5627 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005628 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005629 } else {
5630 break;
5631 }
5632 }
5633 }
5634
5635 // If we could not write all frames, allocate a buffer and queue it for next time.
5636 if (inBuffer.frameCount) {
5637 sp<ThreadBase> thread = mThread.promote();
5638 if (thread != 0 && !thread->standby()) {
5639 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5640 pInBuffer = new Buffer;
5641 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5642 pInBuffer->frameCount = inBuffer.frameCount;
5643 pInBuffer->i16 = pInBuffer->mBuffer;
5644 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5645 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005646 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005647 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005648 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005649 }
5650 }
5651 }
5652
5653 // Calling write() with a 0 length buffer, means that no more data will be written:
5654 // If no more buffers are pending, fill output track buffer to make sure it is started
5655 // by output mixer.
5656 if (frames == 0 && mBufferQueue.size() == 0) {
5657 if (mCblk->user < mCblk->frameCount) {
5658 frames = mCblk->frameCount - mCblk->user;
5659 pInBuffer = new Buffer;
5660 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5661 pInBuffer->frameCount = frames;
5662 pInBuffer->i16 = pInBuffer->mBuffer;
5663 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5664 mBufferQueue.add(pInBuffer);
5665 } else if (mActive) {
5666 stop();
5667 }
5668 }
5669
5670 return outputBufferFull;
5671}
5672
5673status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5674{
5675 int active;
5676 status_t result;
5677 audio_track_cblk_t* cblk = mCblk;
5678 uint32_t framesReq = buffer->frameCount;
5679
Glenn Kastencbe4b362012-10-18 15:51:03 -07005680 ALOGVV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005681 buffer->frameCount = 0;
5682
5683 uint32_t framesAvail = cblk->framesAvailable();
5684
5685
5686 if (framesAvail == 0) {
5687 Mutex::Autolock _l(cblk->lock);
5688 goto start_loop_here;
5689 while (framesAvail == 0) {
5690 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005691 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005692 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005693 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005694 }
5695 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5696 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005697 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005698 }
5699 // read the server count again
5700 start_loop_here:
5701 framesAvail = cblk->framesAvailable_l();
5702 }
5703 }
5704
5705// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005706// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005707// }
5708
5709 if (framesReq > framesAvail) {
5710 framesReq = framesAvail;
5711 }
5712
5713 uint32_t u = cblk->user;
5714 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5715
Marco Nelissena1472d92012-03-30 14:36:54 -07005716 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005717 framesReq = bufferEnd - u;
5718 }
5719
5720 buffer->frameCount = framesReq;
5721 buffer->raw = (void *)cblk->buffer(u);
5722 return NO_ERROR;
5723}
5724
5725
5726void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5727{
5728 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005729
5730 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005731 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005732 delete [] pBuffer->mBuffer;
5733 delete pBuffer;
5734 }
5735 mBufferQueue.clear();
5736}
5737
5738// ----------------------------------------------------------------------------
5739
5740AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5741 : RefBase(),
5742 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005743 // 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 -07005744 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005745 mPid(pid),
5746 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005747{
5748 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5749}
5750
5751// Client destructor must be called with AudioFlinger::mLock held
5752AudioFlinger::Client::~Client()
5753{
5754 mAudioFlinger->removeClient_l(mPid);
5755}
5756
Glenn Kasten435dbe62012-01-30 10:15:48 -08005757sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005758{
5759 return mMemoryDealer;
5760}
5761
John Grossman4ff14ba2012-02-08 16:37:41 -08005762// Reserve one of the limited slots for a timed audio track associated
5763// with this client
5764bool AudioFlinger::Client::reserveTimedTrack()
5765{
5766 const int kMaxTimedTracksPerClient = 4;
5767
5768 Mutex::Autolock _l(mTimedTrackLock);
5769
5770 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5771 ALOGW("can not create timed track - pid %d has exceeded the limit",
5772 mPid);
5773 return false;
5774 }
5775
5776 mTimedTrackCount++;
5777 return true;
5778}
5779
5780// Release a slot for a timed audio track
5781void AudioFlinger::Client::releaseTimedTrack()
5782{
5783 Mutex::Autolock _l(mTimedTrackLock);
5784 mTimedTrackCount--;
5785}
5786
Mathias Agopian65ab4712010-07-14 17:59:35 -07005787// ----------------------------------------------------------------------------
5788
5789AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5790 const sp<IAudioFlingerClient>& client,
5791 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005792 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005793{
5794}
5795
5796AudioFlinger::NotificationClient::~NotificationClient()
5797{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005798}
5799
5800void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5801{
5802 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005803 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005804}
5805
5806// ----------------------------------------------------------------------------
5807
5808AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5809 : BnAudioTrack(),
5810 mTrack(track)
5811{
5812}
5813
5814AudioFlinger::TrackHandle::~TrackHandle() {
5815 // just stop the track on deletion, associated resources
5816 // will be freed from the main thread once all pending buffers have
5817 // been played. Unless it's not in the active track list, in which
5818 // case we free everything now...
5819 mTrack->destroy();
5820}
5821
Glenn Kasten90716c52012-01-26 13:40:12 -08005822sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5823 return mTrack->getCblk();
5824}
5825
Glenn Kasten3acbd052012-02-28 10:39:56 -08005826status_t AudioFlinger::TrackHandle::start() {
5827 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005828}
5829
5830void AudioFlinger::TrackHandle::stop() {
5831 mTrack->stop();
5832}
5833
5834void AudioFlinger::TrackHandle::flush() {
5835 mTrack->flush();
5836}
5837
5838void AudioFlinger::TrackHandle::mute(bool e) {
5839 mTrack->mute(e);
5840}
5841
5842void AudioFlinger::TrackHandle::pause() {
5843 mTrack->pause();
5844}
5845
Mathias Agopian65ab4712010-07-14 17:59:35 -07005846status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5847{
5848 return mTrack->attachAuxEffect(EffectId);
5849}
5850
John Grossman4ff14ba2012-02-08 16:37:41 -08005851status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5852 sp<IMemory>* buffer) {
5853 if (!mTrack->isTimedTrack())
5854 return INVALID_OPERATION;
5855
5856 PlaybackThread::TimedTrack* tt =
5857 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5858 return tt->allocateTimedBuffer(size, buffer);
5859}
5860
5861status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5862 int64_t pts) {
5863 if (!mTrack->isTimedTrack())
5864 return INVALID_OPERATION;
5865
5866 PlaybackThread::TimedTrack* tt =
5867 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5868 return tt->queueTimedBuffer(buffer, pts);
5869}
5870
5871status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5872 const LinearTransform& xform, int target) {
5873
5874 if (!mTrack->isTimedTrack())
5875 return INVALID_OPERATION;
5876
5877 PlaybackThread::TimedTrack* tt =
5878 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5879 return tt->setMediaTimeTransform(
5880 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5881}
5882
Mathias Agopian65ab4712010-07-14 17:59:35 -07005883status_t AudioFlinger::TrackHandle::onTransact(
5884 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5885{
5886 return BnAudioTrack::onTransact(code, data, reply, flags);
5887}
5888
5889// ----------------------------------------------------------------------------
5890
5891sp<IAudioRecord> AudioFlinger::openRecord(
5892 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005893 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005894 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005895 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005896 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005897 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005898 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07005899 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005900 int *sessionId,
5901 status_t *status)
5902{
5903 sp<RecordThread::RecordTrack> recordTrack;
5904 sp<RecordHandle> recordHandle;
5905 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005906 status_t lStatus;
5907 RecordThread *thread;
5908 size_t inFrameCount;
5909 int lSessionId;
5910
5911 // check calling permissions
5912 if (!recordingAllowed()) {
5913 lStatus = PERMISSION_DENIED;
5914 goto Exit;
5915 }
5916
5917 // add client to list
5918 { // scope for mLock
5919 Mutex::Autolock _l(mLock);
5920 thread = checkRecordThread_l(input);
5921 if (thread == NULL) {
5922 lStatus = BAD_VALUE;
5923 goto Exit;
5924 }
5925
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005926 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005927
5928 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005929 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005930 lSessionId = *sessionId;
5931 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005932 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005933 if (sessionId != NULL) {
5934 *sessionId = lSessionId;
5935 }
5936 }
5937 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07005938 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5939 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005940 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005941 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005942 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5943 // destructor is called by the TrackBase destructor with mLock held
5944 client.clear();
5945 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005946 goto Exit;
5947 }
5948
5949 // return to handle to client
5950 recordHandle = new RecordHandle(recordTrack);
5951 lStatus = NO_ERROR;
5952
5953Exit:
5954 if (status) {
5955 *status = lStatus;
5956 }
5957 return recordHandle;
5958}
5959
5960// ----------------------------------------------------------------------------
5961
5962AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5963 : BnAudioRecord(),
5964 mRecordTrack(recordTrack)
5965{
5966}
5967
5968AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005969 stop_nonvirtual();
Glenn Kasten510a3d62012-07-16 14:24:34 -07005970 mRecordTrack->destroy();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005971}
5972
Glenn Kasten90716c52012-01-26 13:40:12 -08005973sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5974 return mRecordTrack->getCblk();
5975}
5976
Glenn Kasten0ec23ce2012-07-10 12:56:08 -07005977status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005978 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005979 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005980}
5981
5982void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005983 stop_nonvirtual();
5984}
5985
5986void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01005987 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005988 mRecordTrack->stop();
5989}
5990
Mathias Agopian65ab4712010-07-14 17:59:35 -07005991status_t AudioFlinger::RecordHandle::onTransact(
5992 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5993{
5994 return BnAudioRecord::onTransact(code, data, reply, flags);
5995}
5996
5997// ----------------------------------------------------------------------------
5998
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005999AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6000 AudioStreamIn *input,
6001 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07006002 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006003 audio_io_handle_t id,
Glenn Kasten8c327342012-09-30 12:29:28 -07006004 audio_devices_t device,
6005 const sp<NBAIO_Sink>& teeSink) :
Eric Laurent88959252012-08-28 14:26:53 -07006006 ThreadBase(audioFlinger, id, AUDIO_DEVICE_NONE, device, RECORD),
Glenn Kasten510a3d62012-07-16 14:24:34 -07006007 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006008 // mRsmpInIndex and mInputBytes set by readInputParameters()
Glenn Kasten254af182012-07-03 14:59:05 -07006009 mReqChannelCount(popcount(channelMask)),
Glenn Kasten8c327342012-09-30 12:29:28 -07006010 mReqSampleRate(sampleRate),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006011 // mBytesRead is only meaningful while active, and so is cleared in start()
6012 // (but might be better to also clear here for dump?)
Glenn Kasten8c327342012-09-30 12:29:28 -07006013 mTeeSink(teeSink)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006014{
Glenn Kasten480b4682012-02-28 12:30:08 -08006015 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07006016
Mathias Agopian65ab4712010-07-14 17:59:35 -07006017 readInputParameters();
Glenn Kasten8c327342012-09-30 12:29:28 -07006018
Mathias Agopian65ab4712010-07-14 17:59:35 -07006019}
6020
6021
6022AudioFlinger::RecordThread::~RecordThread()
6023{
6024 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08006025 delete mResampler;
6026 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006027}
6028
6029void AudioFlinger::RecordThread::onFirstRef()
6030{
Eric Laurentfeb0db62011-07-22 09:04:31 -07006031 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006032}
6033
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006034status_t AudioFlinger::RecordThread::readyToRun()
6035{
6036 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00006037 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006038 return status;
6039}
6040
Mathias Agopian65ab4712010-07-14 17:59:35 -07006041bool AudioFlinger::RecordThread::threadLoop()
6042{
6043 AudioBufferProvider::Buffer buffer;
6044 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006045 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006046
Eric Laurent44d98482010-09-30 16:12:31 -07006047 nsecs_t lastWarning = 0;
6048
Glenn Kastene4e2a372012-07-23 12:55:09 -07006049 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07006050 acquireWakeLock();
6051
Jean-Michel Trivi89b44702012-09-13 11:44:00 -07006052 // used to verify we've read at least once before evaluating how many bytes were read
Jean-Michel Trivi60736462012-09-12 18:48:33 -07006053 bool readOnce = false;
6054
Mathias Agopian65ab4712010-07-14 17:59:35 -07006055 // start recording
6056 while (!exitPending()) {
6057
6058 processConfigEvents();
6059
6060 { // scope for mLock
6061 Mutex::Autolock _l(mLock);
6062 checkForNewParameters_l();
6063 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006064 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006065
6066 if (exitPending()) break;
6067
Eric Laurentfeb0db62011-07-22 09:04:31 -07006068 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01006069 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006070 // go to sleep
6071 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006072 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006073 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074 continue;
6075 }
6076 if (mActiveTrack != 0) {
6077 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006078 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006079 mActiveTrack.clear();
6080 mStartStopCond.broadcast();
6081 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6082 if (mReqChannelCount != mActiveTrack->channelCount()) {
6083 mActiveTrack.clear();
6084 mStartStopCond.broadcast();
Jean-Michel Trivi60736462012-09-12 18:48:33 -07006085 } else if (readOnce) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006086 // record start succeeds only if first read from audio input
6087 // succeeds
Jean-Michel Trivi60736462012-09-12 18:48:33 -07006088 if (mBytesRead >= 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006089 mActiveTrack->mState = TrackBase::ACTIVE;
6090 } else {
6091 mActiveTrack.clear();
6092 }
6093 mStartStopCond.broadcast();
6094 }
6095 mStandby = false;
Glenn Kasten510a3d62012-07-16 14:24:34 -07006096 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
6097 removeTrack_l(mActiveTrack);
6098 mActiveTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006099 }
6100 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006101 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006102 }
6103
6104 if (mActiveTrack != 0) {
6105 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6106 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006107 unlockEffectChains(effectChains);
6108 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006109 continue;
6110 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006111 for (size_t i = 0; i < effectChains.size(); i ++) {
6112 effectChains[i]->process_l();
6113 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006114
Mathias Agopian65ab4712010-07-14 17:59:35 -07006115 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006116 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Jean-Michel Trivi60736462012-09-12 18:48:33 -07006117 readOnce = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006118 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006119 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120 // no resampling
6121 while (framesOut) {
6122 size_t framesIn = mFrameCount - mRsmpInIndex;
6123 if (framesIn) {
6124 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6125 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6126 if (framesIn > framesOut)
6127 framesIn = framesOut;
6128 mRsmpInIndex += framesIn;
6129 framesOut -= framesIn;
6130 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006131 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006132 memcpy(dst, src, framesIn * mFrameSize);
6133 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006134 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006135 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6136 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006137 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006138 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6139 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006140 }
6141 }
6142 }
6143 if (framesOut && mFrameCount == mRsmpInIndex) {
Glenn Kasten8c327342012-09-30 12:29:28 -07006144 void *readInto;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006145 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006146 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Glenn Kasten8c327342012-09-30 12:29:28 -07006147 readInto = buffer.raw;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006148 framesOut = 0;
6149 } else {
Glenn Kasten8c327342012-09-30 12:29:28 -07006150 readInto = mRsmpInBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006151 mRsmpInIndex = 0;
6152 }
Glenn Kasten8c327342012-09-30 12:29:28 -07006153 mBytesRead = mInput->stream->read(mInput->stream, readInto, mInputBytes);
Jean-Michel Trivi60736462012-09-12 18:48:33 -07006154 if (mBytesRead <= 0) {
6155 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
6156 {
6157 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006158 // Force input into standby so that it tries to
6159 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006160 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006161 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006162 }
6163 mRsmpInIndex = mFrameCount;
6164 framesOut = 0;
6165 buffer.frameCount = 0;
Glenn Kasten8c327342012-09-30 12:29:28 -07006166 } else if (mTeeSink != 0) {
6167 (void) mTeeSink->write(readInto,
6168 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006169 }
6170 }
6171 }
6172 } else {
6173 // resampling
6174
6175 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6176 // alter output frame count as if we were expecting stereo samples
6177 if (mChannelCount == 1 && mReqChannelCount == 1) {
6178 framesOut >>= 1;
6179 }
Glenn Kasten2662ac92012-07-30 10:59:30 -07006180 mResampler->resample(mRsmpOutBuffer, framesOut, this /* AudioBufferProvider* */);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006181 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6182 // are 32 bit aligned which should be always true.
6183 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006184 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006185 // the resampler always outputs stereo samples: do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006186 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6187 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006188 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006189 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006190 }
6191
6192 }
Eric Laurenta011e352012-03-29 15:51:43 -07006193 if (mFramestoDrop == 0) {
6194 mActiveTrack->releaseBuffer(&buffer);
6195 } else {
6196 if (mFramestoDrop > 0) {
6197 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006198 if (mFramestoDrop <= 0) {
6199 clearSyncStartEvent();
6200 }
6201 } else {
6202 mFramestoDrop += buffer.frameCount;
6203 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6204 mSyncStartEvent->isCancelled()) {
6205 ALOGW("Synced record %s, session %d, trigger session %d",
6206 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6207 mActiveTrack->sessionId(),
6208 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6209 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006210 }
6211 }
6212 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006213 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006214 }
6215 // client isn't retrieving buffers fast enough
6216 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006217 if (!mActiveTrack->setOverflow()) {
6218 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006219 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006220 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006221 lastWarning = now;
6222 }
6223 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006224 // Release the processor for a while before asking for a new buffer.
6225 // This will give the application more chance to read from the buffer and
6226 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006227 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006228 }
6229 }
Eric Laurentec437d82011-07-26 20:54:46 -07006230 // enable changes in effect chain
6231 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006232 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006233 }
6234
Glenn Kastene4e2a372012-07-23 12:55:09 -07006235 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006236
Glenn Kasten33e6e352012-07-16 15:56:57 -07006237 {
6238 Mutex::Autolock _l(mLock);
6239 mActiveTrack.clear();
6240 mStartStopCond.broadcast();
6241 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006242
Eric Laurentfeb0db62011-07-22 09:04:31 -07006243 releaseWakeLock();
6244
Steve Block3856b092011-10-20 11:56:00 +01006245 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006246 return false;
6247}
6248
Glenn Kastene4e2a372012-07-23 12:55:09 -07006249void AudioFlinger::RecordThread::standby()
6250{
6251 if (!mStandby) {
6252 inputStandBy();
6253 mStandby = true;
6254 }
6255}
6256
6257void AudioFlinger::RecordThread::inputStandBy()
6258{
6259 mInput->stream->common.standby(&mInput->stream->common);
6260}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006261
6262sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6263 const sp<AudioFlinger::Client>& client,
6264 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006265 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006266 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006267 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006268 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006269 IAudioFlinger::track_flags_t flags,
6270 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006271 status_t *status)
6272{
6273 sp<RecordTrack> track;
6274 status_t lStatus;
6275
6276 lStatus = initCheck();
6277 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006278 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006279 goto Exit;
6280 }
6281
Glenn Kasten1879fff2012-07-11 15:36:59 -07006282 // FIXME use flags and tid similar to createTrack_l()
6283
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006284 { // scope for mLock
6285 Mutex::Autolock _l(mLock);
6286
6287 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006288 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006289
Glenn Kasten7378ca52012-01-20 13:44:40 -08006290 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006291 lStatus = NO_MEMORY;
6292 goto Exit;
6293 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006294 mTracks.add(track);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006295
Eric Laurent59bd0da2011-08-01 09:52:20 -07006296 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurent88959252012-08-28 14:26:53 -07006297 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006298 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006299 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6300 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006301 }
6302 lStatus = NO_ERROR;
6303
6304Exit:
6305 if (status) {
6306 *status = lStatus;
6307 }
6308 return track;
6309}
6310
Eric Laurenta011e352012-03-29 15:51:43 -07006311status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006312 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006313 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006314{
Glenn Kasten58912562012-04-03 10:45:00 -07006315 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006316 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006317 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006318
6319 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006320 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006321 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6322 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6323 triggerSession,
6324 recordTrack->sessionId(),
6325 syncStartEventCallback,
6326 this);
Eric Laurent29864602012-05-08 18:57:51 -07006327 // Sync event can be cancelled by the trigger session if the track is not in a
6328 // compatible state in which case we start record immediately
6329 if (mSyncStartEvent->isCancelled()) {
6330 clearSyncStartEvent();
6331 } else {
6332 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6333 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6334 }
Eric Laurenta011e352012-03-29 15:51:43 -07006335 }
6336
Mathias Agopian65ab4712010-07-14 17:59:35 -07006337 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006338 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006339 if (mActiveTrack != 0) {
6340 if (recordTrack != mActiveTrack.get()) {
6341 status = -EBUSY;
6342 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6343 mActiveTrack->mState = TrackBase::ACTIVE;
6344 }
6345 return status;
6346 }
6347
6348 recordTrack->mState = TrackBase::IDLE;
6349 mActiveTrack = recordTrack;
6350 mLock.unlock();
6351 status_t status = AudioSystem::startInput(mId);
6352 mLock.lock();
6353 if (status != NO_ERROR) {
6354 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006355 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006356 return status;
6357 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006358 mRsmpInIndex = mFrameCount;
6359 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006360 if (mResampler != NULL) {
6361 mResampler->reset();
6362 }
6363 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006364 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006365 ALOGV("Signal record thread");
Eric Laurent67d8ac32012-09-24 15:02:17 -07006366 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006367 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006368 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006369 mActiveTrack.clear();
6370 status = INVALID_OPERATION;
6371 goto startError;
6372 }
6373 mStartStopCond.wait(mLock);
6374 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006375 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006376 status = BAD_VALUE;
6377 goto startError;
6378 }
Steve Block3856b092011-10-20 11:56:00 +01006379 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006380 return status;
6381 }
6382startError:
6383 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006384 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006385 return status;
6386}
6387
Eric Laurenta011e352012-03-29 15:51:43 -07006388void AudioFlinger::RecordThread::clearSyncStartEvent()
6389{
6390 if (mSyncStartEvent != 0) {
6391 mSyncStartEvent->cancel();
6392 }
6393 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006394 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006395}
6396
6397void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6398{
6399 sp<SyncEvent> strongEvent = event.promote();
6400
6401 if (strongEvent != 0) {
6402 RecordThread *me = (RecordThread *)strongEvent->cookie();
6403 me->handleSyncStartEvent(strongEvent);
6404 }
6405}
6406
6407void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6408{
Eric Laurent29864602012-05-08 18:57:51 -07006409 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006410 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6411 // from audio HAL
6412 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006413 }
6414}
6415
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006416bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006417 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006418 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
6419 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006420 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006421 recordTrack->mState = TrackBase::PAUSING;
6422 // do not wait for mStartStopCond if exiting
6423 if (exitPending()) {
6424 return true;
6425 }
6426 mStartStopCond.wait(mLock);
6427 // if we have been restarted, recordTrack == mActiveTrack.get() here
6428 if (exitPending() || recordTrack != mActiveTrack.get()) {
6429 ALOGV("Record stopped OK");
6430 return true;
6431 }
6432 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006433}
6434
Glenn Kasten106e8a42012-08-02 13:37:12 -07006435bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07006436{
6437 return false;
6438}
6439
6440status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6441{
Glenn Kasten7f7d27e2012-08-02 16:37:07 -07006442#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 -07006443 if (!isValidSyncEvent(event)) {
6444 return BAD_VALUE;
6445 }
6446
Glenn Kasten510a3d62012-07-16 14:24:34 -07006447 int eventSession = event->triggerSession();
6448 status_t ret = NAME_NOT_FOUND;
6449
Eric Laurenta011e352012-03-29 15:51:43 -07006450 Mutex::Autolock _l(mLock);
6451
Glenn Kasten510a3d62012-07-16 14:24:34 -07006452 for (size_t i = 0; i < mTracks.size(); i++) {
6453 sp<RecordTrack> track = mTracks[i];
6454 if (eventSession == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07006455 (void) track->setSyncEvent(event);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006456 ret = NO_ERROR;
6457 }
Eric Laurenta011e352012-03-29 15:51:43 -07006458 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006459 return ret;
Glenn Kasten7f7d27e2012-08-02 16:37:07 -07006460#else
6461 return BAD_VALUE;
6462#endif
Glenn Kasten510a3d62012-07-16 14:24:34 -07006463}
6464
6465void AudioFlinger::RecordThread::RecordTrack::destroy()
6466{
6467 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
6468 sp<RecordTrack> keep(this);
6469 {
6470 sp<ThreadBase> thread = mThread.promote();
6471 if (thread != 0) {
6472 if (mState == ACTIVE || mState == RESUMING) {
6473 AudioSystem::stopInput(thread->id());
6474 }
6475 AudioSystem::releaseInput(thread->id());
6476 Mutex::Autolock _l(thread->mLock);
6477 RecordThread *recordThread = (RecordThread *) thread.get();
6478 recordThread->destroyTrack_l(this);
6479 }
6480 }
6481}
6482
6483// destroyTrack_l() must be called with ThreadBase::mLock held
6484void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6485{
6486 track->mState = TrackBase::TERMINATED;
6487 // active tracks are removed by threadLoop()
6488 if (mActiveTrack != track) {
6489 removeTrack_l(track);
6490 }
6491}
6492
6493void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6494{
6495 mTracks.remove(track);
6496 // need anything related to effects here?
Eric Laurenta011e352012-03-29 15:51:43 -07006497}
6498
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07006499void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006500{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006501 dumpInternals(fd, args);
6502 dumpTracks(fd, args);
6503 dumpEffectChains(fd, args);
6504}
6505
6506void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6507{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006508 const size_t SIZE = 256;
6509 char buffer[SIZE];
6510 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006511
6512 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6513 result.append(buffer);
6514
6515 if (mActiveTrack != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006516 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6517 result.append(buffer);
6518 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6519 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006520 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006521 result.append(buffer);
6522 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6523 result.append(buffer);
6524 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6525 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006526 } else {
Glenn Kasten510a3d62012-07-16 14:24:34 -07006527 result.append("No active record client\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006528 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006529
Mathias Agopian65ab4712010-07-14 17:59:35 -07006530 write(fd, result.string(), result.size());
6531
6532 dumpBase(fd, args);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006533}
6534
6535void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
6536{
6537 const size_t SIZE = 256;
6538 char buffer[SIZE];
6539 String8 result;
6540
6541 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
6542 result.append(buffer);
6543 RecordTrack::appendDumpHeader(result);
6544 for (size_t i = 0; i < mTracks.size(); ++i) {
6545 sp<RecordTrack> track = mTracks[i];
6546 if (track != 0) {
6547 track->dump(buffer, SIZE);
6548 result.append(buffer);
6549 }
6550 }
6551
6552 if (mActiveTrack != 0) {
6553 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
6554 result.append(buffer);
6555 RecordTrack::appendDumpHeader(result);
6556 mActiveTrack->dump(buffer, SIZE);
6557 result.append(buffer);
6558
6559 }
6560 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006561}
6562
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006563// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006564status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006565{
6566 size_t framesReq = buffer->frameCount;
6567 size_t framesReady = mFrameCount - mRsmpInIndex;
6568 int channelCount;
6569
6570 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006571 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Jean-Michel Trivi89b44702012-09-13 11:44:00 -07006572 if (mBytesRead <= 0) {
6573 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
6574 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006575 // Force input into standby so that it tries to
6576 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006577 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006578 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006579 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006580 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006581 buffer->frameCount = 0;
6582 return NOT_ENOUGH_DATA;
6583 }
6584 mRsmpInIndex = 0;
6585 framesReady = mFrameCount;
6586 }
6587
6588 if (framesReq > framesReady) {
6589 framesReq = framesReady;
6590 }
6591
6592 if (mChannelCount == 1 && mReqChannelCount == 2) {
6593 channelCount = 1;
6594 } else {
6595 channelCount = 2;
6596 }
6597 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6598 buffer->frameCount = framesReq;
6599 return NO_ERROR;
6600}
6601
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006602// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006603void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6604{
6605 mRsmpInIndex += buffer->frameCount;
6606 buffer->frameCount = 0;
6607}
6608
6609bool AudioFlinger::RecordThread::checkForNewParameters_l()
6610{
6611 bool reconfig = false;
6612
6613 while (!mNewParameters.isEmpty()) {
6614 status_t status = NO_ERROR;
6615 String8 keyValuePair = mNewParameters[0];
6616 AudioParameter param = AudioParameter(keyValuePair);
6617 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006618 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006619 int reqSamplingRate = mReqSampleRate;
6620 int reqChannelCount = mReqChannelCount;
6621
6622 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6623 reqSamplingRate = value;
6624 reconfig = true;
6625 }
6626 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006627 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006628 reconfig = true;
6629 }
6630 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006631 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006632 reconfig = true;
6633 }
6634 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6635 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006636 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006637 // if frame count is changed after track creation
6638 if (mActiveTrack != 0) {
6639 status = INVALID_OPERATION;
6640 } else {
6641 reconfig = true;
6642 }
6643 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006644 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6645 // forward device change to effects that have requested to be
6646 // aware of attached audio device.
6647 for (size_t i = 0; i < mEffectChains.size(); i++) {
6648 mEffectChains[i]->setDevice_l(value);
6649 }
Eric Laurent88959252012-08-28 14:26:53 -07006650
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006651 // store input device and output device but do not forward output device to audio HAL.
6652 // Note that status is ignored by the caller for output device
6653 // (see AudioFlinger::setParameters()
Eric Laurent88959252012-08-28 14:26:53 -07006654 if (audio_is_output_devices(value)) {
6655 mOutDevice = value;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006656 status = BAD_VALUE;
6657 } else {
Eric Laurent88959252012-08-28 14:26:53 -07006658 mInDevice = value;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006659 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kasten510a3d62012-07-16 14:24:34 -07006660 if (mTracks.size() > 0) {
Eric Laurent88959252012-08-28 14:26:53 -07006661 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6662 mAudioFlinger->btNrecIsOff();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006663 for (size_t i = 0; i < mTracks.size(); i++) {
6664 sp<RecordTrack> track = mTracks[i];
6665 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6666 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6667 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07006668 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006669 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006670 }
Eric Laurent2e9b0f22012-08-31 17:44:06 -07006671 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6672 mAudioSource != (audio_source_t)value) {
6673 // forward device change to effects that have requested to be
6674 // aware of attached audio device.
6675 for (size_t i = 0; i < mEffectChains.size(); i++) {
6676 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
6677 }
6678 mAudioSource = (audio_source_t)value;
6679 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006680 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006681 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006682 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006683 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006684 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6685 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006686 }
6687 if (reconfig) {
6688 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006689 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006690 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006691 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006692 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6693 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006694 status = NO_ERROR;
6695 }
6696 if (status == NO_ERROR) {
6697 readInputParameters();
Eric Laurentef6be0b2012-09-13 11:18:23 -07006698 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006699 }
6700 }
6701 }
6702
6703 mNewParameters.removeAt(0);
6704
6705 mParamStatus = status;
6706 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006707 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6708 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006709 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006710 }
6711 return reconfig;
6712}
6713
6714String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6715{
Dima Zavinfce7a472011-04-19 22:30:36 -07006716 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006717 String8 out_s8 = String8();
6718
6719 Mutex::Autolock _l(mLock);
6720 if (initCheck() != NO_ERROR) {
6721 return out_s8;
6722 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006723
Dima Zavin799a70e2011-04-18 16:57:27 -07006724 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006725 out_s8 = String8(s);
6726 free(s);
6727 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006728}
6729
6730void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6731 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006732 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006733
6734 switch (event) {
6735 case AudioSystem::INPUT_OPENED:
6736 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006737 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006738 desc.samplingRate = mSampleRate;
6739 desc.format = mFormat;
6740 desc.frameCount = mFrameCount;
6741 desc.latency = 0;
6742 param2 = &desc;
6743 break;
6744
6745 case AudioSystem::INPUT_CLOSED:
6746 default:
6747 break;
6748 }
6749 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6750}
6751
6752void AudioFlinger::RecordThread::readInputParameters()
6753{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006754 delete mRsmpInBuffer;
6755 // mRsmpInBuffer is always assigned a new[] below
6756 delete mRsmpOutBuffer;
6757 mRsmpOutBuffer = NULL;
6758 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006759 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006760
Dima Zavin799a70e2011-04-18 16:57:27 -07006761 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006762 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6763 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006764 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006765 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006766 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006767 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006768 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006769 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6770
Glenn Kasten53d76db2012-03-08 12:32:47 -08006771 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006772 {
6773 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006774 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6775 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006776 if (mChannelCount == 1 && mReqChannelCount == 2) {
6777 channelCount = 1;
6778 } else {
6779 channelCount = 2;
6780 }
6781 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6782 mResampler->setSampleRate(mSampleRate);
6783 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6784 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6785
6786 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6787 if (mChannelCount == 1 && mReqChannelCount == 1) {
6788 mFrameCount >>= 1;
6789 }
6790
6791 }
6792 mRsmpInIndex = mFrameCount;
6793}
6794
6795unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6796{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006797 Mutex::Autolock _l(mLock);
6798 if (initCheck() != NO_ERROR) {
6799 return 0;
6800 }
6801
Dima Zavin799a70e2011-04-18 16:57:27 -07006802 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006803}
6804
Glenn Kasten106e8a42012-08-02 13:37:12 -07006805uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006806{
6807 Mutex::Autolock _l(mLock);
6808 uint32_t result = 0;
6809 if (getEffectChain_l(sessionId) != 0) {
6810 result = EFFECT_SESSION;
6811 }
6812
Glenn Kasten510a3d62012-07-16 14:24:34 -07006813 for (size_t i = 0; i < mTracks.size(); ++i) {
6814 if (sessionId == mTracks[i]->sessionId()) {
6815 result |= TRACK_SESSION;
6816 break;
6817 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006818 }
6819
6820 return result;
6821}
6822
Glenn Kasten106e8a42012-08-02 13:37:12 -07006823KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent59bd0da2011-08-01 09:52:20 -07006824{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006825 KeyedVector<int, bool> ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006826 Mutex::Autolock _l(mLock);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006827 for (size_t j = 0; j < mTracks.size(); ++j) {
6828 sp<RecordThread::RecordTrack> track = mTracks[j];
6829 int sessionId = track->sessionId();
6830 if (ids.indexOfKey(sessionId) < 0) {
6831 ids.add(sessionId, true);
6832 }
6833 }
6834 return ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006835}
6836
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006837AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6838{
6839 Mutex::Autolock _l(mLock);
6840 AudioStreamIn *input = mInput;
6841 mInput = NULL;
6842 return input;
6843}
6844
6845// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006846audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006847{
6848 if (mInput == NULL) {
6849 return NULL;
6850 }
6851 return &mInput->stream->common;
6852}
6853
6854
Mathias Agopian65ab4712010-07-14 17:59:35 -07006855// ----------------------------------------------------------------------------
6856
Eric Laurenta4c5a552012-03-29 10:12:40 -07006857audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6858{
6859 if (!settingsAllowed()) {
6860 return 0;
6861 }
6862 Mutex::Autolock _l(mLock);
6863 return loadHwModule_l(name);
6864}
6865
6866// loadHwModule_l() must be called with AudioFlinger::mLock held
6867audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6868{
6869 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6870 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6871 ALOGW("loadHwModule() module %s already loaded", name);
6872 return mAudioHwDevs.keyAt(i);
6873 }
6874 }
6875
Eric Laurenta4c5a552012-03-29 10:12:40 -07006876 audio_hw_device_t *dev;
6877
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006878 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006879 if (rc) {
6880 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6881 return 0;
6882 }
6883
6884 mHardwareStatus = AUDIO_HW_INIT;
6885 rc = dev->init_check(dev);
6886 mHardwareStatus = AUDIO_HW_IDLE;
6887 if (rc) {
6888 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6889 return 0;
6890 }
6891
John Grossmanee578c02012-07-23 17:05:46 -07006892 // Check and cache this HAL's level of support for master mute and master
6893 // volume. If this is the first HAL opened, and it supports the get
6894 // methods, use the initial values provided by the HAL as the current
6895 // master mute and volume settings.
6896
6897 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
6898 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07006899 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07006900
6901 if (0 == mAudioHwDevs.size()) {
6902 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6903 if (NULL != dev->get_master_volume) {
6904 float mv;
6905 if (OK == dev->get_master_volume(dev, &mv)) {
6906 mMasterVolume = mv;
6907 }
6908 }
6909
6910 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
6911 if (NULL != dev->get_master_mute) {
6912 bool mm;
6913 if (OK == dev->get_master_mute(dev, &mm)) {
6914 mMasterMute = mm;
6915 }
6916 }
6917 }
6918
Eric Laurenta4c5a552012-03-29 10:12:40 -07006919 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07006920 if ((NULL != dev->set_master_volume) &&
6921 (OK == dev->set_master_volume(dev, mMasterVolume))) {
6922 flags = static_cast<AudioHwDevice::Flags>(flags |
6923 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
6924 }
6925
6926 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
6927 if ((NULL != dev->set_master_mute) &&
6928 (OK == dev->set_master_mute(dev, mMasterMute))) {
6929 flags = static_cast<AudioHwDevice::Flags>(flags |
6930 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
6931 }
6932
Eric Laurenta4c5a552012-03-29 10:12:40 -07006933 mHardwareStatus = AUDIO_HW_IDLE;
6934 }
6935
6936 audio_module_handle_t handle = nextUniqueId();
John Grossmanee578c02012-07-23 17:05:46 -07006937 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07006938
6939 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006940 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006941
6942 return handle;
6943
6944}
6945
Glenn Kasten4c6db4c2012-09-24 11:27:18 -07006946// ----------------------------------------------------------------------------
6947
6948int32_t AudioFlinger::getPrimaryOutputSamplingRate()
6949{
6950 Mutex::Autolock _l(mLock);
6951 PlaybackThread *thread = primaryPlaybackThread_l();
6952 return thread != NULL ? thread->sampleRate() : 0;
6953}
6954
6955int32_t AudioFlinger::getPrimaryOutputFrameCount()
6956{
6957 Mutex::Autolock _l(mLock);
6958 PlaybackThread *thread = primaryPlaybackThread_l();
6959 return thread != NULL ? thread->frameCountHAL() : 0;
6960}
6961
6962// ----------------------------------------------------------------------------
6963
Eric Laurenta4c5a552012-03-29 10:12:40 -07006964audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6965 audio_devices_t *pDevices,
6966 uint32_t *pSamplingRate,
6967 audio_format_t *pFormat,
6968 audio_channel_mask_t *pChannelMask,
6969 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006970 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006971{
6972 status_t status;
6973 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006974 struct audio_config config = {
6975 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6976 channel_mask: pChannelMask ? *pChannelMask : 0,
6977 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6978 };
6979 audio_stream_out_t *outStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07006980 AudioHwDevice *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006981
Eric Laurenta4c5a552012-03-29 10:12:40 -07006982 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6983 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006984 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006985 config.sample_rate,
6986 config.format,
6987 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006988 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006989
6990 if (pDevices == NULL || *pDevices == 0) {
6991 return 0;
6992 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006993
Mathias Agopian65ab4712010-07-14 17:59:35 -07006994 Mutex::Autolock _l(mLock);
6995
Eric Laurenta4c5a552012-03-29 10:12:40 -07006996 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006997 if (outHwDev == NULL)
6998 return 0;
6999
John Grossmanee578c02012-07-23 17:05:46 -07007000 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007001 audio_io_handle_t id = nextUniqueId();
7002
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007003 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007004
John Grossmanee578c02012-07-23 17:05:46 -07007005 status = hwDevHal->open_output_stream(hwDevHal,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007006 id,
7007 *pDevices,
7008 (audio_output_flags_t)flags,
7009 &config,
7010 &outStream);
7011
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007012 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01007013 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007014 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007015 config.sample_rate,
7016 config.format,
7017 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007018 status);
7019
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007020 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007021 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007022
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007023 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007024 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
7025 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007026 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007027 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007028 } else {
7029 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007030 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007031 }
7032 mPlaybackThreads.add(id, thread);
7033
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007034 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
7035 if (pFormat != NULL) *pFormat = config.format;
7036 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08007037 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007038
7039 // notify client processes of the new output creation
7040 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007041
7042 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007043 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07007044 ALOGI("Using module %d has the primary audio interface", module);
7045 mPrimaryHardwareDev = outHwDev;
7046
7047 AutoMutex lock(mHardwareLock);
7048 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -07007049 hwDevHal->set_mode(hwDevHal, mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007050 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007051 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007052 return id;
7053 }
7054
7055 return 0;
7056}
7057
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007058audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
7059 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007060{
7061 Mutex::Autolock _l(mLock);
7062 MixerThread *thread1 = checkMixerThread_l(output1);
7063 MixerThread *thread2 = checkMixerThread_l(output2);
7064
7065 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007066 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007067 return 0;
7068 }
7069
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007070 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007071 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
7072 thread->addOutputTrack(thread2);
7073 mPlaybackThreads.add(id, thread);
7074 // notify client processes of the new output creation
7075 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7076 return id;
7077}
7078
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007079status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007080{
Glenn Kastend96c5722012-04-25 13:44:49 -07007081 return closeOutput_nonvirtual(output);
7082}
7083
7084status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
7085{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007086 // keep strong reference on the playback thread so that
7087 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007088 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007089 {
7090 Mutex::Autolock _l(mLock);
7091 thread = checkPlaybackThread_l(output);
7092 if (thread == NULL) {
7093 return BAD_VALUE;
7094 }
7095
Steve Block3856b092011-10-20 11:56:00 +01007096 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007097
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007098 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007099 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007100 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007101 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
7102 dupThread->removeOutputTrack((MixerThread *)thread.get());
7103 }
7104 }
7105 }
Glenn Kastena1117922012-01-26 10:53:32 -08007106 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007107 mPlaybackThreads.removeItem(output);
7108 }
7109 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007110 // The thread entity (active unit of execution) is no longer running here,
7111 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007112
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007113 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007114 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007115 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007116 // from now on thread->mOutput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007117 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007118 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007119 }
7120 return NO_ERROR;
7121}
7122
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007123status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007124{
7125 Mutex::Autolock _l(mLock);
7126 PlaybackThread *thread = checkPlaybackThread_l(output);
7127
7128 if (thread == NULL) {
7129 return BAD_VALUE;
7130 }
7131
Steve Block3856b092011-10-20 11:56:00 +01007132 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007133 thread->suspend();
7134
7135 return NO_ERROR;
7136}
7137
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007138status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007139{
7140 Mutex::Autolock _l(mLock);
7141 PlaybackThread *thread = checkPlaybackThread_l(output);
7142
7143 if (thread == NULL) {
7144 return BAD_VALUE;
7145 }
7146
Steve Block3856b092011-10-20 11:56:00 +01007147 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007148
7149 thread->restore();
7150
7151 return NO_ERROR;
7152}
7153
Eric Laurenta4c5a552012-03-29 10:12:40 -07007154audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
7155 audio_devices_t *pDevices,
7156 uint32_t *pSamplingRate,
7157 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07007158 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007159{
7160 status_t status;
7161 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007162 struct audio_config config = {
7163 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7164 channel_mask: pChannelMask ? *pChannelMask : 0,
7165 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7166 };
7167 uint32_t reqSamplingRate = config.sample_rate;
7168 audio_format_t reqFormat = config.format;
7169 audio_channel_mask_t reqChannels = config.channel_mask;
7170 audio_stream_in_t *inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007171 AudioHwDevice *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007172
7173 if (pDevices == NULL || *pDevices == 0) {
7174 return 0;
7175 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007176
Mathias Agopian65ab4712010-07-14 17:59:35 -07007177 Mutex::Autolock _l(mLock);
7178
Eric Laurenta4c5a552012-03-29 10:12:40 -07007179 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007180 if (inHwDev == NULL)
7181 return 0;
7182
John Grossmanee578c02012-07-23 17:05:46 -07007183 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007184 audio_io_handle_t id = nextUniqueId();
7185
John Grossmanee578c02012-07-23 17:05:46 -07007186 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007187 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007188 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007189 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007190 config.sample_rate,
7191 config.format,
7192 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007193 status);
7194
7195 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7196 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7197 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007198 if (status == BAD_VALUE &&
7199 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7200 (config.sample_rate <= 2 * reqSamplingRate) &&
7201 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007202 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007203 inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007204 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007205 }
7206
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007207 if (status == NO_ERROR && inStream != NULL) {
Glenn Kasten8c327342012-09-30 12:29:28 -07007208
7209 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
7210 // or (re-)create if current Pipe is idle and does not match the new format
7211 sp<NBAIO_Sink> teeSink;
7212#ifdef TEE_SINK_INPUT_FRAMES
7213 enum {
7214 TEE_SINK_NO, // don't copy input
7215 TEE_SINK_NEW, // copy input using a new pipe
7216 TEE_SINK_OLD, // copy input using an existing pipe
7217 } kind;
7218 NBAIO_Format format = Format_from_SR_C(inStream->common.get_sample_rate(&inStream->common),
7219 popcount(inStream->common.get_channels(&inStream->common)));
7220 if (format == Format_Invalid) {
7221 kind = TEE_SINK_NO;
7222 } else if (mRecordTeeSink == 0) {
7223 kind = TEE_SINK_NEW;
7224 } else if (mRecordTeeSink->getStrongCount() != 1) {
7225 kind = TEE_SINK_NO;
7226 } else if (format == mRecordTeeSink->format()) {
7227 kind = TEE_SINK_OLD;
7228 } else {
7229 kind = TEE_SINK_NEW;
7230 }
7231 switch (kind) {
7232 case TEE_SINK_NEW: {
7233 Pipe *pipe = new Pipe(TEE_SINK_INPUT_FRAMES, format);
7234 size_t numCounterOffers = 0;
7235 const NBAIO_Format offers[1] = {format};
7236 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7237 ALOG_ASSERT(index == 0);
7238 PipeReader *pipeReader = new PipeReader(*pipe);
7239 numCounterOffers = 0;
7240 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7241 ALOG_ASSERT(index == 0);
7242 mRecordTeeSink = pipe;
7243 mRecordTeeSource = pipeReader;
7244 teeSink = pipe;
7245 }
7246 break;
7247 case TEE_SINK_OLD:
7248 teeSink = mRecordTeeSink;
7249 break;
7250 case TEE_SINK_NO:
7251 default:
7252 break;
7253 }
7254#endif
Dima Zavin799a70e2011-04-18 16:57:27 -07007255 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7256
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007257 // Start record thread
7258 // RecorThread require both input and output device indication to forward to audio
7259 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007260 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Glenn Kasten8c327342012-09-30 12:29:28 -07007261
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007262 thread = new RecordThread(this,
7263 input,
7264 reqSamplingRate,
7265 reqChannels,
7266 id,
Glenn Kasten8c327342012-09-30 12:29:28 -07007267 device, teeSink);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007268 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007269 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007270 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007271 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007272 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007273
Mathias Agopian65ab4712010-07-14 17:59:35 -07007274 // notify client processes of the new input creation
7275 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7276 return id;
7277 }
7278
7279 return 0;
7280}
7281
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007282status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007283{
Glenn Kastend96c5722012-04-25 13:44:49 -07007284 return closeInput_nonvirtual(input);
7285}
7286
7287status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7288{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007289 // keep strong reference on the record thread so that
7290 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007291 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007292 {
7293 Mutex::Autolock _l(mLock);
7294 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007295 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007296 return BAD_VALUE;
7297 }
7298
Steve Block3856b092011-10-20 11:56:00 +01007299 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007300 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007301 mRecordThreads.removeItem(input);
7302 }
7303 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007304 // The thread entity (active unit of execution) is no longer running here,
7305 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007306
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007307 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007308 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007309 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007310 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007311 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007312
7313 return NO_ERROR;
7314}
7315
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007316status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007317{
7318 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007319 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007320
7321 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7322 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007323 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007324 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007325
7326 return NO_ERROR;
7327}
7328
7329
7330int AudioFlinger::newAudioSessionId()
7331{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007332 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007333}
7334
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007335void AudioFlinger::acquireAudioSessionId(int audioSession)
7336{
7337 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007338 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007339 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007340 size_t num = mAudioSessionRefs.size();
7341 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007342 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007343 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7344 ref->mCnt++;
7345 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007346 return;
7347 }
7348 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007349 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7350 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007351}
7352
7353void AudioFlinger::releaseAudioSessionId(int audioSession)
7354{
7355 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007356 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007357 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007358 size_t num = mAudioSessionRefs.size();
7359 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007360 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007361 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7362 ref->mCnt--;
7363 ALOGV(" decremented refcount to %d", ref->mCnt);
7364 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007365 mAudioSessionRefs.removeAt(i);
7366 delete ref;
7367 purgeStaleEffects_l();
7368 }
7369 return;
7370 }
7371 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007372 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007373}
7374
7375void AudioFlinger::purgeStaleEffects_l() {
7376
Steve Block3856b092011-10-20 11:56:00 +01007377 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007378
7379 Vector< sp<EffectChain> > chains;
7380
7381 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7382 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7383 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7384 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007385 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7386 chains.push(ec);
7387 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007388 }
7389 }
7390 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7391 sp<RecordThread> t = mRecordThreads.valueAt(i);
7392 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7393 sp<EffectChain> ec = t->mEffectChains[j];
7394 chains.push(ec);
7395 }
7396 }
7397
7398 for (size_t i = 0; i < chains.size(); i++) {
7399 sp<EffectChain> ec = chains[i];
7400 int sessionid = ec->sessionId();
7401 sp<ThreadBase> t = ec->mThread.promote();
7402 if (t == 0) {
7403 continue;
7404 }
7405 size_t numsessionrefs = mAudioSessionRefs.size();
7406 bool found = false;
7407 for (size_t k = 0; k < numsessionrefs; k++) {
7408 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007409 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007410 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007411 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007412 found = true;
7413 break;
7414 }
7415 }
7416 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007417 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007418 // remove all effects from the chain
7419 while (ec->mEffects.size()) {
7420 sp<EffectModule> effect = ec->mEffects[0];
7421 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007422 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007423 if (effect->purgeHandles()) {
7424 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007425 }
7426 AudioSystem::unregisterEffect(effect->id());
7427 }
7428 }
7429 }
7430 return;
7431}
7432
Mathias Agopian65ab4712010-07-14 17:59:35 -07007433// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007434AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007435{
Glenn Kastena1117922012-01-26 10:53:32 -08007436 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007437}
7438
7439// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007440AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007441{
7442 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007443 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007444}
7445
7446// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007447AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007448{
Glenn Kastena1117922012-01-26 10:53:32 -08007449 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007450}
7451
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007452uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007453{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007454 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007455}
7456
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007457AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007458{
7459 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7460 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007461 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07007462 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007463 return thread;
7464 }
7465 }
7466 return NULL;
7467}
7468
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007469audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007470{
7471 PlaybackThread *thread = primaryPlaybackThread_l();
7472
7473 if (thread == NULL) {
7474 return 0;
7475 }
7476
Eric Laurent88959252012-08-28 14:26:53 -07007477 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007478}
7479
Eric Laurenta011e352012-03-29 15:51:43 -07007480sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7481 int triggerSession,
7482 int listenerSession,
7483 sync_event_callback_t callBack,
7484 void *cookie)
7485{
7486 Mutex::Autolock _l(mLock);
7487
7488 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7489 status_t playStatus = NAME_NOT_FOUND;
7490 status_t recStatus = NAME_NOT_FOUND;
7491 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7492 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7493 if (playStatus == NO_ERROR) {
7494 return event;
7495 }
7496 }
7497 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7498 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7499 if (recStatus == NO_ERROR) {
7500 return event;
7501 }
7502 }
7503 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7504 mPendingSyncEvents.add(event);
7505 } else {
7506 ALOGV("createSyncEvent() invalid event %d", event->type());
7507 event.clear();
7508 }
7509 return event;
7510}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007511
Mathias Agopian65ab4712010-07-14 17:59:35 -07007512// ----------------------------------------------------------------------------
7513// Effect management
7514// ----------------------------------------------------------------------------
7515
7516
Glenn Kastenf587ba52012-01-26 16:25:10 -08007517status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007518{
7519 Mutex::Autolock _l(mLock);
7520 return EffectQueryNumberEffects(numEffects);
7521}
7522
Glenn Kastenf587ba52012-01-26 16:25:10 -08007523status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007524{
7525 Mutex::Autolock _l(mLock);
7526 return EffectQueryEffect(index, descriptor);
7527}
7528
Glenn Kasten5e92a782012-01-30 07:40:52 -08007529status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007530 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007531{
7532 Mutex::Autolock _l(mLock);
7533 return EffectGetDescriptor(pUuid, descriptor);
7534}
7535
7536
Mathias Agopian65ab4712010-07-14 17:59:35 -07007537sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7538 effect_descriptor_t *pDesc,
7539 const sp<IEffectClient>& effectClient,
7540 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007541 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007542 int sessionId,
7543 status_t *status,
7544 int *id,
7545 int *enabled)
7546{
7547 status_t lStatus = NO_ERROR;
7548 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007549 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007550
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007551 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007552 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007553
7554 if (pDesc == NULL) {
7555 lStatus = BAD_VALUE;
7556 goto Exit;
7557 }
7558
Eric Laurent84e9a102010-09-23 16:10:16 -07007559 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007560 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007561 lStatus = PERMISSION_DENIED;
7562 goto Exit;
7563 }
7564
Dima Zavinfce7a472011-04-19 22:30:36 -07007565 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007566 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007567 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007568 lStatus = PERMISSION_DENIED;
7569 goto Exit;
7570 }
7571
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007572 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007573 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007574 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007575 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007576 lStatus = BAD_VALUE;
7577 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007578 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007579 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007580 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007581 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007582 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007583 }
7584 }
7585
Mathias Agopian65ab4712010-07-14 17:59:35 -07007586 {
7587 Mutex::Autolock _l(mLock);
7588
Mathias Agopian65ab4712010-07-14 17:59:35 -07007589
7590 if (!EffectIsNullUuid(&pDesc->uuid)) {
7591 // if uuid is specified, request effect descriptor
7592 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7593 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007594 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007595 goto Exit;
7596 }
7597 } else {
7598 // if uuid is not specified, look for an available implementation
7599 // of the required type in effect factory
7600 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007601 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007602 lStatus = BAD_VALUE;
7603 goto Exit;
7604 }
7605 uint32_t numEffects = 0;
7606 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007607 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007608 bool found = false;
7609
7610 lStatus = EffectQueryNumberEffects(&numEffects);
7611 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007612 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007613 goto Exit;
7614 }
7615 for (uint32_t i = 0; i < numEffects; i++) {
7616 lStatus = EffectQueryEffect(i, &desc);
7617 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007618 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007619 continue;
7620 }
7621 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7622 // If matching type found save effect descriptor. If the session is
7623 // 0 and the effect is not auxiliary, continue enumeration in case
7624 // an auxiliary version of this effect type is available
7625 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08007626 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07007627 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007628 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7629 break;
7630 }
7631 }
7632 }
7633 if (!found) {
7634 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007635 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007636 goto Exit;
7637 }
7638 // For same effect type, chose auxiliary version over insert version if
7639 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007640 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007641 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08007642 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007643 }
7644 }
7645
7646 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007647 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007648 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7649 lStatus = INVALID_OPERATION;
7650 goto Exit;
7651 }
7652
Eric Laurent59255e42011-07-27 19:49:51 -07007653 // check recording permission for visualizer
7654 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7655 !recordingAllowed()) {
7656 lStatus = PERMISSION_DENIED;
7657 goto Exit;
7658 }
7659
Mathias Agopian65ab4712010-07-14 17:59:35 -07007660 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08007661 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007662
7663 // If output is not specified try to find a matching audio session ID in one of the
7664 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007665 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7666 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007667 // Note: io is never 0 when creating an effect on an input
7668 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007669 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007670 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7671 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007672 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007673 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007674 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007675 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007676 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007677 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7678 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7679 io = mRecordThreads.keyAt(i);
7680 break;
7681 }
7682 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007683 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007684 // If no output thread contains the requested session ID, default to
7685 // first output. The effect chain will be moved to the correct output
7686 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007687 if (io == 0 && mPlaybackThreads.size()) {
7688 io = mPlaybackThreads.keyAt(0);
7689 }
Steve Block3856b092011-10-20 11:56:00 +01007690 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007691 }
7692 ThreadBase *thread = checkRecordThread_l(io);
7693 if (thread == NULL) {
7694 thread = checkPlaybackThread_l(io);
7695 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007696 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007697 lStatus = BAD_VALUE;
7698 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007699 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007700 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007701
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007702 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007703
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007704 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007705 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7706 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007707 if (handle != 0 && id != NULL) {
7708 *id = handle->id();
7709 }
7710 }
7711
7712Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007713 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007714 *status = lStatus;
7715 }
7716 return handle;
7717}
7718
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007719status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7720 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007721{
Steve Block3856b092011-10-20 11:56:00 +01007722 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007723 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007724 Mutex::Autolock _l(mLock);
7725 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007726 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007727 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007728 }
Eric Laurentde070132010-07-13 04:45:46 -07007729 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7730 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007731 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007732 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007733 }
Eric Laurentde070132010-07-13 04:45:46 -07007734 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7735 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007736 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007737 return BAD_VALUE;
7738 }
7739
7740 Mutex::Autolock _dl(dstThread->mLock);
7741 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007742 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007743
Mathias Agopian65ab4712010-07-14 17:59:35 -07007744 return NO_ERROR;
7745}
7746
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007747// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007748status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007749 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007750 AudioFlinger::PlaybackThread *dstThread,
7751 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007752{
Steve Block3856b092011-10-20 11:56:00 +01007753 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007754 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007755
Eric Laurent59255e42011-07-27 19:49:51 -07007756 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007757 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007758 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007759 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007760 return INVALID_OPERATION;
7761 }
7762
Eric Laurent39e94f82010-07-28 01:32:47 -07007763 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007764 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007765 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007766 // removed.
7767 srcThread->removeEffectChain_l(chain);
7768
7769 // transfer all effects one by one so that new effect chain is created on new thread with
7770 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007771 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007772 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007773 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007774 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7775 while (effect != 0) {
7776 srcThread->removeEffect_l(effect);
7777 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007778 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7779 if (effect->state() == EffectModule::ACTIVE ||
7780 effect->state() == EffectModule::STOPPING) {
7781 effect->start();
7782 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007783 // if the move request is not received from audio policy manager, the effect must be
7784 // re-registered with the new strategy and output
7785 if (dstChain == 0) {
7786 dstChain = effect->chain().promote();
7787 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007788 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007789 srcThread->addEffect_l(effect);
7790 return NO_INIT;
7791 }
7792 strategy = dstChain->strategy();
7793 }
7794 if (reRegister) {
7795 AudioSystem::unregisterEffect(effect->id());
7796 AudioSystem::registerEffect(&effect->desc(),
7797 dstOutput,
7798 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007799 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007800 effect->id());
7801 }
Eric Laurentde070132010-07-13 04:45:46 -07007802 effect = chain->getEffectFromId_l(0);
7803 }
7804
7805 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007806}
7807
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007808
Mathias Agopian65ab4712010-07-14 17:59:35 -07007809// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007810sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007811 const sp<AudioFlinger::Client>& client,
7812 const sp<IEffectClient>& effectClient,
7813 int32_t priority,
7814 int sessionId,
7815 effect_descriptor_t *desc,
7816 int *enabled,
7817 status_t *status
7818 )
7819{
7820 sp<EffectModule> effect;
7821 sp<EffectHandle> handle;
7822 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007823 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007824 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007825 bool effectCreated = false;
7826 bool effectRegistered = false;
7827
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007828 lStatus = initCheck();
7829 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007830 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007831 goto Exit;
7832 }
7833
7834 // Do not allow effects with session ID 0 on direct output or duplicating threads
7835 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007836 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007837 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007838 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007839 lStatus = BAD_VALUE;
7840 goto Exit;
7841 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007842 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007843 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007844 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007845 desc->name, desc->flags, mType);
7846 lStatus = BAD_VALUE;
7847 goto Exit;
7848 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007849
Steve Block3856b092011-10-20 11:56:00 +01007850 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007851
7852 { // scope for mLock
7853 Mutex::Autolock _l(mLock);
7854
7855 // check for existing effect chain with the requested audio session
7856 chain = getEffectChain_l(sessionId);
7857 if (chain == 0) {
7858 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007859 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007860 chain = new EffectChain(this, sessionId);
7861 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007862 chain->setStrategy(getStrategyForSession_l(sessionId));
7863 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007864 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007865 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007866 }
7867
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007868 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007869
7870 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007871 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007872 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007873 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007874 if (lStatus != NO_ERROR) {
7875 goto Exit;
7876 }
7877 effectRegistered = true;
7878 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007879 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007880 lStatus = effect->status();
7881 if (lStatus != NO_ERROR) {
7882 goto Exit;
7883 }
Eric Laurentcab11242010-07-15 12:50:15 -07007884 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007885 if (lStatus != NO_ERROR) {
7886 goto Exit;
7887 }
7888 effectCreated = true;
7889
Eric Laurent88959252012-08-28 14:26:53 -07007890 effect->setDevice(mOutDevice);
7891 effect->setDevice(mInDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007892 effect->setMode(mAudioFlinger->getMode());
Eric Laurent2e9b0f22012-08-31 17:44:06 -07007893 effect->setAudioSource(mAudioSource);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007894 }
7895 // create effect handle and connect it to effect module
7896 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007897 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007898 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007899 *enabled = (int)effect->isEnabled();
7900 }
7901 }
7902
7903Exit:
7904 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007905 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007906 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007907 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007908 }
7909 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007910 AudioSystem::unregisterEffect(effect->id());
7911 }
7912 if (chainCreated) {
7913 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007914 }
7915 handle.clear();
7916 }
7917
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007918 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007919 *status = lStatus;
7920 }
7921 return handle;
7922}
7923
Eric Laurent717e1282012-06-29 16:36:52 -07007924sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7925{
7926 Mutex::Autolock _l(mLock);
7927 return getEffect_l(sessionId, effectId);
7928}
7929
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007930sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7931{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007932 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007933 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007934}
7935
Eric Laurentde070132010-07-13 04:45:46 -07007936// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7937// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007938status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007939{
7940 // check for existing effect chain with the requested audio session
7941 int sessionId = effect->sessionId();
7942 sp<EffectChain> chain = getEffectChain_l(sessionId);
7943 bool chainCreated = false;
7944
7945 if (chain == 0) {
7946 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007947 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007948 chain = new EffectChain(this, sessionId);
7949 addEffectChain_l(chain);
7950 chain->setStrategy(getStrategyForSession_l(sessionId));
7951 chainCreated = true;
7952 }
Steve Block3856b092011-10-20 11:56:00 +01007953 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007954
7955 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007956 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007957 this, effect->desc().name, chain.get());
7958 return BAD_VALUE;
7959 }
7960
7961 status_t status = chain->addEffect_l(effect);
7962 if (status != NO_ERROR) {
7963 if (chainCreated) {
7964 removeEffectChain_l(chain);
7965 }
7966 return status;
7967 }
7968
Eric Laurent88959252012-08-28 14:26:53 -07007969 effect->setDevice(mOutDevice);
7970 effect->setDevice(mInDevice);
Eric Laurentde070132010-07-13 04:45:46 -07007971 effect->setMode(mAudioFlinger->getMode());
Eric Laurent2e9b0f22012-08-31 17:44:06 -07007972 effect->setAudioSource(mAudioSource);
Eric Laurentde070132010-07-13 04:45:46 -07007973 return NO_ERROR;
7974}
7975
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007976void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007977
Steve Block3856b092011-10-20 11:56:00 +01007978 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007979 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007980 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7981 detachAuxEffect_l(effect->id());
7982 }
7983
7984 sp<EffectChain> chain = effect->chain().promote();
7985 if (chain != 0) {
7986 // remove effect chain if removing last effect
7987 if (chain->removeEffect_l(effect) == 0) {
7988 removeEffectChain_l(chain);
7989 }
7990 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007991 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007992 }
7993}
7994
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007995void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007996 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007997{
7998 effectChains = mEffectChains;
7999 for (size_t i = 0; i < mEffectChains.size(); i++) {
8000 mEffectChains[i]->lock();
8001 }
8002}
8003
8004void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008005 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008006{
8007 for (size_t i = 0; i < effectChains.size(); i++) {
8008 effectChains[i]->unlock();
8009 }
8010}
8011
8012sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
8013{
8014 Mutex::Autolock _l(mLock);
8015 return getEffectChain_l(sessionId);
8016}
8017
Glenn Kasten106e8a42012-08-02 13:37:12 -07008018sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008019{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008020 size_t size = mEffectChains.size();
8021 for (size_t i = 0; i < size; i++) {
8022 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008023 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008024 }
8025 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008026 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008027}
8028
Glenn Kastenf78aee72012-01-04 11:00:47 -08008029void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008030{
8031 Mutex::Autolock _l(mLock);
8032 size_t size = mEffectChains.size();
8033 for (size_t i = 0; i < size; i++) {
8034 mEffectChains[i]->setMode_l(mode);
8035 }
8036}
8037
8038void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008039 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08008040 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07008041
Mathias Agopian65ab4712010-07-14 17:59:35 -07008042 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008043 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008044 // delete the effect module if removing last handle on it
8045 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008046 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008047 removeEffect_l(effect);
8048 AudioSystem::unregisterEffect(effect->id());
8049 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008050 }
8051}
8052
8053status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
8054{
8055 int session = chain->sessionId();
8056 int16_t *buffer = mMixBuffer;
8057 bool ownsBuffer = false;
8058
Steve Block3856b092011-10-20 11:56:00 +01008059 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008060 if (session > 0) {
8061 // Only one effect chain can be present in direct output thread and it uses
8062 // the mix buffer as input
8063 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07008064 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008065 buffer = new int16_t[numSamples];
8066 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01008067 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008068 ownsBuffer = true;
8069 }
8070
8071 // Attach all tracks with same session ID to this chain.
8072 for (size_t i = 0; i < mTracks.size(); ++i) {
8073 sp<Track> track = mTracks[i];
8074 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008075 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008076 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008077 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008078 }
8079 }
8080
8081 // indicate all active tracks in the chain
8082 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8083 sp<Track> track = mActiveTracks[i].promote();
8084 if (track == 0) continue;
8085 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008086 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07008087 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008088 }
8089 }
8090 }
8091
8092 chain->setInBuffer(buffer, ownsBuffer);
8093 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07008094 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07008095 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008096 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
8097 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008098 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07008099 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
8100 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07008101 // Effect chain for other sessions are inserted at beginning of effect
8102 // chains list to be processed before output mix effects. Relative order between other
8103 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07008104 size_t size = mEffectChains.size();
8105 size_t i = 0;
8106 for (i = 0; i < size; i++) {
8107 if (mEffectChains[i]->sessionId() < session) break;
8108 }
8109 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008110 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008111
8112 return NO_ERROR;
8113}
8114
8115size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
8116{
8117 int session = chain->sessionId();
8118
Steve Block3856b092011-10-20 11:56:00 +01008119 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008120
8121 for (size_t i = 0; i < mEffectChains.size(); i++) {
8122 if (chain == mEffectChains[i]) {
8123 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07008124 // detach all active tracks from the chain
8125 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8126 sp<Track> track = mActiveTracks[i].promote();
8127 if (track == 0) continue;
8128 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008129 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07008130 chain.get(), session);
8131 chain->decActiveTrackCnt();
8132 }
8133 }
8134
Mathias Agopian65ab4712010-07-14 17:59:35 -07008135 // detach all tracks with same session ID from this chain
8136 for (size_t i = 0; i < mTracks.size(); ++i) {
8137 sp<Track> track = mTracks[i];
8138 if (session == track->sessionId()) {
8139 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008140 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008141 }
8142 }
Eric Laurentde070132010-07-13 04:45:46 -07008143 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008144 }
8145 }
8146 return mEffectChains.size();
8147}
8148
Eric Laurentde070132010-07-13 04:45:46 -07008149status_t AudioFlinger::PlaybackThread::attachAuxEffect(
8150 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008151{
8152 Mutex::Autolock _l(mLock);
8153 return attachAuxEffect_l(track, EffectId);
8154}
8155
Eric Laurentde070132010-07-13 04:45:46 -07008156status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
8157 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008158{
8159 status_t status = NO_ERROR;
8160
8161 if (EffectId == 0) {
8162 track->setAuxBuffer(0, NULL);
8163 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07008164 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
8165 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008166 if (effect != 0) {
8167 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8168 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
8169 } else {
8170 status = INVALID_OPERATION;
8171 }
8172 } else {
8173 status = BAD_VALUE;
8174 }
8175 }
8176 return status;
8177}
8178
8179void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
8180{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008181 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008182 sp<Track> track = mTracks[i];
8183 if (track->auxEffectId() == effectId) {
8184 attachAuxEffect_l(track, 0);
8185 }
8186 }
8187}
8188
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008189status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8190{
8191 // only one chain per input thread
8192 if (mEffectChains.size() != 0) {
8193 return INVALID_OPERATION;
8194 }
Steve Block3856b092011-10-20 11:56:00 +01008195 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008196
8197 chain->setInBuffer(NULL);
8198 chain->setOutBuffer(NULL);
8199
Eric Laurent59255e42011-07-27 19:49:51 -07008200 checkSuspendOnAddEffectChain_l(chain);
8201
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008202 mEffectChains.add(chain);
8203
8204 return NO_ERROR;
8205}
8206
8207size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8208{
Steve Block3856b092011-10-20 11:56:00 +01008209 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00008210 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008211 "removeEffectChain_l() %p invalid chain size %d on thread %p",
8212 chain.get(), mEffectChains.size(), this);
8213 if (mEffectChains.size() == 1) {
8214 mEffectChains.removeAt(0);
8215 }
8216 return 0;
8217}
8218
Mathias Agopian65ab4712010-07-14 17:59:35 -07008219// ----------------------------------------------------------------------------
8220// EffectModule implementation
8221// ----------------------------------------------------------------------------
8222
8223#undef LOG_TAG
8224#define LOG_TAG "AudioFlinger::EffectModule"
8225
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008226AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008227 const wp<AudioFlinger::EffectChain>& chain,
8228 effect_descriptor_t *desc,
8229 int id,
8230 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07008231 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
8232 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07008233 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07008234 // mConfig is set by configure() and not used before then
8235 mEffectInterface(NULL),
8236 mStatus(NO_INIT), mState(IDLE),
8237 // mMaxDisableWaitCnt is set by configure() and not used before then
8238 // mDisableWaitCnt is set by process() and updateState() and not used before then
8239 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008240{
Steve Block3856b092011-10-20 11:56:00 +01008241 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008242 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008243
8244 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008245 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008246
8247 if (mStatus != NO_ERROR) {
8248 return;
8249 }
8250 lStatus = init();
8251 if (lStatus < 0) {
8252 mStatus = lStatus;
8253 goto Error;
8254 }
8255
Steve Block3856b092011-10-20 11:56:00 +01008256 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008257 return;
8258Error:
8259 EffectRelease(mEffectInterface);
8260 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008261 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008262}
8263
8264AudioFlinger::EffectModule::~EffectModule()
8265{
Steve Block3856b092011-10-20 11:56:00 +01008266 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008267 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008268 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8269 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8270 sp<ThreadBase> thread = mThread.promote();
8271 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008272 audio_stream_t *stream = thread->stream();
8273 if (stream != NULL) {
8274 stream->remove_audio_effect(stream, mEffectInterface);
8275 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008276 }
8277 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008278 // release effect engine
8279 EffectRelease(mEffectInterface);
8280 }
8281}
8282
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008283status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008284{
8285 status_t status;
8286
8287 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008288 int priority = handle->priority();
8289 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008290 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008291 size_t i;
8292 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008293 EffectHandle *h = mHandles[i];
8294 if (h == NULL || h->destroyed_l()) continue;
8295 // first non destroyed handle is considered in control
8296 if (controlHandle == NULL)
8297 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008298 if (h->priority() <= priority) break;
8299 }
8300 // if inserted in first place, move effect control from previous owner to this handle
8301 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008302 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008303 if (controlHandle != NULL) {
8304 enabled = controlHandle->enabled();
8305 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008306 }
Eric Laurent59255e42011-07-27 19:49:51 -07008307 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008308 status = NO_ERROR;
8309 } else {
8310 status = ALREADY_EXISTS;
8311 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008312 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008313 mHandles.insertAt(handle, i);
8314 return status;
8315}
8316
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008317size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008318{
8319 Mutex::Autolock _l(mLock);
8320 size_t size = mHandles.size();
8321 size_t i;
8322 for (i = 0; i < size; i++) {
8323 if (mHandles[i] == handle) break;
8324 }
8325 if (i == size) {
8326 return size;
8327 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008328 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008329
Mathias Agopian65ab4712010-07-14 17:59:35 -07008330 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008331 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008332 if (i == 0) {
8333 EffectHandle *h = controlHandle_l();
8334 if (h != NULL) {
8335 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008336 }
8337 }
8338
Eric Laurentec437d82011-07-26 20:54:46 -07008339 // Prevent calls to process() and other functions on effect interface from now on.
8340 // The effect engine will be released by the destructor when the last strong reference on
8341 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008342 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008343 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008344 }
8345
Eric Laurente65c8912012-07-20 15:57:23 -07008346 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008347}
8348
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008349// must be called with EffectModule::mLock held
8350AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008351{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008352 // the first valid handle in the list has control over the module
8353 for (size_t i = 0; i < mHandles.size(); i++) {
8354 EffectHandle *h = mHandles[i];
8355 if (h != NULL && !h->destroyed_l()) {
8356 return h;
8357 }
8358 }
8359
8360 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008361}
8362
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008363size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008364{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008365 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008366 // keep a strong reference on this EffectModule to avoid calling the
8367 // destructor before we exit
8368 sp<EffectModule> keep(this);
8369 {
8370 sp<ThreadBase> thread = mThread.promote();
8371 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008372 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008373 }
8374 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008375 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008376}
8377
8378void AudioFlinger::EffectModule::updateState() {
8379 Mutex::Autolock _l(mLock);
8380
8381 switch (mState) {
8382 case RESTART:
8383 reset_l();
8384 // FALL THROUGH
8385
8386 case STARTING:
8387 // clear auxiliary effect input buffer for next accumulation
8388 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8389 memset(mConfig.inputCfg.buffer.raw,
8390 0,
8391 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8392 }
8393 start_l();
8394 mState = ACTIVE;
8395 break;
8396 case STOPPING:
8397 stop_l();
8398 mDisableWaitCnt = mMaxDisableWaitCnt;
8399 mState = STOPPED;
8400 break;
8401 case STOPPED:
8402 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8403 // turn off sequence.
8404 if (--mDisableWaitCnt == 0) {
8405 reset_l();
8406 mState = IDLE;
8407 }
8408 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008409 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008410 break;
8411 }
8412}
8413
8414void AudioFlinger::EffectModule::process()
8415{
8416 Mutex::Autolock _l(mLock);
8417
Eric Laurentec437d82011-07-26 20:54:46 -07008418 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008419 mConfig.inputCfg.buffer.raw == NULL ||
8420 mConfig.outputCfg.buffer.raw == NULL) {
8421 return;
8422 }
8423
Eric Laurent8f45bd72010-08-31 13:50:07 -07008424 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008425 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8426 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008427 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008428 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008429 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008430 }
8431
8432 // do the actual processing in the effect engine
8433 int ret = (*mEffectInterface)->process(mEffectInterface,
8434 &mConfig.inputCfg.buffer,
8435 &mConfig.outputCfg.buffer);
8436
8437 // force transition to IDLE state when engine is ready
8438 if (mState == STOPPED && ret == -ENODATA) {
8439 mDisableWaitCnt = 1;
8440 }
8441
8442 // clear auxiliary effect input buffer for next accumulation
8443 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008444 memset(mConfig.inputCfg.buffer.raw, 0,
8445 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008446 }
8447 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008448 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8449 // If an insert effect is idle and input buffer is different from output buffer,
8450 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008451 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008452 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008453 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8454 int16_t *in = mConfig.inputCfg.buffer.s16;
8455 int16_t *out = mConfig.outputCfg.buffer.s16;
8456 for (size_t i = 0; i < frameCnt; i++) {
8457 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008458 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008459 }
8460 }
8461}
8462
8463void AudioFlinger::EffectModule::reset_l()
8464{
8465 if (mEffectInterface == NULL) {
8466 return;
8467 }
8468 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8469}
8470
8471status_t AudioFlinger::EffectModule::configure()
8472{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008473 if (mEffectInterface == NULL) {
8474 return NO_INIT;
8475 }
8476
8477 sp<ThreadBase> thread = mThread.promote();
8478 if (thread == 0) {
8479 return DEAD_OBJECT;
8480 }
8481
8482 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07008483 audio_channel_mask_t channelMask = thread->channelMask();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008484
8485 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008486 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008487 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07008488 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008489 }
Glenn Kasten254af182012-07-03 14:59:05 -07008490 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07008491 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8492 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008493 mConfig.inputCfg.samplingRate = thread->sampleRate();
8494 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8495 mConfig.inputCfg.bufferProvider.cookie = NULL;
8496 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8497 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8498 mConfig.outputCfg.bufferProvider.cookie = NULL;
8499 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8500 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8501 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8502 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008503 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008504 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008505 // - in other sessions:
8506 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8507 // other effect: overwrites output buffer: input buffer == output buffer
8508 // Auxiliary effect:
8509 // accumulates in output buffer: input buffer != output buffer
8510 // Therefore: accumulate <=> input buffer != output buffer
8511 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8512 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8513 } else {
8514 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8515 }
8516 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8517 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8518 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8519 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8520
Steve Block3856b092011-10-20 11:56:00 +01008521 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008522 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8523
Mathias Agopian65ab4712010-07-14 17:59:35 -07008524 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008525 uint32_t size = sizeof(int);
8526 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008527 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008528 sizeof(effect_config_t),
8529 &mConfig,
8530 &size,
8531 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008532 if (status == 0) {
8533 status = cmdStatus;
8534 }
8535
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008536 if (status == 0 &&
8537 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8538 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8539 effect_param_t *p = (effect_param_t *)buf32;
8540
8541 p->psize = sizeof(uint32_t);
8542 p->vsize = sizeof(uint32_t);
8543 size = sizeof(int);
8544 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8545
8546 uint32_t latency = 0;
8547 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8548 if (pbt != NULL) {
8549 latency = pbt->latency_l();
8550 }
8551
8552 *((int32_t *)p->data + 1)= latency;
8553 (*mEffectInterface)->command(mEffectInterface,
8554 EFFECT_CMD_SET_PARAM,
8555 sizeof(effect_param_t) + 8,
8556 &buf32,
8557 &size,
8558 &cmdStatus);
8559 }
8560
Mathias Agopian65ab4712010-07-14 17:59:35 -07008561 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8562 (1000 * mConfig.outputCfg.buffer.frameCount);
8563
8564 return status;
8565}
8566
8567status_t AudioFlinger::EffectModule::init()
8568{
8569 Mutex::Autolock _l(mLock);
8570 if (mEffectInterface == NULL) {
8571 return NO_INIT;
8572 }
8573 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008574 uint32_t size = sizeof(status_t);
8575 status_t status = (*mEffectInterface)->command(mEffectInterface,
8576 EFFECT_CMD_INIT,
8577 0,
8578 NULL,
8579 &size,
8580 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008581 if (status == 0) {
8582 status = cmdStatus;
8583 }
8584 return status;
8585}
8586
Eric Laurentec35a142011-10-05 17:42:25 -07008587status_t AudioFlinger::EffectModule::start()
8588{
8589 Mutex::Autolock _l(mLock);
8590 return start_l();
8591}
8592
Mathias Agopian65ab4712010-07-14 17:59:35 -07008593status_t AudioFlinger::EffectModule::start_l()
8594{
8595 if (mEffectInterface == NULL) {
8596 return NO_INIT;
8597 }
8598 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008599 uint32_t size = sizeof(status_t);
8600 status_t status = (*mEffectInterface)->command(mEffectInterface,
8601 EFFECT_CMD_ENABLE,
8602 0,
8603 NULL,
8604 &size,
8605 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008606 if (status == 0) {
8607 status = cmdStatus;
8608 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008609 if (status == 0 &&
8610 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8611 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8612 sp<ThreadBase> thread = mThread.promote();
8613 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008614 audio_stream_t *stream = thread->stream();
8615 if (stream != NULL) {
8616 stream->add_audio_effect(stream, mEffectInterface);
8617 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008618 }
8619 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008620 return status;
8621}
8622
Eric Laurentec437d82011-07-26 20:54:46 -07008623status_t AudioFlinger::EffectModule::stop()
8624{
8625 Mutex::Autolock _l(mLock);
8626 return stop_l();
8627}
8628
Mathias Agopian65ab4712010-07-14 17:59:35 -07008629status_t AudioFlinger::EffectModule::stop_l()
8630{
8631 if (mEffectInterface == NULL) {
8632 return NO_INIT;
8633 }
8634 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008635 uint32_t size = sizeof(status_t);
8636 status_t status = (*mEffectInterface)->command(mEffectInterface,
8637 EFFECT_CMD_DISABLE,
8638 0,
8639 NULL,
8640 &size,
8641 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008642 if (status == 0) {
8643 status = cmdStatus;
8644 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008645 if (status == 0 &&
8646 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8647 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8648 sp<ThreadBase> thread = mThread.promote();
8649 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008650 audio_stream_t *stream = thread->stream();
8651 if (stream != NULL) {
8652 stream->remove_audio_effect(stream, mEffectInterface);
8653 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008654 }
8655 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008656 return status;
8657}
8658
Eric Laurent25f43952010-07-28 05:40:18 -07008659status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8660 uint32_t cmdSize,
8661 void *pCmdData,
8662 uint32_t *replySize,
8663 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008664{
8665 Mutex::Autolock _l(mLock);
Glenn Kastencbe4b362012-10-18 15:51:03 -07008666 ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008667
Eric Laurentec437d82011-07-26 20:54:46 -07008668 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008669 return NO_INIT;
8670 }
Eric Laurent25f43952010-07-28 05:40:18 -07008671 status_t status = (*mEffectInterface)->command(mEffectInterface,
8672 cmdCode,
8673 cmdSize,
8674 pCmdData,
8675 replySize,
8676 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008677 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008678 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008679 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008680 EffectHandle *h = mHandles[i];
8681 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008682 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8683 }
8684 }
8685 }
8686 return status;
8687}
8688
8689status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8690{
8691 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008692 return setEnabled_l(enabled);
8693}
8694
8695// must be called with EffectModule::mLock held
8696status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8697{
8698
Steve Block3856b092011-10-20 11:56:00 +01008699 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008700
8701 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008702 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8703 if (enabled && status != NO_ERROR) {
8704 return status;
8705 }
8706
Mathias Agopian65ab4712010-07-14 17:59:35 -07008707 switch (mState) {
8708 // going from disabled to enabled
8709 case IDLE:
8710 mState = STARTING;
8711 break;
8712 case STOPPED:
8713 mState = RESTART;
8714 break;
8715 case STOPPING:
8716 mState = ACTIVE;
8717 break;
8718
8719 // going from enabled to disabled
8720 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008721 mState = STOPPED;
8722 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008723 case STARTING:
8724 mState = IDLE;
8725 break;
8726 case ACTIVE:
8727 mState = STOPPING;
8728 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008729 case DESTROYED:
8730 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008731 }
8732 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008733 EffectHandle *h = mHandles[i];
8734 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008735 h->setEnabled(enabled);
8736 }
8737 }
8738 }
8739 return NO_ERROR;
8740}
8741
Glenn Kastenc59c0042012-02-02 14:06:11 -08008742bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008743{
8744 switch (mState) {
8745 case RESTART:
8746 case STARTING:
8747 case ACTIVE:
8748 return true;
8749 case IDLE:
8750 case STOPPING:
8751 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008752 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008753 default:
8754 return false;
8755 }
8756}
8757
Glenn Kastenc59c0042012-02-02 14:06:11 -08008758bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008759{
8760 switch (mState) {
8761 case RESTART:
8762 case ACTIVE:
8763 case STOPPING:
8764 case STOPPED:
8765 return true;
8766 case IDLE:
8767 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008768 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008769 default:
8770 return false;
8771 }
8772}
8773
Mathias Agopian65ab4712010-07-14 17:59:35 -07008774status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8775{
8776 Mutex::Autolock _l(mLock);
8777 status_t status = NO_ERROR;
8778
8779 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8780 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008781 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008782 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8783 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008784 status_t cmdStatus;
8785 uint32_t volume[2];
8786 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008787 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008788 volume[0] = *left;
8789 volume[1] = *right;
8790 if (controller) {
8791 pVolume = volume;
8792 }
Eric Laurent25f43952010-07-28 05:40:18 -07008793 status = (*mEffectInterface)->command(mEffectInterface,
8794 EFFECT_CMD_SET_VOLUME,
8795 size,
8796 volume,
8797 &size,
8798 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008799 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8800 *left = volume[0];
8801 *right = volume[1];
8802 }
8803 }
8804 return status;
8805}
8806
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008807status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008808{
Eric Laurent88959252012-08-28 14:26:53 -07008809 if (device == AUDIO_DEVICE_NONE) {
8810 return NO_ERROR;
8811 }
8812
Mathias Agopian65ab4712010-07-14 17:59:35 -07008813 Mutex::Autolock _l(mLock);
8814 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008815 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Eric Laurent88959252012-08-28 14:26:53 -07008816 status_t cmdStatus;
8817 uint32_t size = sizeof(status_t);
8818 uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE :
8819 EFFECT_CMD_SET_INPUT_DEVICE;
8820 status = (*mEffectInterface)->command(mEffectInterface,
8821 cmd,
8822 sizeof(uint32_t),
8823 &device,
8824 &size,
8825 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008826 }
8827 return status;
8828}
8829
Glenn Kastenf78aee72012-01-04 11:00:47 -08008830status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008831{
8832 Mutex::Autolock _l(mLock);
8833 status_t status = NO_ERROR;
8834 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008835 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008836 uint32_t size = sizeof(status_t);
8837 status = (*mEffectInterface)->command(mEffectInterface,
8838 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008839 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008840 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008841 &size,
8842 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008843 if (status == NO_ERROR) {
8844 status = cmdStatus;
8845 }
8846 }
8847 return status;
8848}
8849
Eric Laurent2e9b0f22012-08-31 17:44:06 -07008850status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
8851{
8852 Mutex::Autolock _l(mLock);
8853 status_t status = NO_ERROR;
8854 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
8855 uint32_t size = 0;
8856 status = (*mEffectInterface)->command(mEffectInterface,
8857 EFFECT_CMD_SET_AUDIO_SOURCE,
8858 sizeof(audio_source_t),
8859 &source,
8860 &size,
8861 NULL);
8862 }
8863 return status;
8864}
8865
Eric Laurent59255e42011-07-27 19:49:51 -07008866void AudioFlinger::EffectModule::setSuspended(bool suspended)
8867{
8868 Mutex::Autolock _l(mLock);
8869 mSuspended = suspended;
8870}
Glenn Kastena3a85482012-01-04 11:01:11 -08008871
8872bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008873{
8874 Mutex::Autolock _l(mLock);
8875 return mSuspended;
8876}
8877
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008878bool AudioFlinger::EffectModule::purgeHandles()
8879{
8880 bool enabled = false;
8881 Mutex::Autolock _l(mLock);
8882 for (size_t i = 0; i < mHandles.size(); i++) {
8883 EffectHandle *handle = mHandles[i];
8884 if (handle != NULL && !handle->destroyed_l()) {
8885 handle->effect().clear();
8886 if (handle->hasControl()) {
8887 enabled = handle->enabled();
8888 }
8889 }
8890 }
8891 return enabled;
8892}
8893
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07008894void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008895{
8896 const size_t SIZE = 256;
8897 char buffer[SIZE];
8898 String8 result;
8899
8900 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8901 result.append(buffer);
8902
8903 bool locked = tryLock(mLock);
8904 // failed to lock - AudioFlinger is probably deadlocked
8905 if (!locked) {
8906 result.append("\t\tCould not lock Fx mutex:\n");
8907 }
8908
8909 result.append("\t\tSession Status State Engine:\n");
8910 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8911 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8912 result.append(buffer);
8913
8914 result.append("\t\tDescriptor:\n");
8915 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8916 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8917 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8918 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8919 result.append(buffer);
8920 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8921 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8922 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8923 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8924 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008925 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008926 mDescriptor.apiVersion,
8927 mDescriptor.flags);
8928 result.append(buffer);
8929 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8930 mDescriptor.name);
8931 result.append(buffer);
8932 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8933 mDescriptor.implementor);
8934 result.append(buffer);
8935
8936 result.append("\t\t- Input configuration:\n");
8937 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8938 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8939 (uint32_t)mConfig.inputCfg.buffer.raw,
8940 mConfig.inputCfg.buffer.frameCount,
8941 mConfig.inputCfg.samplingRate,
8942 mConfig.inputCfg.channels,
8943 mConfig.inputCfg.format);
8944 result.append(buffer);
8945
8946 result.append("\t\t- Output configuration:\n");
8947 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8948 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8949 (uint32_t)mConfig.outputCfg.buffer.raw,
8950 mConfig.outputCfg.buffer.frameCount,
8951 mConfig.outputCfg.samplingRate,
8952 mConfig.outputCfg.channels,
8953 mConfig.outputCfg.format);
8954 result.append(buffer);
8955
8956 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8957 result.append(buffer);
8958 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8959 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008960 EffectHandle *handle = mHandles[i];
8961 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008962 handle->dump(buffer, SIZE);
8963 result.append(buffer);
8964 }
8965 }
8966
8967 result.append("\n");
8968
8969 write(fd, result.string(), result.length());
8970
8971 if (locked) {
8972 mLock.unlock();
8973 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008974}
8975
8976// ----------------------------------------------------------------------------
8977// EffectHandle implementation
8978// ----------------------------------------------------------------------------
8979
8980#undef LOG_TAG
8981#define LOG_TAG "AudioFlinger::EffectHandle"
8982
8983AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8984 const sp<AudioFlinger::Client>& client,
8985 const sp<IEffectClient>& effectClient,
8986 int32_t priority)
8987 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008988 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008989 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008990{
Steve Block3856b092011-10-20 11:56:00 +01008991 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008992
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008993 if (client == 0) {
8994 return;
8995 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008996 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8997 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8998 if (mCblkMemory != 0) {
8999 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
9000
Glenn Kastena0d68332012-01-27 16:47:15 -08009001 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009002 new(mCblk) effect_param_cblk_t();
9003 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009004 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009005 } else {
Steve Block29357bc2012-01-06 19:20:56 +00009006 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07009007 return;
9008 }
9009}
9010
9011AudioFlinger::EffectHandle::~EffectHandle()
9012{
Steve Block3856b092011-10-20 11:56:00 +01009013 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009014
9015 if (mEffect == 0) {
9016 mDestroyed = true;
9017 return;
9018 }
9019 mEffect->lock();
9020 mDestroyed = true;
9021 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009022 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009023}
9024
9025status_t AudioFlinger::EffectHandle::enable()
9026{
Steve Block3856b092011-10-20 11:56:00 +01009027 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009028 if (!mHasControl) return INVALID_OPERATION;
9029 if (mEffect == 0) return DEAD_OBJECT;
9030
Eric Laurentdb7c0792011-08-10 10:37:50 -07009031 if (mEnabled) {
9032 return NO_ERROR;
9033 }
9034
Eric Laurent59255e42011-07-27 19:49:51 -07009035 mEnabled = true;
9036
9037 sp<ThreadBase> thread = mEffect->thread().promote();
9038 if (thread != 0) {
9039 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
9040 }
9041
9042 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
9043 if (mEffect->suspended()) {
9044 return NO_ERROR;
9045 }
9046
Eric Laurentdb7c0792011-08-10 10:37:50 -07009047 status_t status = mEffect->setEnabled(true);
9048 if (status != NO_ERROR) {
9049 if (thread != 0) {
9050 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9051 }
9052 mEnabled = false;
9053 }
9054 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009055}
9056
9057status_t AudioFlinger::EffectHandle::disable()
9058{
Steve Block3856b092011-10-20 11:56:00 +01009059 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009060 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07009061 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009062
Eric Laurentdb7c0792011-08-10 10:37:50 -07009063 if (!mEnabled) {
9064 return NO_ERROR;
9065 }
Eric Laurent59255e42011-07-27 19:49:51 -07009066 mEnabled = false;
9067
9068 if (mEffect->suspended()) {
9069 return NO_ERROR;
9070 }
9071
9072 status_t status = mEffect->setEnabled(false);
9073
9074 sp<ThreadBase> thread = mEffect->thread().promote();
9075 if (thread != 0) {
9076 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9077 }
9078
9079 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009080}
9081
9082void AudioFlinger::EffectHandle::disconnect()
9083{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009084 disconnect(true);
9085}
9086
Glenn Kasten58123c32012-02-03 10:32:24 -08009087void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009088{
Glenn Kasten58123c32012-02-03 10:32:24 -08009089 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009090 if (mEffect == 0) {
9091 return;
9092 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009093 // restore suspended effects if the disconnected handle was enabled and the last one.
9094 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009095 sp<ThreadBase> thread = mEffect->thread().promote();
9096 if (thread != 0) {
9097 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9098 }
Eric Laurent59255e42011-07-27 19:49:51 -07009099 }
9100
Mathias Agopian65ab4712010-07-14 17:59:35 -07009101 // release sp on module => module destructor can be called now
9102 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009103 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08009104 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08009105 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009106 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
9107 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08009108 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08009109 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07009110 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
9111 mClient.clear();
9112 }
9113}
9114
Eric Laurent25f43952010-07-28 05:40:18 -07009115status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
9116 uint32_t cmdSize,
9117 void *pCmdData,
9118 uint32_t *replySize,
9119 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009120{
Glenn Kastencbe4b362012-10-18 15:51:03 -07009121 ALOGVV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
9122 cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07009123
9124 // only get parameter command is permitted for applications not controlling the effect
9125 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
9126 return INVALID_OPERATION;
9127 }
9128 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009129 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009130
9131 // handle commands that are not forwarded transparently to effect engine
9132 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
9133 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
9134 // no risk to block the whole media server process or mixer threads is we are stuck here
9135 Mutex::Autolock _l(mCblk->lock);
9136 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
9137 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
9138 mCblk->serverIndex = 0;
9139 mCblk->clientIndex = 0;
9140 return BAD_VALUE;
9141 }
9142 status_t status = NO_ERROR;
9143 while (mCblk->serverIndex < mCblk->clientIndex) {
9144 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07009145 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009146 int *p = (int *)(mBuffer + mCblk->serverIndex);
9147 int size = *p++;
9148 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009149 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009150 break;
9151 }
9152 effect_param_t *param = (effect_param_t *)p;
9153 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009154 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009155 mCblk->serverIndex += size;
9156 continue;
9157 }
Eric Laurent25f43952010-07-28 05:40:18 -07009158 uint32_t psize = sizeof(effect_param_t) +
9159 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
9160 param->vsize;
9161 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
9162 psize,
9163 p,
9164 &rsize,
9165 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07009166 // stop at first error encountered
9167 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009168 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07009169 *(int *)pReplyData = reply;
9170 break;
9171 } else if (reply != NO_ERROR) {
9172 *(int *)pReplyData = reply;
9173 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009174 }
9175 mCblk->serverIndex += size;
9176 }
9177 mCblk->serverIndex = 0;
9178 mCblk->clientIndex = 0;
9179 return status;
9180 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009181 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009182 return enable();
9183 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009184 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009185 return disable();
9186 }
9187
9188 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9189}
9190
Eric Laurent59255e42011-07-27 19:49:51 -07009191void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009192{
Steve Block3856b092011-10-20 11:56:00 +01009193 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009194
9195 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07009196 mEnabled = enabled;
9197
Mathias Agopian65ab4712010-07-14 17:59:35 -07009198 if (signal && mEffectClient != 0) {
9199 mEffectClient->controlStatusChanged(hasControl);
9200 }
9201}
9202
Eric Laurent25f43952010-07-28 05:40:18 -07009203void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
9204 uint32_t cmdSize,
9205 void *pCmdData,
9206 uint32_t replySize,
9207 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009208{
9209 if (mEffectClient != 0) {
9210 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9211 }
9212}
9213
9214
9215
9216void AudioFlinger::EffectHandle::setEnabled(bool enabled)
9217{
9218 if (mEffectClient != 0) {
9219 mEffectClient->enableStatusChanged(enabled);
9220 }
9221}
9222
9223status_t AudioFlinger::EffectHandle::onTransact(
9224 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9225{
9226 return BnEffect::onTransact(code, data, reply, flags);
9227}
9228
9229
9230void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
9231{
Glenn Kastena0d68332012-01-27 16:47:15 -08009232 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009233
9234 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08009235 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07009236 mPriority,
9237 mHasControl,
9238 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009239 mCblk ? mCblk->clientIndex : 0,
9240 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07009241 );
9242
9243 if (locked) {
9244 mCblk->lock.unlock();
9245 }
9246}
9247
9248#undef LOG_TAG
9249#define LOG_TAG "AudioFlinger::EffectChain"
9250
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009251AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009252 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009253 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07009254 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9255 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009256{
Dima Zavinfce7a472011-04-19 22:30:36 -07009257 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009258 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009259 return;
9260 }
9261 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9262 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009263}
9264
9265AudioFlinger::EffectChain::~EffectChain()
9266{
9267 if (mOwnInBuffer) {
9268 delete mInBuffer;
9269 }
9270
9271}
9272
Eric Laurent59255e42011-07-27 19:49:51 -07009273// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009274sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009275{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009276 size_t size = mEffects.size();
9277
9278 for (size_t i = 0; i < size; i++) {
9279 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009280 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009281 }
9282 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009283 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009284}
9285
Eric Laurent59255e42011-07-27 19:49:51 -07009286// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009287sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009288{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009289 size_t size = mEffects.size();
9290
9291 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009292 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9293 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009294 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009295 }
9296 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009297 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009298}
9299
Eric Laurent59255e42011-07-27 19:49:51 -07009300// getEffectFromType_l() must be called with ThreadBase::mLock held
9301sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9302 const effect_uuid_t *type)
9303{
Eric Laurent59255e42011-07-27 19:49:51 -07009304 size_t size = mEffects.size();
9305
9306 for (size_t i = 0; i < size; i++) {
9307 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009308 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009309 }
9310 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009311 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009312}
9313
Eric Laurent91b14c42012-05-30 12:30:29 -07009314void AudioFlinger::EffectChain::clearInputBuffer()
9315{
9316 Mutex::Autolock _l(mLock);
9317 sp<ThreadBase> thread = mThread.promote();
9318 if (thread == 0) {
9319 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9320 return;
9321 }
9322 clearInputBuffer_l(thread);
9323}
9324
9325// Must be called with EffectChain::mLock locked
9326void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9327{
9328 size_t numSamples = thread->frameCount() * thread->channelCount();
9329 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9330
9331}
9332
Mathias Agopian65ab4712010-07-14 17:59:35 -07009333// Must be called with EffectChain::mLock locked
9334void AudioFlinger::EffectChain::process_l()
9335{
Eric Laurentdac69112010-09-28 14:09:57 -07009336 sp<ThreadBase> thread = mThread.promote();
9337 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009338 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009339 return;
9340 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009341 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9342 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009343 // always process effects unless no more tracks are on the session and the effect tail
9344 // has been rendered
9345 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009346 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009347 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009348
Eric Laurent544fe9b2011-11-11 15:42:52 -08009349 if (!tracksOnSession && mTailBufferCount == 0) {
9350 doProcess = false;
9351 }
9352
9353 if (activeTrackCnt() == 0) {
9354 // if no track is active and the effect tail has not been rendered,
9355 // the input buffer must be cleared here as the mixer process will not do it
9356 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009357 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009358 if (mTailBufferCount > 0) {
9359 mTailBufferCount--;
9360 }
9361 }
9362 }
Eric Laurentdac69112010-09-28 14:09:57 -07009363 }
9364
Mathias Agopian65ab4712010-07-14 17:59:35 -07009365 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009366 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009367 for (size_t i = 0; i < size; i++) {
9368 mEffects[i]->process();
9369 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009370 }
9371 for (size_t i = 0; i < size; i++) {
9372 mEffects[i]->updateState();
9373 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009374}
9375
Eric Laurentcab11242010-07-15 12:50:15 -07009376// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009377status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009378{
9379 effect_descriptor_t desc = effect->desc();
9380 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9381
9382 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009383 effect->setChain(this);
9384 sp<ThreadBase> thread = mThread.promote();
9385 if (thread == 0) {
9386 return NO_INIT;
9387 }
9388 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009389
9390 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9391 // Auxiliary effects are inserted at the beginning of mEffects vector as
9392 // they are processed first and accumulated in chain input buffer
9393 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009394
Mathias Agopian65ab4712010-07-14 17:59:35 -07009395 // the input buffer for auxiliary effect contains mono samples in
9396 // 32 bit format. This is to avoid saturation in AudoMixer
9397 // accumulation stage. Saturation is done in EffectModule::process() before
9398 // calling the process in effect engine
9399 size_t numSamples = thread->frameCount();
9400 int32_t *buffer = new int32_t[numSamples];
9401 memset(buffer, 0, numSamples * sizeof(int32_t));
9402 effect->setInBuffer((int16_t *)buffer);
9403 // auxiliary effects output samples to chain input buffer for further processing
9404 // by insert effects
9405 effect->setOutBuffer(mInBuffer);
9406 } else {
9407 // Insert effects are inserted at the end of mEffects vector as they are processed
9408 // after track and auxiliary effects.
9409 // Insert effect order as a function of indicated preference:
9410 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9411 // another effect is present
9412 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9413 // last effect claiming first position
9414 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9415 // first effect claiming last position
9416 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9417 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9418 // already present
9419
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009420 size_t size = mEffects.size();
9421 size_t idx_insert = size;
9422 ssize_t idx_insert_first = -1;
9423 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009424
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009425 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009426 effect_descriptor_t d = mEffects[i]->desc();
9427 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9428 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9429 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9430 // check invalid effect chaining combinations
9431 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9432 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009433 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009434 return INVALID_OPERATION;
9435 }
9436 // remember position of first insert effect and by default
9437 // select this as insert position for new effect
9438 if (idx_insert == size) {
9439 idx_insert = i;
9440 }
9441 // remember position of last insert effect claiming
9442 // first position
9443 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9444 idx_insert_first = i;
9445 }
9446 // remember position of first insert effect claiming
9447 // last position
9448 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9449 idx_insert_last == -1) {
9450 idx_insert_last = i;
9451 }
9452 }
9453 }
9454
9455 // modify idx_insert from first position if needed
9456 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9457 if (idx_insert_last != -1) {
9458 idx_insert = idx_insert_last;
9459 } else {
9460 idx_insert = size;
9461 }
9462 } else {
9463 if (idx_insert_first != -1) {
9464 idx_insert = idx_insert_first + 1;
9465 }
9466 }
9467
9468 // always read samples from chain input buffer
9469 effect->setInBuffer(mInBuffer);
9470
9471 // if last effect in the chain, output samples to chain
9472 // output buffer, otherwise to chain input buffer
9473 if (idx_insert == size) {
9474 if (idx_insert != 0) {
9475 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9476 mEffects[idx_insert-1]->configure();
9477 }
9478 effect->setOutBuffer(mOutBuffer);
9479 } else {
9480 effect->setOutBuffer(mInBuffer);
9481 }
9482 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009483
Steve Block3856b092011-10-20 11:56:00 +01009484 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009485 }
9486 effect->configure();
9487 return NO_ERROR;
9488}
9489
Eric Laurentcab11242010-07-15 12:50:15 -07009490// removeEffect_l() must be called with PlaybackThread::mLock held
9491size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009492{
9493 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009494 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009495 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9496
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009497 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009498 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009499 // calling stop here will remove pre-processing effect from the audio HAL.
9500 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9501 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009502 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9503 mEffects[i]->state() == EffectModule::STOPPING) {
9504 mEffects[i]->stop();
9505 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009506 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9507 delete[] effect->inBuffer();
9508 } else {
9509 if (i == size - 1 && i != 0) {
9510 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9511 mEffects[i - 1]->configure();
9512 }
9513 }
9514 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009515 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009516 break;
9517 }
9518 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009519
9520 return mEffects.size();
9521}
9522
Eric Laurentcab11242010-07-15 12:50:15 -07009523// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009524void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009525{
9526 size_t size = mEffects.size();
9527 for (size_t i = 0; i < size; i++) {
9528 mEffects[i]->setDevice(device);
9529 }
9530}
9531
Eric Laurentcab11242010-07-15 12:50:15 -07009532// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009533void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009534{
9535 size_t size = mEffects.size();
9536 for (size_t i = 0; i < size; i++) {
9537 mEffects[i]->setMode(mode);
9538 }
9539}
9540
Eric Laurent2e9b0f22012-08-31 17:44:06 -07009541// setAudioSource_l() must be called with PlaybackThread::mLock held
9542void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
9543{
9544 size_t size = mEffects.size();
9545 for (size_t i = 0; i < size; i++) {
9546 mEffects[i]->setAudioSource(source);
9547 }
9548}
9549
Eric Laurentcab11242010-07-15 12:50:15 -07009550// setVolume_l() must be called with PlaybackThread::mLock held
9551bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009552{
9553 uint32_t newLeft = *left;
9554 uint32_t newRight = *right;
9555 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009556 int ctrlIdx = -1;
9557 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009558
Eric Laurentcab11242010-07-15 12:50:15 -07009559 // first update volume controller
9560 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009561 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009562 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9563 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009564 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009565 break;
9566 }
9567 }
9568
9569 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009570 if (hasControl) {
9571 *left = mNewLeftVolume;
9572 *right = mNewRightVolume;
9573 }
9574 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009575 }
9576
9577 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009578 mLeftVolume = newLeft;
9579 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009580
9581 // second get volume update from volume controller
9582 if (ctrlIdx >= 0) {
9583 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009584 mNewLeftVolume = newLeft;
9585 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009586 }
9587 // then indicate volume to all other effects in chain.
9588 // Pass altered volume to effects before volume controller
9589 // and requested volume to effects after controller
9590 uint32_t lVol = newLeft;
9591 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009592
Mathias Agopian65ab4712010-07-14 17:59:35 -07009593 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009594 if ((int)i == ctrlIdx) continue;
9595 // this also works for ctrlIdx == -1 when there is no volume controller
9596 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009597 lVol = *left;
9598 rVol = *right;
9599 }
9600 mEffects[i]->setVolume(&lVol, &rVol, false);
9601 }
9602 *left = newLeft;
9603 *right = newRight;
9604
9605 return hasControl;
9606}
9607
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009608void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009609{
9610 const size_t SIZE = 256;
9611 char buffer[SIZE];
9612 String8 result;
9613
9614 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9615 result.append(buffer);
9616
9617 bool locked = tryLock(mLock);
9618 // failed to lock - AudioFlinger is probably deadlocked
9619 if (!locked) {
9620 result.append("\tCould not lock mutex:\n");
9621 }
9622
Eric Laurentcab11242010-07-15 12:50:15 -07009623 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9624 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009625 mEffects.size(),
9626 (uint32_t)mInBuffer,
9627 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009628 mActiveTrackCnt);
9629 result.append(buffer);
9630 write(fd, result.string(), result.size());
9631
9632 for (size_t i = 0; i < mEffects.size(); ++i) {
9633 sp<EffectModule> effect = mEffects[i];
9634 if (effect != 0) {
9635 effect->dump(fd, args);
9636 }
9637 }
9638
9639 if (locked) {
9640 mLock.unlock();
9641 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009642}
9643
Eric Laurent59255e42011-07-27 19:49:51 -07009644// must be called with ThreadBase::mLock held
9645void AudioFlinger::EffectChain::setEffectSuspended_l(
9646 const effect_uuid_t *type, bool suspend)
9647{
9648 sp<SuspendedEffectDesc> desc;
9649 // use effect type UUID timelow as key as there is no real risk of identical
9650 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009651 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009652 if (suspend) {
9653 if (index >= 0) {
9654 desc = mSuspendedEffects.valueAt(index);
9655 } else {
9656 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -08009657 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07009658 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009659 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009660 }
9661 if (desc->mRefCount++ == 0) {
9662 sp<EffectModule> effect = getEffectIfEnabled(type);
9663 if (effect != 0) {
9664 desc->mEffect = effect;
9665 effect->setSuspended(true);
9666 effect->setEnabled(false);
9667 }
9668 }
9669 } else {
9670 if (index < 0) {
9671 return;
9672 }
9673 desc = mSuspendedEffects.valueAt(index);
9674 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009675 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009676 desc->mRefCount = 1;
9677 }
9678 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009679 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009680 if (desc->mEffect != 0) {
9681 sp<EffectModule> effect = desc->mEffect.promote();
9682 if (effect != 0) {
9683 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009684 effect->lock();
9685 EffectHandle *handle = effect->controlHandle_l();
9686 if (handle != NULL && !handle->destroyed_l()) {
9687 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009688 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009689 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009690 }
9691 desc->mEffect.clear();
9692 }
9693 mSuspendedEffects.removeItemsAt(index);
9694 }
9695 }
9696}
9697
9698// must be called with ThreadBase::mLock held
9699void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9700{
9701 sp<SuspendedEffectDesc> desc;
9702
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009703 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009704 if (suspend) {
9705 if (index >= 0) {
9706 desc = mSuspendedEffects.valueAt(index);
9707 } else {
9708 desc = new SuspendedEffectDesc();
9709 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009710 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009711 }
9712 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009713 Vector< sp<EffectModule> > effects;
9714 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009715 for (size_t i = 0; i < effects.size(); i++) {
9716 setEffectSuspended_l(&effects[i]->desc().type, true);
9717 }
9718 }
9719 } else {
9720 if (index < 0) {
9721 return;
9722 }
9723 desc = mSuspendedEffects.valueAt(index);
9724 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009725 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009726 desc->mRefCount = 1;
9727 }
9728 if (--desc->mRefCount == 0) {
9729 Vector<const effect_uuid_t *> types;
9730 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9731 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9732 continue;
9733 }
9734 types.add(&mSuspendedEffects.valueAt(i)->mType);
9735 }
9736 for (size_t i = 0; i < types.size(); i++) {
9737 setEffectSuspended_l(types[i], false);
9738 }
Steve Block3856b092011-10-20 11:56:00 +01009739 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009740 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9741 }
9742 }
9743}
9744
Eric Laurent6bffdb82011-09-23 08:40:41 -07009745
9746// The volume effect is used for automated tests only
9747#ifndef OPENSL_ES_H_
9748static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9749 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9750const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9751#endif //OPENSL_ES_H_
9752
Eric Laurentdb7c0792011-08-10 10:37:50 -07009753bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9754{
9755 // auxiliary effects and visualizer are never suspended on output mix
9756 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9757 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009758 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9759 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009760 return false;
9761 }
9762 return true;
9763}
9764
Glenn Kastend0539712012-01-30 12:56:03 -08009765void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009766{
Glenn Kastend0539712012-01-30 12:56:03 -08009767 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009768 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009769 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9770 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009771 }
Eric Laurent59255e42011-07-27 19:49:51 -07009772 }
Eric Laurent59255e42011-07-27 19:49:51 -07009773}
9774
9775sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9776 const effect_uuid_t *type)
9777{
Glenn Kasten090f0192012-01-30 13:00:02 -08009778 sp<EffectModule> effect = getEffectFromType_l(type);
9779 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009780}
9781
9782void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9783 bool enabled)
9784{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009785 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009786 if (enabled) {
9787 if (index < 0) {
9788 // if the effect is not suspend check if all effects are suspended
9789 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9790 if (index < 0) {
9791 return;
9792 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009793 if (!isEffectEligibleForSuspend(effect->desc())) {
9794 return;
9795 }
Eric Laurent59255e42011-07-27 19:49:51 -07009796 setEffectSuspended_l(&effect->desc().type, enabled);
9797 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009798 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009799 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009800 return;
9801 }
Eric Laurent59255e42011-07-27 19:49:51 -07009802 }
Steve Block3856b092011-10-20 11:56:00 +01009803 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009804 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009805 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9806 // if effect is requested to suspended but was not yet enabled, supend it now.
9807 if (desc->mEffect == 0) {
9808 desc->mEffect = effect;
9809 effect->setEnabled(false);
9810 effect->setSuspended(true);
9811 }
9812 } else {
9813 if (index < 0) {
9814 return;
9815 }
Steve Block3856b092011-10-20 11:56:00 +01009816 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009817 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009818 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9819 desc->mEffect.clear();
9820 effect->setSuspended(false);
9821 }
9822}
9823
Mathias Agopian65ab4712010-07-14 17:59:35 -07009824#undef LOG_TAG
9825#define LOG_TAG "AudioFlinger"
9826
9827// ----------------------------------------------------------------------------
9828
9829status_t AudioFlinger::onTransact(
9830 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9831{
9832 return BnAudioFlinger::onTransact(code, data, reply, flags);
9833}
9834
Mathias Agopian65ab4712010-07-14 17:59:35 -07009835}; // namespace android