blob: 9baa8300551637c749e20c4b6e33231908f33f40 [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
Glenn Kastena2049222012-06-22 17:21:07 -0700426 if (locked) {
427 mLock.unlock();
428 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700429 }
430 return NO_ERROR;
431}
432
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800433sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
434{
435 // If pid is already in the mClients wp<> map, then use that entry
436 // (for which promote() is always != 0), otherwise create a new entry and Client.
437 sp<Client> client = mClients.valueFor(pid).promote();
438 if (client == 0) {
439 client = new Client(this, pid);
440 mClients.add(pid, client);
441 }
442
443 return client;
444}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700445
446// IAudioFlinger interface
447
448
449sp<IAudioTrack> AudioFlinger::createTrack(
450 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800451 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800453 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700454 audio_channel_mask_t channelMask,
Glenn Kasten7da35f22012-11-14 12:54:39 -0800455 size_t frameCount,
Glenn Kastenc2674152012-11-06 15:03:34 -0800456 IAudioFlinger::track_flags_t *flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700457 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800458 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800459 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700460 int *sessionId,
461 status_t *status)
462{
463 sp<PlaybackThread::Track> track;
464 sp<TrackHandle> trackHandle;
465 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700466 status_t lStatus;
467 int lSessionId;
468
Glenn Kasten263709e2012-01-06 08:40:01 -0800469 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
470 // but if someone uses binder directly they could bypass that and cause us to crash
471 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000472 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700473 lStatus = BAD_VALUE;
474 goto Exit;
475 }
476
Glenn Kasten520a9af2012-06-21 12:56:37 -0700477 // client is responsible for conversion of 8-bit PCM to 16-bit PCM,
478 // and we don't yet support 8.24 or 32-bit PCM
479 if (audio_is_linear_pcm(format) && format != AUDIO_FORMAT_PCM_16_BIT) {
480 ALOGE("createTrack() invalid format %d", format);
481 lStatus = BAD_VALUE;
482 goto Exit;
483 }
484
Mathias Agopian65ab4712010-07-14 17:59:35 -0700485 {
486 Mutex::Autolock _l(mLock);
487 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700488 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700489 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000490 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700491 lStatus = BAD_VALUE;
492 goto Exit;
493 }
494
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800495 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700496
Steve Block3856b092011-10-20 11:56:00 +0100497 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700498 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700499 // check if an effect chain with the same session ID is present on another
500 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700501 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700502 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
503 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700504 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700505 if (sessions & PlaybackThread::EFFECT_SESSION) {
506 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700507 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700508 }
Eric Laurentde070132010-07-13 04:45:46 -0700509 }
510 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700511 lSessionId = *sessionId;
512 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700513 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700514 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700515 if (sessionId != NULL) {
516 *sessionId = lSessionId;
517 }
518 }
Steve Block3856b092011-10-20 11:56:00 +0100519 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700520
521 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800522 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700523
524 // move effect chain to this output thread if an effect on same session was waiting
525 // for a track to be created
526 if (lStatus == NO_ERROR && effectThread != NULL) {
527 Mutex::Autolock _dl(thread->mLock);
528 Mutex::Autolock _sl(effectThread->mLock);
529 moveEffectChain_l(lSessionId, effectThread, thread, true);
530 }
Eric Laurenta011e352012-03-29 15:51:43 -0700531
532 // Look for sync events awaiting for a session to be used.
533 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
534 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
535 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700536 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700537 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700538 } else {
539 mPendingSyncEvents[i]->cancel();
540 }
Eric Laurenta011e352012-03-29 15:51:43 -0700541 mPendingSyncEvents.removeAt(i);
542 i--;
543 }
544 }
545 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700546 }
547 if (lStatus == NO_ERROR) {
548 trackHandle = new TrackHandle(track);
549 } else {
550 // remove local strong reference to Client before deleting the Track so that the Client
551 // destructor is called by the TrackBase destructor with mLock held
552 client.clear();
553 track.clear();
554 }
555
556Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700557 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558 *status = lStatus;
559 }
560 return trackHandle;
561}
562
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800563uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700564{
565 Mutex::Autolock _l(mLock);
566 PlaybackThread *thread = checkPlaybackThread_l(output);
567 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000568 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700569 return 0;
570 }
571 return thread->sampleRate();
572}
573
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800574int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575{
576 Mutex::Autolock _l(mLock);
577 PlaybackThread *thread = checkPlaybackThread_l(output);
578 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000579 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700580 return 0;
581 }
582 return thread->channelCount();
583}
584
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800585audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700586{
587 Mutex::Autolock _l(mLock);
588 PlaybackThread *thread = checkPlaybackThread_l(output);
589 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000590 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800591 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700592 }
593 return thread->format();
594}
595
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800596size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700597{
598 Mutex::Autolock _l(mLock);
599 PlaybackThread *thread = checkPlaybackThread_l(output);
600 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000601 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700602 return 0;
603 }
Glenn Kasten58912562012-04-03 10:45:00 -0700604 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
605 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700606 return thread->frameCount();
607}
608
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800609uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700610{
611 Mutex::Autolock _l(mLock);
612 PlaybackThread *thread = checkPlaybackThread_l(output);
613 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000614 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700615 return 0;
616 }
617 return thread->latency();
618}
619
620status_t AudioFlinger::setMasterVolume(float value)
621{
Eric Laurenta1884f92011-08-23 08:25:03 -0700622 status_t ret = initCheck();
623 if (ret != NO_ERROR) {
624 return ret;
625 }
626
Mathias Agopian65ab4712010-07-14 17:59:35 -0700627 // check calling permissions
628 if (!settingsAllowed()) {
629 return PERMISSION_DENIED;
630 }
631
Eric Laurenta4c5a552012-03-29 10:12:40 -0700632 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700633 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700634
John Grossmanee578c02012-07-23 17:05:46 -0700635 // Set master volume in the HALs which support it.
636 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
637 AutoMutex lock(mHardwareLock);
638 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800639
John Grossmanee578c02012-07-23 17:05:46 -0700640 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
641 if (dev->canSetMasterVolume()) {
642 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800643 }
John Grossmanee578c02012-07-23 17:05:46 -0700644 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700645 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700646
John Grossmanee578c02012-07-23 17:05:46 -0700647 // Now set the master volume in each playback thread. Playback threads
648 // assigned to HALs which do not have master volume support will apply
649 // master volume during the mix operation. Threads with HALs which do
650 // support master volume will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800651 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700652 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700653
654 return NO_ERROR;
655}
656
Glenn Kastenf78aee72012-01-04 11:00:47 -0800657status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700658{
Eric Laurenta1884f92011-08-23 08:25:03 -0700659 status_t ret = initCheck();
660 if (ret != NO_ERROR) {
661 return ret;
662 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700663
664 // check calling permissions
665 if (!settingsAllowed()) {
666 return PERMISSION_DENIED;
667 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800668 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000669 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700670 return BAD_VALUE;
671 }
672
673 { // scope for the lock
674 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700675 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700676 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700677 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700678 mHardwareStatus = AUDIO_HW_IDLE;
679 }
680
681 if (NO_ERROR == ret) {
682 Mutex::Autolock _l(mLock);
683 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800684 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700685 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700686 }
687
688 return ret;
689}
690
691status_t AudioFlinger::setMicMute(bool state)
692{
Eric Laurenta1884f92011-08-23 08:25:03 -0700693 status_t ret = initCheck();
694 if (ret != NO_ERROR) {
695 return ret;
696 }
697
Mathias Agopian65ab4712010-07-14 17:59:35 -0700698 // check calling permissions
699 if (!settingsAllowed()) {
700 return PERMISSION_DENIED;
701 }
702
703 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700704 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700705 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700706 ret = dev->set_mic_mute(dev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700707 mHardwareStatus = AUDIO_HW_IDLE;
708 return ret;
709}
710
711bool AudioFlinger::getMicMute() const
712{
Eric Laurenta1884f92011-08-23 08:25:03 -0700713 status_t ret = initCheck();
714 if (ret != NO_ERROR) {
715 return false;
716 }
717
Dima Zavinfce7a472011-04-19 22:30:36 -0700718 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800719 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700720 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700721 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700722 dev->get_mic_mute(dev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700723 mHardwareStatus = AUDIO_HW_IDLE;
724 return state;
725}
726
727status_t AudioFlinger::setMasterMute(bool muted)
728{
John Grossmand8f178d2012-07-20 14:51:35 -0700729 status_t ret = initCheck();
730 if (ret != NO_ERROR) {
731 return ret;
732 }
733
Mathias Agopian65ab4712010-07-14 17:59:35 -0700734 // check calling permissions
735 if (!settingsAllowed()) {
736 return PERMISSION_DENIED;
737 }
738
John Grossmanee578c02012-07-23 17:05:46 -0700739 Mutex::Autolock _l(mLock);
740 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700741
John Grossmanee578c02012-07-23 17:05:46 -0700742 // Set master mute in the HALs which support it.
743 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
744 AutoMutex lock(mHardwareLock);
745 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700746
John Grossmanee578c02012-07-23 17:05:46 -0700747 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
748 if (dev->canSetMasterMute()) {
749 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700750 }
John Grossmanee578c02012-07-23 17:05:46 -0700751 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700752 }
753
John Grossmanee578c02012-07-23 17:05:46 -0700754 // Now set the master mute in each playback thread. Playback threads
755 // assigned to HALs which do not have master mute support will apply master
756 // mute during the mix operation. Threads with HALs which do support master
757 // mute will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800758 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700759 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700760
761 return NO_ERROR;
762}
763
764float AudioFlinger::masterVolume() const
765{
Glenn Kasten98067102011-12-13 11:47:54 -0800766 Mutex::Autolock _l(mLock);
767 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700768}
769
770bool AudioFlinger::masterMute() const
771{
Glenn Kasten98067102011-12-13 11:47:54 -0800772 Mutex::Autolock _l(mLock);
773 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700774}
775
John Grossman4ff14ba2012-02-08 16:37:41 -0800776float AudioFlinger::masterVolume_l() const
777{
John Grossman4ff14ba2012-02-08 16:37:41 -0800778 return mMasterVolume;
779}
780
John Grossmand8f178d2012-07-20 14:51:35 -0700781bool AudioFlinger::masterMute_l() const
782{
John Grossmanee578c02012-07-23 17:05:46 -0700783 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700784}
785
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800786status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
787 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700788{
789 // check calling permissions
790 if (!settingsAllowed()) {
791 return PERMISSION_DENIED;
792 }
793
Glenn Kasten263709e2012-01-06 08:40:01 -0800794 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000795 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796 return BAD_VALUE;
797 }
798
799 AutoMutex lock(mLock);
800 PlaybackThread *thread = NULL;
801 if (output) {
802 thread = checkPlaybackThread_l(output);
803 if (thread == NULL) {
804 return BAD_VALUE;
805 }
806 }
807
808 mStreamTypes[stream].volume = value;
809
810 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800811 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700812 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700813 }
814 } else {
815 thread->setStreamVolume(stream, value);
816 }
817
818 return NO_ERROR;
819}
820
Glenn Kastenfff6d712012-01-12 16:38:12 -0800821status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822{
823 // check calling permissions
824 if (!settingsAllowed()) {
825 return PERMISSION_DENIED;
826 }
827
Glenn Kasten263709e2012-01-06 08:40:01 -0800828 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700829 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000830 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700831 return BAD_VALUE;
832 }
833
Eric Laurent93575202011-01-18 18:39:02 -0800834 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835 mStreamTypes[stream].mute = muted;
836 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700837 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838
839 return NO_ERROR;
840}
841
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800842float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843{
Glenn Kasten263709e2012-01-06 08:40:01 -0800844 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845 return 0.0f;
846 }
847
848 AutoMutex lock(mLock);
849 float volume;
850 if (output) {
851 PlaybackThread *thread = checkPlaybackThread_l(output);
852 if (thread == NULL) {
853 return 0.0f;
854 }
855 volume = thread->streamVolume(stream);
856 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800857 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700858 }
859
860 return volume;
861}
862
Glenn Kastenfff6d712012-01-12 16:38:12 -0800863bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700864{
Glenn Kasten263709e2012-01-06 08:40:01 -0800865 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700866 return true;
867 }
868
Glenn Kasten6637baa2012-01-09 09:40:36 -0800869 AutoMutex lock(mLock);
870 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700871}
872
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800873status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700874{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800875 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700876 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
877 // check calling permissions
878 if (!settingsAllowed()) {
879 return PERMISSION_DENIED;
880 }
881
Mathias Agopian65ab4712010-07-14 17:59:35 -0700882 // ioHandle == 0 means the parameters are global to the audio hardware interface
883 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700884 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700885 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800886 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700887 AutoMutex lock(mHardwareLock);
888 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
889 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
890 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
891 status_t result = dev->set_parameters(dev, keyValuePairs.string());
892 final_result = result ?: final_result;
893 }
894 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800895 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700896 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
897 AudioParameter param = AudioParameter(keyValuePairs);
898 String8 value;
899 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700900 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
901 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700902 for (size_t i = 0; i < mRecordThreads.size(); i++) {
903 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurent88959252012-08-28 14:26:53 -0700904 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -0700905 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
906 // collect all of the thread's session IDs
907 KeyedVector<int, bool> ids = thread->sessionIds();
908 // suspend effects associated with those session IDs
909 for (size_t j = 0; j < ids.size(); ++j) {
910 int sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700911 thread->setEffectSuspended(FX_IID_AEC,
912 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700913 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700914 thread->setEffectSuspended(FX_IID_NS,
915 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700916 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700917 }
918 }
Eric Laurentbee53372011-08-29 12:42:48 -0700919 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700920 }
921 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700922 String8 screenState;
923 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
924 bool isOff = screenState == "off";
925 if (isOff != (gScreenState & 1)) {
926 gScreenState = ((gScreenState & ~1) + 2) | isOff;
927 }
928 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700929 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700930 }
931
932 // hold a strong ref on thread in case closeOutput() or closeInput() is called
933 // and the thread is exited once the lock is released
934 sp<ThreadBase> thread;
935 {
936 Mutex::Autolock _l(mLock);
937 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -0700938 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700939 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800940 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700941 // indicate output device change to all input threads for pre processing
942 AudioParameter param = AudioParameter(keyValuePairs);
943 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700944 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
945 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700946 for (size_t i = 0; i < mRecordThreads.size(); i++) {
947 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
948 }
949 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700950 }
951 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800952 if (thread != 0) {
953 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700954 }
955 return BAD_VALUE;
956}
957
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800958String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700959{
Glenn Kastencbe4b362012-10-18 15:51:03 -0700960 ALOGVV("getParameters() io %d, keys %s, tid %d, calling pid %d",
961 ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700962
Eric Laurenta4c5a552012-03-29 10:12:40 -0700963 Mutex::Autolock _l(mLock);
964
Mathias Agopian65ab4712010-07-14 17:59:35 -0700965 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700966 String8 out_s8;
967
Dima Zavin799a70e2011-04-18 16:57:27 -0700968 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800969 char *s;
970 {
971 AutoMutex lock(mHardwareLock);
972 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700973 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800974 s = dev->get_parameters(dev, keys.string());
975 mHardwareStatus = AUDIO_HW_IDLE;
976 }
John Grossmanef7740b2012-02-09 11:28:36 -0800977 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700978 free(s);
979 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700980 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700981 }
982
Mathias Agopian65ab4712010-07-14 17:59:35 -0700983 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
984 if (playbackThread != NULL) {
985 return playbackThread->getParameters(keys);
986 }
987 RecordThread *recordThread = checkRecordThread_l(ioHandle);
988 if (recordThread != NULL) {
989 return recordThread->getParameters(keys);
990 }
991 return String8("");
992}
993
Glenn Kastendd8104c2012-07-02 12:42:44 -0700994size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
995 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700996{
Eric Laurenta1884f92011-08-23 08:25:03 -0700997 status_t ret = initCheck();
998 if (ret != NO_ERROR) {
999 return 0;
1000 }
1001
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001002 AutoMutex lock(mHardwareLock);
1003 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001004 struct audio_config config = {
1005 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -07001006 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07001007 format: format,
1008 };
John Grossmanee578c02012-07-23 17:05:46 -07001009 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1010 size_t size = dev->get_input_buffer_size(dev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001011 mHardwareStatus = AUDIO_HW_IDLE;
1012 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001013}
1014
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001015unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001016{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001017 Mutex::Autolock _l(mLock);
1018
1019 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1020 if (recordThread != NULL) {
1021 return recordThread->getInputFramesLost();
1022 }
1023 return 0;
1024}
1025
1026status_t AudioFlinger::setVoiceVolume(float value)
1027{
Eric Laurenta1884f92011-08-23 08:25:03 -07001028 status_t ret = initCheck();
1029 if (ret != NO_ERROR) {
1030 return ret;
1031 }
1032
Mathias Agopian65ab4712010-07-14 17:59:35 -07001033 // check calling permissions
1034 if (!settingsAllowed()) {
1035 return PERMISSION_DENIED;
1036 }
1037
1038 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001039 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001040 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001041 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001042 mHardwareStatus = AUDIO_HW_IDLE;
1043
1044 return ret;
1045}
1046
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001047status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1048 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001049{
1050 status_t status;
1051
1052 Mutex::Autolock _l(mLock);
1053
1054 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1055 if (playbackThread != NULL) {
1056 return playbackThread->getRenderPosition(halFrames, dspFrames);
1057 }
1058
1059 return BAD_VALUE;
1060}
1061
1062void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1063{
1064
1065 Mutex::Autolock _l(mLock);
1066
Glenn Kastenbb001922012-02-03 11:10:26 -08001067 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001068 if (mNotificationClients.indexOfKey(pid) < 0) {
1069 sp<NotificationClient> notificationClient = new NotificationClient(this,
1070 client,
1071 pid);
Steve Block3856b092011-10-20 11:56:00 +01001072 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001073
1074 mNotificationClients.add(pid, notificationClient);
1075
1076 sp<IBinder> binder = client->asBinder();
1077 binder->linkToDeath(notificationClient);
1078
1079 // the config change is always sent from playback or record threads to avoid deadlock
1080 // with AudioSystem::gLock
1081 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentef6be0b2012-09-13 11:18:23 -07001082 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001083 }
1084
1085 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentef6be0b2012-09-13 11:18:23 -07001086 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001087 }
1088 }
1089}
1090
1091void AudioFlinger::removeNotificationClient(pid_t pid)
1092{
1093 Mutex::Autolock _l(mLock);
1094
Glenn Kastena3b09252012-01-20 09:19:01 -08001095 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001096
Steve Block3856b092011-10-20 11:56:00 +01001097 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001098 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001099 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001100 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001101 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001102 ALOGV(" pid %d @ %d", ref->mPid, i);
1103 if (ref->mPid == pid) {
1104 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001105 mAudioSessionRefs.removeAt(i);
1106 delete ref;
1107 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001108 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001109 } else {
1110 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001111 }
1112 }
1113 if (removed) {
1114 purgeStaleEffects_l();
1115 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116}
1117
1118// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001119void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001120{
1121 size_t size = mNotificationClients.size();
1122 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001123 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1124 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001125 }
1126}
1127
1128// removeClient_l() must be called with AudioFlinger::mLock held
1129void AudioFlinger::removeClient_l(pid_t pid)
1130{
Glenn Kasten8af901c2012-11-01 11:11:38 -07001131 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(),
1132 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133 mClients.removeItem(pid);
1134}
1135
Eric Laurent717e1282012-06-29 16:36:52 -07001136// getEffectThread_l() must be called with AudioFlinger::mLock held
1137sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1138{
1139 sp<PlaybackThread> thread;
1140
1141 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1142 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1143 ALOG_ASSERT(thread == 0);
1144 thread = mPlaybackThreads.valueAt(i);
1145 }
1146 }
1147
1148 return thread;
1149}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001150
1151// ----------------------------------------------------------------------------
1152
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001153AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent88959252012-08-28 14:26:53 -07001154 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
Glenn Kasten2662ac92012-07-30 10:59:30 -07001155 : Thread(false /*canCallJava*/),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001156 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001157 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001158 // mChannelMask
1159 mChannelCount(0),
1160 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1161 mParamStatus(NO_ERROR),
Eric Laurent88959252012-08-28 14:26:53 -07001162 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
1163 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Glenn Kasten2662ac92012-07-30 10:59:30 -07001164 // mName will be set by concrete (non-virtual) subclass
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001165 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001166{
1167}
1168
1169AudioFlinger::ThreadBase::~ThreadBase()
1170{
1171 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001172 // do not lock the mutex in destructor
1173 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001174 if (mPowerManager != 0) {
1175 sp<IBinder> binder = mPowerManager->asBinder();
1176 binder->unlinkToDeath(mDeathRecipient);
1177 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001178}
1179
1180void AudioFlinger::ThreadBase::exit()
1181{
Steve Block3856b092011-10-20 11:56:00 +01001182 ALOGV("ThreadBase::exit");
Jean-Michel Trivi2fa114d2012-09-28 14:49:39 -07001183 // do any cleanup required for exit to succeed
1184 preExit();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001185 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001186 // This lock prevents the following race in thread (uniprocessor for illustration):
1187 // if (!exitPending()) {
1188 // // context switch from here to exit()
1189 // // exit() calls requestExit(), what exitPending() observes
1190 // // exit() calls signal(), which is dropped since no waiters
1191 // // context switch back from exit() to here
1192 // mWaitWorkCV.wait(...);
1193 // // now thread is hung
1194 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001195 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001196 requestExit();
Eric Laurent67d8ac32012-09-24 15:02:17 -07001197 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001198 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001199 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1200 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001201 requestExitAndWait();
1202}
1203
Mathias Agopian65ab4712010-07-14 17:59:35 -07001204status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1205{
1206 status_t status;
1207
Steve Block3856b092011-10-20 11:56:00 +01001208 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001209 Mutex::Autolock _l(mLock);
1210
1211 mNewParameters.add(keyValuePairs);
1212 mWaitWorkCV.signal();
1213 // wait condition with timeout in case the thread loop has exited
1214 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001215 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001216 status = mParamStatus;
1217 mWaitWorkCV.signal();
1218 } else {
1219 status = TIMED_OUT;
1220 }
1221 return status;
1222}
1223
Eric Laurentef6be0b2012-09-13 11:18:23 -07001224void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001225{
1226 Mutex::Autolock _l(mLock);
Eric Laurentef6be0b2012-09-13 11:18:23 -07001227 sendIoConfigEvent_l(event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001228}
1229
Eric Laurentef6be0b2012-09-13 11:18:23 -07001230// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
1231void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001232{
Eric Laurentef6be0b2012-09-13 11:18:23 -07001233 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
1234 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
Glenn Kasten8af901c2012-11-01 11:11:38 -07001235 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
1236 param);
Eric Laurentef6be0b2012-09-13 11:18:23 -07001237 mWaitWorkCV.signal();
1238}
1239
1240// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
1241void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
1242{
1243 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
1244 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
1245 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
1246 mConfigEvents.size(), pid, tid, prio);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001247 mWaitWorkCV.signal();
1248}
1249
1250void AudioFlinger::ThreadBase::processConfigEvents()
1251{
1252 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001253 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001254 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Eric Laurentef6be0b2012-09-13 11:18:23 -07001255 ConfigEvent *event = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001256 mConfigEvents.removeAt(0);
1257 // release mLock before locking AudioFlinger mLock: lock order is always
1258 // AudioFlinger then ThreadBase to avoid cross deadlock
1259 mLock.unlock();
Eric Laurentef6be0b2012-09-13 11:18:23 -07001260 switch(event->type()) {
1261 case CFG_EVENT_PRIO: {
1262 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
1263 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio());
1264 if (err != 0) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07001265 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; "
1266 "error %d",
Eric Laurentef6be0b2012-09-13 11:18:23 -07001267 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
1268 }
1269 } break;
1270 case CFG_EVENT_IO: {
1271 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
1272 mAudioFlinger->mLock.lock();
1273 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
1274 mAudioFlinger->mLock.unlock();
1275 } break;
1276 default:
1277 ALOGE("processConfigEvents() unknown event type %d", event->type());
1278 break;
1279 }
1280 delete event;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001281 mLock.lock();
1282 }
1283 mLock.unlock();
1284}
1285
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001286void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001287{
1288 const size_t SIZE = 256;
1289 char buffer[SIZE];
1290 String8 result;
1291
1292 bool locked = tryLock(mLock);
1293 if (!locked) {
1294 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1295 write(fd, buffer, strlen(buffer));
1296 }
1297
Eric Laurent612bbb52012-03-14 15:03:26 -07001298 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1299 result.append(buffer);
1300 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1301 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001302 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1303 result.append(buffer);
Glenn Kasten1127d652012-11-14 08:44:39 -08001304 snprintf(buffer, SIZE, "Sample rate: %u\n", mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001305 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001306 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1307 result.append(buffer);
1308 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001309 result.append(buffer);
1310 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1311 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001312 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1313 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001314 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1315 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001316 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001317 result.append(buffer);
1318
1319 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1320 result.append(buffer);
1321 result.append(" Index Command");
1322 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1323 snprintf(buffer, SIZE, "\n %02d ", i);
1324 result.append(buffer);
1325 result.append(mNewParameters[i]);
1326 }
1327
1328 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1329 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001330 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Eric Laurentef6be0b2012-09-13 11:18:23 -07001331 mConfigEvents[i]->dump(buffer, SIZE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001332 result.append(buffer);
1333 }
1334 result.append("\n");
1335
1336 write(fd, result.string(), result.size());
1337
1338 if (locked) {
1339 mLock.unlock();
1340 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001341}
1342
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001343void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001344{
1345 const size_t SIZE = 256;
1346 char buffer[SIZE];
1347 String8 result;
1348
1349 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1350 write(fd, buffer, strlen(buffer));
1351
1352 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1353 sp<EffectChain> chain = mEffectChains[i];
1354 if (chain != 0) {
1355 chain->dump(fd, args);
1356 }
1357 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001358}
1359
Eric Laurentfeb0db62011-07-22 09:04:31 -07001360void AudioFlinger::ThreadBase::acquireWakeLock()
1361{
1362 Mutex::Autolock _l(mLock);
1363 acquireWakeLock_l();
1364}
1365
1366void AudioFlinger::ThreadBase::acquireWakeLock_l()
1367{
1368 if (mPowerManager == 0) {
1369 // use checkService() to avoid blocking if power service is not up yet
1370 sp<IBinder> binder =
1371 defaultServiceManager()->checkService(String16("power"));
1372 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001373 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001374 } else {
1375 mPowerManager = interface_cast<IPowerManager>(binder);
1376 binder->linkToDeath(mDeathRecipient);
1377 }
1378 }
1379 if (mPowerManager != 0) {
1380 sp<IBinder> binder = new BBinder();
1381 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1382 binder,
1383 String16(mName));
1384 if (status == NO_ERROR) {
1385 mWakeLockToken = binder;
1386 }
Steve Block3856b092011-10-20 11:56:00 +01001387 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001388 }
1389}
1390
1391void AudioFlinger::ThreadBase::releaseWakeLock()
1392{
1393 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001394 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001395}
1396
1397void AudioFlinger::ThreadBase::releaseWakeLock_l()
1398{
1399 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001400 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001401 if (mPowerManager != 0) {
1402 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1403 }
1404 mWakeLockToken.clear();
1405 }
1406}
1407
1408void AudioFlinger::ThreadBase::clearPowerManager()
1409{
1410 Mutex::Autolock _l(mLock);
1411 releaseWakeLock_l();
1412 mPowerManager.clear();
1413}
1414
1415void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1416{
1417 sp<ThreadBase> thread = mThread.promote();
1418 if (thread != 0) {
1419 thread->clearPowerManager();
1420 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001421 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001422}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001423
Eric Laurent59255e42011-07-27 19:49:51 -07001424void AudioFlinger::ThreadBase::setEffectSuspended(
1425 const effect_uuid_t *type, bool suspend, int sessionId)
1426{
1427 Mutex::Autolock _l(mLock);
1428 setEffectSuspended_l(type, suspend, sessionId);
1429}
1430
1431void AudioFlinger::ThreadBase::setEffectSuspended_l(
1432 const effect_uuid_t *type, bool suspend, int sessionId)
1433{
Glenn Kasten090f0192012-01-30 13:00:02 -08001434 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001435 if (chain != 0) {
1436 if (type != NULL) {
1437 chain->setEffectSuspended_l(type, suspend);
1438 } else {
1439 chain->setEffectSuspendedAll_l(suspend);
1440 }
1441 }
1442
1443 updateSuspendedSessions_l(type, suspend, sessionId);
1444}
1445
1446void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1447{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001448 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001449 if (index < 0) {
1450 return;
1451 }
1452
Glenn Kasten0a7af182012-07-09 16:09:19 -07001453 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1454 mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001455
1456 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001457 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001458 for (int j = 0; j < desc->mRefCount; j++) {
1459 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1460 chain->setEffectSuspendedAll_l(true);
1461 } else {
Steve Block3856b092011-10-20 11:56:00 +01001462 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001463 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001464 chain->setEffectSuspended_l(&desc->mType, true);
1465 }
1466 }
1467 }
1468}
1469
Eric Laurent59255e42011-07-27 19:49:51 -07001470void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1471 bool suspend,
1472 int sessionId)
1473{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001474 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001475
1476 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1477
1478 if (suspend) {
1479 if (index >= 0) {
Glenn Kasten0a7af182012-07-09 16:09:19 -07001480 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001481 } else {
1482 mSuspendedSessions.add(sessionId, sessionEffects);
1483 }
1484 } else {
1485 if (index < 0) {
1486 return;
1487 }
Glenn Kasten0a7af182012-07-09 16:09:19 -07001488 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001489 }
1490
1491
1492 int key = EffectChain::kKeyForSuspendAll;
1493 if (type != NULL) {
1494 key = type->timeLow;
1495 }
1496 index = sessionEffects.indexOfKey(key);
1497
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001498 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001499 if (suspend) {
1500 if (index >= 0) {
1501 desc = sessionEffects.valueAt(index);
1502 } else {
1503 desc = new SuspendedSessionDesc();
1504 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001505 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001506 }
1507 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001508 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001509 }
1510 desc->mRefCount++;
1511 } else {
1512 if (index < 0) {
1513 return;
1514 }
1515 desc = sessionEffects.valueAt(index);
1516 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001517 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001518 sessionEffects.removeItemsAt(index);
1519 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001520 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001521 sessionId);
1522 mSuspendedSessions.removeItem(sessionId);
1523 }
1524 }
1525 }
1526 if (!sessionEffects.isEmpty()) {
1527 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1528 }
1529}
1530
1531void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1532 bool enabled,
1533 int sessionId)
1534{
1535 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001536 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1537}
Eric Laurent59255e42011-07-27 19:49:51 -07001538
Eric Laurenta85a74a2011-10-19 11:44:54 -07001539void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1540 bool enabled,
1541 int sessionId)
1542{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001543 if (mType != RECORD) {
1544 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1545 // another session. This gives the priority to well behaved effect control panels
1546 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001547 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1548 // global effects
1549 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001550 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1551 }
1552 }
Eric Laurent59255e42011-07-27 19:49:51 -07001553
1554 sp<EffectChain> chain = getEffectChain_l(sessionId);
1555 if (chain != 0) {
1556 chain->checkSuspendOnEffectEnabled(effect, enabled);
1557 }
1558}
1559
Mathias Agopian65ab4712010-07-14 17:59:35 -07001560// ----------------------------------------------------------------------------
1561
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001562AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1563 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001564 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001565 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001566 type_t type)
Eric Laurent88959252012-08-28 14:26:53 -07001567 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001568 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001569 // mStreamTypes[] initialized in constructor body
1570 mOutput(output),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001571 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001572 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001573 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001574 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001575 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001576 // index 0 is reserved for normal mixer's submix
1577 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578{
Glenn Kasten480b4682012-02-28 12:30:08 -08001579 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001580
John Grossmanee578c02012-07-23 17:05:46 -07001581 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1582 // it would be safer to explicitly pass initial masterVolume/masterMute as
1583 // parameter.
1584 //
1585 // If the HAL we are using has support for master volume or master mute,
1586 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1587 // and the mute set to false).
1588 mMasterVolume = audioFlinger->masterVolume_l();
1589 mMasterMute = audioFlinger->masterMute_l();
1590 if (mOutput && mOutput->audioHwDev) {
1591 if (mOutput->audioHwDev->canSetMasterVolume()) {
1592 mMasterVolume = 1.0;
1593 }
1594
1595 if (mOutput->audioHwDev->canSetMasterMute()) {
1596 mMasterMute = false;
1597 }
1598 }
1599
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600 readOutputParameters();
1601
Glenn Kasten263709e2012-01-06 08:40:01 -08001602 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001603 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1604 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1605 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001606 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1607 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001608 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001609 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1610 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001611}
1612
1613AudioFlinger::PlaybackThread::~PlaybackThread()
1614{
1615 delete [] mMixBuffer;
1616}
1617
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001618void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001619{
1620 dumpInternals(fd, args);
1621 dumpTracks(fd, args);
1622 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001623}
1624
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001625void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001626{
1627 const size_t SIZE = 256;
1628 char buffer[SIZE];
1629 String8 result;
1630
Glenn Kasten58912562012-04-03 10:45:00 -07001631 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1632 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1633 const stream_type_t *st = &mStreamTypes[i];
1634 if (i > 0) {
1635 result.appendFormat(", ");
1636 }
1637 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1638 if (st->mute) {
1639 result.append("M");
1640 }
1641 }
1642 result.append("\n");
1643 write(fd, result.string(), result.length());
1644 result.clear();
1645
Mathias Agopian65ab4712010-07-14 17:59:35 -07001646 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1647 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001648 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001649 for (size_t i = 0; i < mTracks.size(); ++i) {
1650 sp<Track> track = mTracks[i];
1651 if (track != 0) {
1652 track->dump(buffer, SIZE);
1653 result.append(buffer);
1654 }
1655 }
1656
1657 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1658 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001659 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001660 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001661 sp<Track> track = mActiveTracks[i].promote();
1662 if (track != 0) {
1663 track->dump(buffer, SIZE);
1664 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001665 }
1666 }
1667 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001668
1669 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1670 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1671 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1672 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001673}
1674
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001675void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001676{
1677 const size_t SIZE = 256;
1678 char buffer[SIZE];
1679 String8 result;
1680
1681 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1682 result.append(buffer);
Glenn Kasten8af901c2012-11-01 11:11:38 -07001683 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1684 ns2ms(systemTime() - mLastWriteTime));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685 result.append(buffer);
1686 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1687 result.append(buffer);
1688 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1689 result.append(buffer);
1690 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1691 result.append(buffer);
1692 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1693 result.append(buffer);
1694 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1695 result.append(buffer);
1696 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001697 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698
1699 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001700}
1701
1702// Thread virtuals
1703status_t AudioFlinger::PlaybackThread::readyToRun()
1704{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001705 status_t status = initCheck();
1706 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001707 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001708 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001709 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001710 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001711 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001712}
1713
1714void AudioFlinger::PlaybackThread::onFirstRef()
1715{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001716 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001717}
1718
Jean-Michel Trivi2fa114d2012-09-28 14:49:39 -07001719// ThreadBase virtuals
1720void AudioFlinger::PlaybackThread::preExit()
1721{
1722 ALOGV(" preExit()");
1723 // FIXME this is using hard-coded strings but in the future, this functionality will be
1724 // converted to use audio HAL extensions required to support tunneling
1725 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1726}
1727
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001729sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001730 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001731 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001732 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001733 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001734 audio_channel_mask_t channelMask,
Glenn Kasten7da35f22012-11-14 12:54:39 -08001735 size_t frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001736 const sp<IMemory>& sharedBuffer,
1737 int sessionId,
Glenn Kastenc2674152012-11-06 15:03:34 -08001738 IAudioFlinger::track_flags_t *flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001739 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001740 status_t *status)
1741{
1742 sp<Track> track;
1743 status_t lStatus;
1744
Glenn Kastenc2674152012-11-06 15:03:34 -08001745 bool isTimed = (*flags & IAudioFlinger::TRACK_TIMED) != 0;
Glenn Kasten73d22752012-03-19 13:38:30 -07001746
1747 // client expresses a preference for FAST, but we get the final say
Glenn Kastenc2674152012-11-06 15:03:34 -08001748 if (*flags & IAudioFlinger::TRACK_FAST) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001749 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001750 // not timed
1751 (!isTimed) &&
1752 // either of these use cases:
1753 (
1754 // use case 1: shared buffer with any frame count
1755 (
1756 (sharedBuffer != 0)
1757 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001758 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001759 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001760 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001761 ((frameCount == 0) ||
Glenn Kasten3ed29202012-08-07 15:24:44 -07001762 (frameCount >= (int) (mFrameCount * kFastTrackMultiplier)))
Glenn Kasten73d22752012-03-19 13:38:30 -07001763 )
1764 ) &&
1765 // PCM data
1766 audio_is_linear_pcm(format) &&
1767 // mono or stereo
1768 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1769 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001770#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001771 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001772 (sampleRate == mSampleRate) &&
1773#endif
1774 // normal mixer has an associated fast mixer
1775 hasFastMixer() &&
1776 // there are sufficient fast track slots available
1777 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001778 // FIXME test that MixerThread for this fast track has a capable output HAL
1779 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001780 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001781 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1782 if (frameCount == 0) {
Glenn Kasten3ed29202012-08-07 15:24:44 -07001783 frameCount = mFrameCount * kFastTrackMultiplier;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001784 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001785 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001786 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001787 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001788 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten1127d652012-11-14 08:44:39 -08001789 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten58912562012-04-03 10:45:00 -07001790 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1791 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1792 audio_is_linear_pcm(format),
1793 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kastenc2674152012-11-06 15:03:34 -08001794 *flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001795 // For compatibility with AudioTrack calculation, buffer depth is forced
1796 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1797 // This is probably too conservative, but legacy application code may depend on it.
1798 // If you change this calculation, also review the start threshold which is related.
1799 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1800 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1801 if (minBufCount < 2) {
1802 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001803 }
Glenn Kasten7da35f22012-11-14 12:54:39 -08001804 size_t minFrameCount = mNormalFrameCount * minBufCount;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001805 if (frameCount < minFrameCount) {
1806 frameCount = minFrameCount;
1807 }
1808 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001809 }
1810
Mathias Agopian65ab4712010-07-14 17:59:35 -07001811 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001812 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1813 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kasten1127d652012-11-14 08:44:39 -08001814 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %d, channelMask 0x%08x "
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001815 "for output %p with format %d",
1816 sampleRate, format, channelMask, mOutput, mFormat);
1817 lStatus = BAD_VALUE;
1818 goto Exit;
1819 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001820 }
1821 } else {
1822 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1823 if (sampleRate > mSampleRate*2) {
Glenn Kasten1127d652012-11-14 08:44:39 -08001824 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825 lStatus = BAD_VALUE;
1826 goto Exit;
1827 }
1828 }
1829
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001830 lStatus = initCheck();
1831 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001832 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833 goto Exit;
1834 }
1835
1836 { // scope for mLock
1837 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001838
1839 // all tracks in same audio session must share the same routing strategy otherwise
1840 // conflicts will happen when tracks are moved from one output to another by audio policy
1841 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001842 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001843 for (size_t i = 0; i < mTracks.size(); ++i) {
1844 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001845 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001846 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001847 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001848 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001849 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001850 lStatus = BAD_VALUE;
1851 goto Exit;
1852 }
1853 }
1854 }
1855
John Grossman4ff14ba2012-02-08 16:37:41 -08001856 if (!isTimed) {
1857 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kastenc2674152012-11-06 15:03:34 -08001858 channelMask, frameCount, sharedBuffer, sessionId, *flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001859 } else {
1860 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1861 channelMask, frameCount, sharedBuffer, sessionId);
1862 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001863 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864 lStatus = NO_MEMORY;
1865 goto Exit;
1866 }
1867 mTracks.add(track);
1868
1869 sp<EffectChain> chain = getEffectChain_l(sessionId);
1870 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001871 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001872 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001873 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001874 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001875 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001876
Glenn Kastenc2674152012-11-06 15:03:34 -08001877 if ((*flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
Eric Laurentef6be0b2012-09-13 11:18:23 -07001878 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1879 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1880 // so ask activity manager to do this on our behalf
1881 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001882 }
1883 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001884
Mathias Agopian65ab4712010-07-14 17:59:35 -07001885 lStatus = NO_ERROR;
1886
1887Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001888 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001889 *status = lStatus;
1890 }
1891 return track;
1892}
1893
Eric Laurente737cda2012-05-22 18:55:44 -07001894uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1895{
1896 if (mFastMixer != NULL) {
1897 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1898 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1899 }
1900 return latency;
1901}
1902
1903uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1904{
1905 return latency;
1906}
1907
Mathias Agopian65ab4712010-07-14 17:59:35 -07001908uint32_t AudioFlinger::PlaybackThread::latency() const
1909{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001910 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001911 return latency_l();
1912}
1913uint32_t AudioFlinger::PlaybackThread::latency_l() const
1914{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001915 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001916 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001917 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918 return 0;
1919 }
1920}
1921
Glenn Kasten6637baa2012-01-09 09:40:36 -08001922void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001923{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001924 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001925 // Don't apply master volume in SW if our HAL can do it for us.
1926 if (mOutput && mOutput->audioHwDev &&
1927 mOutput->audioHwDev->canSetMasterVolume()) {
1928 mMasterVolume = 1.0;
1929 } else {
1930 mMasterVolume = value;
1931 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932}
1933
Glenn Kasten6637baa2012-01-09 09:40:36 -08001934void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001935{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001936 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001937 // Don't apply master mute in SW if our HAL can do it for us.
1938 if (mOutput && mOutput->audioHwDev &&
1939 mOutput->audioHwDev->canSetMasterMute()) {
1940 mMasterMute = false;
1941 } else {
1942 mMasterMute = muted;
1943 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001944}
1945
Glenn Kasten6637baa2012-01-09 09:40:36 -08001946void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001947{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001948 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001950}
1951
Glenn Kasten6637baa2012-01-09 09:40:36 -08001952void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001953{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001954 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001955 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001956}
1957
Glenn Kastenfff6d712012-01-12 16:38:12 -08001958float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001960 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001961 return mStreamTypes[stream].volume;
1962}
1963
Mathias Agopian65ab4712010-07-14 17:59:35 -07001964// addTrack_l() must be called with ThreadBase::mLock held
1965status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1966{
1967 status_t status = ALREADY_EXISTS;
1968
1969 // set retry count for buffer fill
1970 track->mRetryCount = kMaxTrackStartupRetries;
1971 if (mActiveTracks.indexOf(track) < 0) {
1972 // the track is newly added, make sure it fills up all its
1973 // buffers before playing. This is to ensure the client will
1974 // effectively get the latency it requested.
1975 track->mFillingUpStatus = Track::FS_FILLING;
1976 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001977 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001978 mActiveTracks.add(track);
1979 if (track->mainBuffer() != mMixBuffer) {
1980 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1981 if (chain != 0) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07001982 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1983 track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001984 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001985 }
1986 }
1987
1988 status = NO_ERROR;
1989 }
1990
Steve Block3856b092011-10-20 11:56:00 +01001991 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992 mWaitWorkCV.broadcast();
1993
1994 return status;
1995}
1996
1997// destroyTrack_l() must be called with ThreadBase::mLock held
1998void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1999{
2000 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07002001 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002002 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07002003 removeTrack_l(track);
2004 }
2005}
2006
2007void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2008{
Eric Laurent29864602012-05-08 18:57:51 -07002009 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07002010 mTracks.remove(track);
2011 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07002012 // redundant as track is about to be destroyed, for dumpsys only
2013 track->mName = -1;
2014 if (track->isFastTrack()) {
2015 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07002016 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07002017 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2018 mFastTrackAvailMask |= 1 << index;
2019 // redundant as track is about to be destroyed, for dumpsys only
2020 track->mFastIndex = -1;
2021 }
Eric Laurentb469b942011-05-09 12:09:06 -07002022 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2023 if (chain != 0) {
2024 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002025 }
2026}
2027
2028String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2029{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002030 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07002031 char *s;
2032
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002033 Mutex::Autolock _l(mLock);
2034 if (initCheck() != NO_ERROR) {
2035 return out_s8;
2036 }
2037
Dima Zavin799a70e2011-04-18 16:57:27 -07002038 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07002039 out_s8 = String8(s);
2040 free(s);
2041 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002042}
2043
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002044// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002045void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
2046 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08002047 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002048
Glenn Kasten8af901c2012-11-01 11:11:38 -07002049 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
2050 param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002051
2052 switch (event) {
2053 case AudioSystem::OUTPUT_OPENED:
2054 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002055 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002056 desc.samplingRate = mSampleRate;
2057 desc.format = mFormat;
Glenn Kasten8af901c2012-11-01 11:11:38 -07002058 desc.frameCount = mNormalFrameCount; // FIXME see
2059 // AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002060 desc.latency = latency();
2061 param2 = &desc;
2062 break;
2063
2064 case AudioSystem::STREAM_CONFIG_CHANGED:
2065 param2 = &param;
2066 case AudioSystem::OUTPUT_CLOSED:
2067 default:
2068 break;
2069 }
2070 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2071}
2072
2073void AudioFlinger::PlaybackThread::readOutputParameters()
2074{
Dima Zavin799a70e2011-04-18 16:57:27 -07002075 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002076 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2077 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07002078 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002079 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002080 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002081 if (mFrameCount & 15) {
2082 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2083 mFrameCount);
2084 }
2085
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002086 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002087 double multiplier = 1.0;
Glenn Kasten8af901c2012-11-01 11:11:38 -07002088 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2089 kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002090 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002091 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2092 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2093 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2094 maxNormalFrameCount = maxNormalFrameCount & ~15;
2095 if (maxNormalFrameCount < minNormalFrameCount) {
2096 maxNormalFrameCount = minNormalFrameCount;
2097 }
2098 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2099 if (multiplier <= 1.0) {
2100 multiplier = 1.0;
2101 } else if (multiplier <= 2.0) {
2102 if (2 * mFrameCount <= maxNormalFrameCount) {
2103 multiplier = 2.0;
2104 } else {
2105 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2106 }
2107 } else {
Glenn Kasten8af901c2012-11-01 11:11:38 -07002108 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
2109 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
2110 // track, but we sometimes have to do this to satisfy the maximum frame count
2111 // constraint)
Glenn Kasten4adcede2012-05-14 12:26:02 -07002112 // FIXME this rounding up should not be done if no HAL SRC
2113 uint32_t truncMult = (uint32_t) multiplier;
2114 if ((truncMult & 1)) {
2115 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2116 ++truncMult;
2117 }
2118 }
2119 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002120 }
Glenn Kasten58912562012-04-03 10:45:00 -07002121 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002122 mNormalFrameCount = multiplier * mFrameCount;
2123 // round up to nearest 16 frames to satisfy AudioMixer
2124 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten8af901c2012-11-01 11:11:38 -07002125 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
2126 mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002127
Glenn Kastene9dd0172012-01-27 18:08:45 -08002128 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002129 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2130 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002131
Eric Laurentde070132010-07-13 04:45:46 -07002132 // force reconfiguration of effect chains and engines to take new buffer size and audio
2133 // parameters into account
2134 // Note that mLock is not held when readOutputParameters() is called from the constructor
2135 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2136 // matter.
2137 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2138 Vector< sp<EffectChain> > effectChains = mEffectChains;
2139 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002140 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002141 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002142}
2143
Eric Laurente737cda2012-05-22 18:55:44 -07002144
Mathias Agopian65ab4712010-07-14 17:59:35 -07002145status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2146{
Glenn Kastena0d68332012-01-27 16:47:15 -08002147 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002148 return BAD_VALUE;
2149 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002150 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002151 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002152 return INVALID_OPERATION;
2153 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002154 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002155
Eric Laurent6090a172012-09-23 15:20:50 -07002156 if (isSuspended()) {
2157 // return an estimation of rendered frames when the output is suspended
2158 int32_t frames = mBytesWritten - latency_l();
2159 if (frames < 0) {
2160 frames = 0;
2161 }
2162 *dspFrames = (uint32_t)frames;
2163 return NO_ERROR;
2164 } else {
2165 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
2166 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002167}
2168
Glenn Kasten106e8a42012-08-02 13:37:12 -07002169uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002170{
2171 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002172 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002173 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002174 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002175 }
2176
2177 for (size_t i = 0; i < mTracks.size(); ++i) {
2178 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002179 if (sessionId == track->sessionId() &&
Glenn Kastend12b0332012-11-05 13:38:15 -08002180 !(track->mCblk->flags & CBLK_INVALID)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002181 result |= TRACK_SESSION;
2182 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002183 }
2184 }
2185
Eric Laurent39e94f82010-07-28 01:32:47 -07002186 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002187}
2188
Eric Laurentde070132010-07-13 04:45:46 -07002189uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2190{
Dima Zavinfce7a472011-04-19 22:30:36 -07002191 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002192 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002193 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2194 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002195 }
2196 for (size_t i = 0; i < mTracks.size(); i++) {
2197 sp<Track> track = mTracks[i];
2198 if (sessionId == track->sessionId() &&
Glenn Kastend12b0332012-11-05 13:38:15 -08002199 !(track->mCblk->flags & CBLK_INVALID)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002200 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002201 }
2202 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002203 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002204}
2205
Mathias Agopian65ab4712010-07-14 17:59:35 -07002206
Glenn Kastenaed850d2012-01-26 09:46:34 -08002207AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002208{
2209 Mutex::Autolock _l(mLock);
2210 return mOutput;
2211}
2212
2213AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2214{
2215 Mutex::Autolock _l(mLock);
2216 AudioStreamOut *output = mOutput;
2217 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002218 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2219 // must push a NULL and wait for ack
2220 mOutputSink.clear();
2221 mPipeSink.clear();
2222 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002223 return output;
2224}
2225
2226// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002227audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002228{
2229 if (mOutput == NULL) {
2230 return NULL;
2231 }
2232 return &mOutput->stream->common;
2233}
2234
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002235uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002236{
Eric Laurentab9071b2012-06-04 13:45:29 -07002237 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002238}
2239
Eric Laurenta011e352012-03-29 15:51:43 -07002240status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2241{
2242 if (!isValidSyncEvent(event)) {
2243 return BAD_VALUE;
2244 }
2245
2246 Mutex::Autolock _l(mLock);
2247
2248 for (size_t i = 0; i < mTracks.size(); ++i) {
2249 sp<Track> track = mTracks[i];
2250 if (event->triggerSession() == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07002251 (void) track->setSyncEvent(event);
Eric Laurenta011e352012-03-29 15:51:43 -07002252 return NO_ERROR;
2253 }
2254 }
2255
2256 return NAME_NOT_FOUND;
2257}
2258
Glenn Kasten106e8a42012-08-02 13:37:12 -07002259bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07002260{
Glenn Kasten0dbb3562012-08-02 16:36:50 -07002261 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
Eric Laurenta011e352012-03-29 15:51:43 -07002262}
2263
Glenn Kasten8af901c2012-11-01 11:11:38 -07002264void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2265 const Vector< sp<Track> >& tracksToRemove)
Eric Laurent44a957f2012-05-15 15:26:05 -07002266{
2267 size_t count = tracksToRemove.size();
2268 if (CC_UNLIKELY(count)) {
2269 for (size_t i = 0 ; i < count ; i++) {
2270 const sp<Track>& track = tracksToRemove.itemAt(i);
2271 if ((track->sharedBuffer() != 0) &&
2272 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2273 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2274 }
2275 }
2276 }
2277
2278}
2279
Mathias Agopian65ab4712010-07-14 17:59:35 -07002280// ----------------------------------------------------------------------------
2281
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002282AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002283 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002284 : PlaybackThread(audioFlinger, output, id, device, type),
2285 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002286 // mFastMixer below
2287 mFastMixerFutex(0)
2288 // mOutputSink below
2289 // mPipeSink below
2290 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002291{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002292 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten520a9af2012-06-21 12:56:37 -07002293 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%u, "
Glenn Kasten58912562012-04-03 10:45:00 -07002294 "mFrameCount=%d, mNormalFrameCount=%d",
2295 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2296 mNormalFrameCount);
2297 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2298
Mathias Agopian65ab4712010-07-14 17:59:35 -07002299 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002300 if (mChannelCount != FCC_2) {
2301 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002302 }
Glenn Kasten58912562012-04-03 10:45:00 -07002303
2304 // create an NBAIO sink for the HAL output stream, and negotiate
2305 mOutputSink = new AudioStreamOutSink(output->stream);
2306 size_t numCounterOffers = 0;
2307 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2308 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2309 ALOG_ASSERT(index == 0);
2310
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002311 // initialize fast mixer depending on configuration
2312 bool initFastMixer;
2313 switch (kUseFastMixer) {
2314 case FastMixer_Never:
2315 initFastMixer = false;
2316 break;
2317 case FastMixer_Always:
2318 initFastMixer = true;
2319 break;
2320 case FastMixer_Static:
2321 case FastMixer_Dynamic:
2322 initFastMixer = mFrameCount < mNormalFrameCount;
2323 break;
2324 }
2325 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002326
2327 // create a MonoPipe to connect our submix to FastMixer
2328 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002329 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2330 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2331 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2332 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002333 const NBAIO_Format offers[1] = {format};
2334 size_t numCounterOffers = 0;
2335 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2336 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002337 monoPipe->setAvgFrames((mScreenState & 1) ?
2338 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002339 mPipeSink = monoPipe;
2340
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002341#ifdef TEE_SINK_FRAMES
2342 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2343 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2344 numCounterOffers = 0;
2345 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2346 ALOG_ASSERT(index == 0);
2347 mTeeSink = teeSink;
2348 PipeReader *teeSource = new PipeReader(*teeSink);
2349 numCounterOffers = 0;
2350 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2351 ALOG_ASSERT(index == 0);
2352 mTeeSource = teeSource;
2353#endif
2354
Glenn Kasten58912562012-04-03 10:45:00 -07002355 // create fast mixer and configure it initially with just one fast track for our submix
2356 mFastMixer = new FastMixer();
2357 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002358#ifdef STATE_QUEUE_DUMP
2359 sq->setObserverDump(&mStateQueueObserverDump);
2360 sq->setMutatorDump(&mStateQueueMutatorDump);
2361#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002362 FastMixerState *state = sq->begin();
2363 FastTrack *fastTrack = &state->mFastTracks[0];
2364 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2365 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2366 fastTrack->mVolumeProvider = NULL;
2367 fastTrack->mGeneration++;
2368 state->mFastTracksGen++;
2369 state->mTrackMask = 1;
2370 // fast mixer will use the HAL output sink
2371 state->mOutputSink = mOutputSink.get();
2372 state->mOutputSinkGen++;
2373 state->mFrameCount = mFrameCount;
2374 state->mCommand = FastMixerState::COLD_IDLE;
2375 // already done in constructor initialization list
2376 //mFastMixerFutex = 0;
2377 state->mColdFutexAddr = &mFastMixerFutex;
2378 state->mColdGen++;
2379 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002380 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002381 sq->end();
2382 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2383
2384 // start the fast mixer
2385 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002386 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002387 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002388 if (err != 0) {
2389 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002390 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002391 }
Glenn Kasten58912562012-04-03 10:45:00 -07002392
Glenn Kastenc15d6652012-05-30 14:52:57 -07002393#ifdef AUDIO_WATCHDOG
2394 // create and start the watchdog
2395 mAudioWatchdog = new AudioWatchdog();
2396 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2397 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2398 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002399 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002400 if (err != 0) {
2401 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002402 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002403 }
2404#endif
2405
Glenn Kasten58912562012-04-03 10:45:00 -07002406 } else {
2407 mFastMixer = NULL;
2408 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002409
2410 switch (kUseFastMixer) {
2411 case FastMixer_Never:
2412 case FastMixer_Dynamic:
2413 mNormalSink = mOutputSink;
2414 break;
2415 case FastMixer_Always:
2416 mNormalSink = mPipeSink;
2417 break;
2418 case FastMixer_Static:
2419 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2420 break;
2421 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002422}
2423
2424AudioFlinger::MixerThread::~MixerThread()
2425{
Glenn Kasten58912562012-04-03 10:45:00 -07002426 if (mFastMixer != NULL) {
2427 FastMixerStateQueue *sq = mFastMixer->sq();
2428 FastMixerState *state = sq->begin();
2429 if (state->mCommand == FastMixerState::COLD_IDLE) {
2430 int32_t old = android_atomic_inc(&mFastMixerFutex);
2431 if (old == -1) {
2432 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2433 }
2434 }
2435 state->mCommand = FastMixerState::EXIT;
2436 sq->end();
2437 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2438 mFastMixer->join();
2439 // Though the fast mixer thread has exited, it's state queue is still valid.
2440 // We'll use that extract the final state which contains one remaining fast track
2441 // corresponding to our sub-mix.
2442 state = sq->begin();
2443 ALOG_ASSERT(state->mTrackMask == 1);
2444 FastTrack *fastTrack = &state->mFastTracks[0];
2445 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2446 delete fastTrack->mBufferProvider;
2447 sq->end(false /*didModify*/);
2448 delete mFastMixer;
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07002449#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002450 if (mAudioWatchdog != 0) {
2451 mAudioWatchdog->requestExit();
2452 mAudioWatchdog->requestExitAndWait();
2453 mAudioWatchdog.clear();
2454 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07002455#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002456 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002457 delete mAudioMixer;
2458}
2459
Glenn Kasten83efdd02012-02-24 07:21:32 -08002460class CpuStats {
2461public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002462 CpuStats();
2463 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002464#ifdef DEBUG_CPU_USAGE
2465private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002466 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2467 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2468
2469 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2470
2471 int mCpuNum; // thread's current CPU number
2472 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002473#endif
2474};
2475
Glenn Kasten190a46f2012-03-06 11:27:10 -08002476CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002477#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002478 : mCpuNum(-1), mCpukHz(-1)
2479#endif
2480{
2481}
2482
2483void CpuStats::sample(const String8 &title) {
2484#ifdef DEBUG_CPU_USAGE
2485 // get current thread's delta CPU time in wall clock ns
2486 double wcNs;
2487 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2488
2489 // record sample for wall clock statistics
2490 if (valid) {
2491 mWcStats.sample(wcNs);
2492 }
2493
2494 // get the current CPU number
2495 int cpuNum = sched_getcpu();
2496
2497 // get the current CPU frequency in kHz
2498 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2499
2500 // check if either CPU number or frequency changed
2501 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2502 mCpuNum = cpuNum;
2503 mCpukHz = cpukHz;
2504 // ignore sample for purposes of cycles
2505 valid = false;
2506 }
2507
2508 // if no change in CPU number or frequency, then record sample for cycle statistics
2509 if (valid && mCpukHz > 0) {
2510 double cycles = wcNs * cpukHz * 0.000001;
2511 mHzStats.sample(cycles);
2512 }
2513
2514 unsigned n = mWcStats.n();
2515 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002516 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002517 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002518 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2519 double perLoop = elapsed / (double) n;
2520 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002521 double perLoop1k = perLoop * 0.001;
2522 double mean = mWcStats.mean();
2523 double stddev = mWcStats.stddev();
2524 double minimum = mWcStats.minimum();
2525 double maximum = mWcStats.maximum();
2526 double meanCycles = mHzStats.mean();
2527 double stddevCycles = mHzStats.stddev();
2528 double minCycles = mHzStats.minimum();
2529 double maxCycles = mHzStats.maximum();
2530 mCpuUsage.resetElapsed();
2531 mWcStats.reset();
2532 mHzStats.reset();
2533 ALOGD("CPU usage for %s over past %.1f secs\n"
2534 " (%u mixer loops at %.1f mean ms per loop):\n"
2535 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2536 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2537 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2538 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002539 elapsed * .000000001, n, perLoop * .000001,
2540 mean * .001,
2541 stddev * .001,
2542 minimum * .001,
2543 maximum * .001,
2544 mean / perLoop100,
2545 stddev / perLoop100,
2546 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002547 maximum / perLoop100,
2548 meanCycles / perLoop1k,
2549 stddevCycles / perLoop1k,
2550 minCycles / perLoop1k,
2551 maxCycles / perLoop1k);
2552
Glenn Kasten83efdd02012-02-24 07:21:32 -08002553 }
2554 }
2555#endif
2556};
2557
Glenn Kasten37d825e2012-02-24 07:21:48 -08002558void AudioFlinger::PlaybackThread::checkSilentMode_l()
2559{
2560 if (!mMasterMute) {
2561 char value[PROPERTY_VALUE_MAX];
2562 if (property_get("ro.audio.silent", value, "0") > 0) {
2563 char *endptr;
2564 unsigned long ul = strtoul(value, &endptr, 0);
2565 if (*endptr == '\0' && ul != 0) {
2566 ALOGD("Silence is golden");
2567 // The setprop command will not allow a property to be changed after
2568 // the first time it is set, so we don't have to worry about un-muting.
2569 setMasterMute_l(true);
2570 }
2571 }
2572 }
2573}
2574
Glenn Kasten000f0e32012-03-01 17:10:56 -08002575bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002576{
2577 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002578
Glenn Kasten000f0e32012-03-01 17:10:56 -08002579 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002580
2581 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002582 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002583
Glenn Kasten000f0e32012-03-01 17:10:56 -08002584 // DUPLICATING
2585 // FIXME could this be made local to while loop?
2586 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002587
Glenn Kasten66fcab92012-02-24 14:59:21 -08002588 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002589 sleepTime = idleSleepTime;
2590
Glenn Kasten9f34a362012-03-20 16:46:41 -07002591 if (mType == MIXER) {
2592 sleepTimeShift = 0;
2593 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002594
Glenn Kasten83efdd02012-02-24 07:21:32 -08002595 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002596 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002597
Eric Laurentfeb0db62011-07-22 09:04:31 -07002598 acquireWakeLock();
2599
Mathias Agopian65ab4712010-07-14 17:59:35 -07002600 while (!exitPending())
2601 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002602 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002603
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002604 Vector< sp<EffectChain> > effectChains;
2605
Mathias Agopian65ab4712010-07-14 17:59:35 -07002606 processConfigEvents();
2607
Mathias Agopian65ab4712010-07-14 17:59:35 -07002608 { // scope for mLock
2609
2610 Mutex::Autolock _l(mLock);
2611
2612 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002613 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002614 }
2615
Glenn Kastenfa26a852012-03-06 11:28:04 -08002616 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002617
Mathias Agopian65ab4712010-07-14 17:59:35 -07002618 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002619 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002620 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002622
2623 threadLoop_standby();
2624
Mathias Agopian65ab4712010-07-14 17:59:35 -07002625 mStandby = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002626 }
2627
Glenn Kasten3e074702012-02-28 18:40:35 -08002628 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002629 // we're about to wait, flush the binder command buffer
2630 IPCThreadState::self()->flushCommands();
2631
Glenn Kastenfa26a852012-03-06 11:28:04 -08002632 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002633
Glenn Kastena2049222012-06-22 17:21:07 -07002634 if (exitPending()) {
2635 break;
2636 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002637
Eric Laurentfeb0db62011-07-22 09:04:31 -07002638 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002639 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002640 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002641 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002642 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002643 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002644
Eric Laurentda747442012-04-25 18:53:13 -07002645 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002646 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Eric Laurent6090a172012-09-23 15:20:50 -07002647 mBytesWritten = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002648
Glenn Kasten37d825e2012-02-24 07:21:48 -08002649 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002650
Glenn Kasten000f0e32012-03-01 17:10:56 -08002651 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002652 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002653 if (mType == MIXER) {
2654 sleepTimeShift = 0;
2655 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002656
Mathias Agopian65ab4712010-07-14 17:59:35 -07002657 continue;
2658 }
2659 }
2660
Glenn Kasten81028042012-04-30 18:15:12 -07002661 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002662 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002663
2664 // prevent any changes in effect chain list and in each effect chain
2665 // during mixing and effect process as the audio buffers could be deleted
2666 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002667 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002668 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002669
Glenn Kastenfec279f2012-03-08 07:47:15 -08002670 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002671 threadLoop_mix();
2672 } else {
2673 threadLoop_sleepTime();
2674 }
2675
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002676 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002677 sleepTime = suspendSleepTimeUs();
Eric Laurent6090a172012-09-23 15:20:50 -07002678 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002679 }
2680
2681 // only process effects if we're going to write
2682 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002683 for (size_t i = 0; i < effectChains.size(); i ++) {
2684 effectChains[i]->process_l();
2685 }
2686 }
2687
2688 // enable changes in effect chain
2689 unlockEffectChains(effectChains);
2690
2691 // sleepTime == 0 means we must write to audio hardware
2692 if (sleepTime == 0) {
2693
2694 threadLoop_write();
2695
2696if (mType == MIXER) {
2697 // write blocked detection
2698 nsecs_t now = systemTime();
2699 nsecs_t delta = now - mLastWriteTime;
2700 if (!mStandby && delta > maxPeriod) {
2701 mNumDelayedWrites++;
2702 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002703#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002704 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002705#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002706 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2707 ns2ms(delta), mNumDelayedWrites, this);
2708 lastWarning = now;
2709 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002710 }
2711}
2712
2713 mStandby = false;
2714 } else {
2715 usleep(sleepTime);
2716 }
2717
Glenn Kasten58912562012-04-03 10:45:00 -07002718 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002719 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002720 // same lock. This will also mutate and push a new fast mixer state.
2721 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002722 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002723
Glenn Kastenfa26a852012-03-06 11:28:04 -08002724 // FIXME I don't understand the need for this here;
2725 // it was in the original code but maybe the
2726 // assignment in saveOutputTracks() makes this unnecessary?
2727 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002728
2729 // Effect chains will be actually deleted here if they were removed from
2730 // mEffectChains list during mixing or effects processing
2731 effectChains.clear();
2732
2733 // FIXME Note that the above .clear() is no longer necessary since effectChains
2734 // is now local to this block, but will keep it for now (at least until merge done).
2735 }
2736
Glenn Kasten9f34a362012-03-20 16:46:41 -07002737 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2738 if (mType == MIXER || mType == DIRECT) {
2739 // put output stream into standby mode
2740 if (!mStandby) {
2741 mOutput->stream->common.standby(&mOutput->stream->common);
2742 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002743 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002744
2745 releaseWakeLock();
2746
2747 ALOGV("Thread %p type %d exiting", this, mType);
2748 return false;
2749}
2750
Glenn Kasten58912562012-04-03 10:45:00 -07002751void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2752{
Glenn Kasten58912562012-04-03 10:45:00 -07002753 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2754}
2755
2756void AudioFlinger::MixerThread::threadLoop_write()
2757{
2758 // FIXME we should only do one push per cycle; confirm this is true
2759 // Start the fast mixer if it's not already running
2760 if (mFastMixer != NULL) {
2761 FastMixerStateQueue *sq = mFastMixer->sq();
2762 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002763 if (state->mCommand != FastMixerState::MIX_WRITE &&
2764 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002765 if (state->mCommand == FastMixerState::COLD_IDLE) {
2766 int32_t old = android_atomic_inc(&mFastMixerFutex);
2767 if (old == -1) {
2768 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2769 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07002770#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002771 if (mAudioWatchdog != 0) {
2772 mAudioWatchdog->resume();
2773 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07002774#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002775 }
2776 state->mCommand = FastMixerState::MIX_WRITE;
2777 sq->end();
2778 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002779 if (kUseFastMixer == FastMixer_Dynamic) {
2780 mNormalSink = mPipeSink;
2781 }
Glenn Kasten58912562012-04-03 10:45:00 -07002782 } else {
2783 sq->end(false /*didModify*/);
2784 }
2785 }
2786 PlaybackThread::threadLoop_write();
2787}
2788
Glenn Kasten000f0e32012-03-01 17:10:56 -08002789// shared by MIXER and DIRECT, overridden by DUPLICATING
2790void AudioFlinger::PlaybackThread::threadLoop_write()
2791{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002792 // FIXME rewrite to reduce number of system calls
2793 mLastWriteTime = systemTime();
2794 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002795 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002796
Eric Laurent67c0a582012-05-01 19:31:12 -07002797 // If an NBAIO sink is present, use it to write the normal mixer's submix
2798 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002799#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002800 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002801#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002802 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002803#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002804 // update the setpoint when gScreenState changes
2805 uint32_t screenState = gScreenState;
2806 if (screenState != mScreenState) {
2807 mScreenState = screenState;
2808 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2809 if (pipe != NULL) {
2810 pipe->setAvgFrames((mScreenState & 1) ?
2811 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2812 }
2813 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002814 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002815#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002816 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002817#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002818 if (framesWritten > 0) {
2819 bytesWritten = framesWritten << mBitShift;
2820 } else {
2821 bytesWritten = framesWritten;
2822 }
2823 // otherwise use the HAL / AudioStreamOut directly
2824 } else {
2825 // Direct output thread.
2826 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002827 }
2828
Glenn Kastena2049222012-06-22 17:21:07 -07002829 if (bytesWritten > 0) {
2830 mBytesWritten += mixBufferSize;
2831 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002832 mNumWrites++;
2833 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002834}
2835
Glenn Kasten58912562012-04-03 10:45:00 -07002836void AudioFlinger::MixerThread::threadLoop_standby()
2837{
2838 // Idle the fast mixer if it's currently running
2839 if (mFastMixer != NULL) {
2840 FastMixerStateQueue *sq = mFastMixer->sq();
2841 FastMixerState *state = sq->begin();
2842 if (!(state->mCommand & FastMixerState::IDLE)) {
2843 state->mCommand = FastMixerState::COLD_IDLE;
2844 state->mColdFutexAddr = &mFastMixerFutex;
2845 state->mColdGen++;
2846 mFastMixerFutex = 0;
2847 sq->end();
2848 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2849 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002850 if (kUseFastMixer == FastMixer_Dynamic) {
2851 mNormalSink = mOutputSink;
2852 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07002853#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002854 if (mAudioWatchdog != 0) {
2855 mAudioWatchdog->pause();
2856 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07002857#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002858 } else {
2859 sq->end(false /*didModify*/);
2860 }
2861 }
2862 PlaybackThread::threadLoop_standby();
2863}
2864
Glenn Kasten000f0e32012-03-01 17:10:56 -08002865// shared by MIXER and DIRECT, overridden by DUPLICATING
2866void AudioFlinger::PlaybackThread::threadLoop_standby()
2867{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002868 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002869 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002870}
2871
2872void AudioFlinger::MixerThread::threadLoop_mix()
2873{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002874 // obtain the presentation timestamp of the next output buffer
2875 int64_t pts;
2876 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002877
John Grossman2c3b2da2012-08-02 17:08:54 -07002878 if (mNormalSink != 0) {
2879 status = mNormalSink->getNextWriteTimestamp(&pts);
2880 } else {
2881 status = mOutputSink->getNextWriteTimestamp(&pts);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002882 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002883
Glenn Kasten952eeb22012-03-06 11:30:57 -08002884 if (status != NO_ERROR) {
2885 pts = AudioBufferProvider::kInvalidPTS;
2886 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002887
Glenn Kasten952eeb22012-03-06 11:30:57 -08002888 // mix buffers...
2889 mAudioMixer->process(pts);
2890 // increase sleep time progressively when application underrun condition clears.
2891 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2892 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2893 // such that we would underrun the audio HAL.
2894 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2895 sleepTimeShift--;
2896 }
2897 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002898 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002899 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002900}
2901
2902void AudioFlinger::MixerThread::threadLoop_sleepTime()
2903{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002904 // If no tracks are ready, sleep once for the duration of an output
2905 // buffer size, then write 0s to the output
2906 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002907 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002908 sleepTime = activeSleepTime >> sleepTimeShift;
2909 if (sleepTime < kMinThreadSleepTimeUs) {
2910 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002911 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002912 // reduce sleep time in case of consecutive application underruns to avoid
2913 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2914 // duration we would end up writing less data than needed by the audio HAL if
2915 // the condition persists.
2916 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2917 sleepTimeShift++;
2918 }
2919 } else {
2920 sleepTime = idleSleepTime;
2921 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002922 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002923 memset (mMixBuffer, 0, mixBufferSize);
2924 sleepTime = 0;
Glenn Kasten8af901c2012-11-01 11:11:38 -07002925 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)),
2926 "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002927 }
2928 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002929}
2930
2931// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002932AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002933 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002934{
2935
Glenn Kasten29c23c32012-01-26 13:37:52 -08002936 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002937 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002938 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002939 size_t mixedTracks = 0;
2940 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002941 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002942 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002943 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002944
2945 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002946 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002947
Eric Laurent571d49c2010-08-11 05:20:11 -07002948 if (masterMute) {
2949 masterVolume = 0;
2950 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002951 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002952 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002953 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002954 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002955 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002956 masterVolume = (float)((v + (1 << 23)) >> 24);
2957 chain.clear();
2958 }
2959
Glenn Kasten288ed212012-04-25 17:52:27 -07002960 // prepare a new state to push
2961 FastMixerStateQueue *sq = NULL;
2962 FastMixerState *state = NULL;
2963 bool didModify = false;
2964 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2965 if (mFastMixer != NULL) {
2966 sq = mFastMixer->sq();
2967 state = sq->begin();
2968 }
2969
Mathias Agopian65ab4712010-07-14 17:59:35 -07002970 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002971 sp<Track> t = mActiveTracks[i].promote();
Glenn Kastena2049222012-06-22 17:21:07 -07002972 if (t == 0) {
2973 continue;
2974 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002975
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002976 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002977 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002978
Glenn Kasten288ed212012-04-25 17:52:27 -07002979 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002980 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002981
2982 // It's theoretically possible (though unlikely) for a fast track to be created
2983 // and then removed within the same normal mix cycle. This is not a problem, as
2984 // the track never becomes active so it's fast mixer slot is never touched.
2985 // The converse, of removing an (active) track and then creating a new track
2986 // at the identical fast mixer slot within the same normal mix cycle,
2987 // is impossible because the slot isn't marked available until the end of each cycle.
2988 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002989 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2990 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002991 FastTrack *fastTrack = &state->mFastTracks[j];
2992
2993 // Determine whether the track is currently in underrun condition,
2994 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002995 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2996 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002997 uint32_t recentFull = (underruns.mBitFields.mFull -
2998 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2999 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3000 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3001 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3002 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3003 uint32_t recentUnderruns = recentPartial + recentEmpty;
3004 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07003005 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07003006 // or stopped which can occur when flush() is called while active
3007 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07003008 track->mUnderrunCount += recentUnderruns;
3009 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003010
Glenn Kastend08f48c2012-05-01 18:14:02 -07003011 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07003012 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07003013 bool isActive = true;
3014 switch (track->mState) {
3015 case TrackBase::STOPPING_1:
3016 // track stays active in STOPPING_1 state until first underrun
3017 if (recentUnderruns > 0) {
3018 track->mState = TrackBase::STOPPING_2;
3019 }
3020 break;
3021 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003022 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003023 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07003024 break;
3025 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003026 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003027 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003028 break;
3029 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07003030 if (recentFull > 0 || recentPartial > 0) {
3031 // track has provided at least some frames recently: reset retry count
3032 track->mRetryCount = kMaxTrackRetries;
3033 }
3034 if (recentUnderruns == 0) {
3035 // no recent underruns: stay active
3036 break;
3037 }
3038 // there has recently been an underrun of some kind
3039 if (track->sharedBuffer() == 0) {
3040 // were any of the recent underruns "empty" (no frames available)?
3041 if (recentEmpty == 0) {
3042 // no, then ignore the partial underruns as they are allowed indefinitely
3043 break;
3044 }
3045 // there has recently been an "empty" underrun: decrement the retry counter
3046 if (--(track->mRetryCount) > 0) {
3047 break;
3048 }
3049 // indicate to client process that the track was disabled because of underrun;
3050 // it will then automatically call start() when data is available
Glenn Kastend12b0332012-11-05 13:38:15 -08003051 android_atomic_or(CBLK_DISABLED, &track->mCblk->flags);
Glenn Kasten09474df2012-05-10 14:48:07 -07003052 // remove from active list, but state remains ACTIVE [confusing but true]
3053 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003054 break;
3055 }
3056 // fall through
3057 case TrackBase::STOPPING_2:
3058 case TrackBase::PAUSED:
3059 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07003060 case TrackBase::STOPPED:
3061 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07003062 // Check for presentation complete if track is inactive
3063 // We have consumed all the buffers of this track.
3064 // This would be incomplete if we auto-paused on underrun
3065 {
3066 size_t audioHALFrames =
3067 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3068 size_t framesWritten =
3069 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten126c9102012-10-18 15:51:31 -07003070 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
Glenn Kastend08f48c2012-05-01 18:14:02 -07003071 // track stays in active list until presentation is complete
3072 break;
3073 }
3074 }
3075 if (track->isStopping_2()) {
3076 track->mState = TrackBase::STOPPED;
3077 }
3078 if (track->isStopped()) {
3079 // Can't reset directly, as fast mixer is still polling this track
3080 // track->reset();
3081 // So instead mark this track as needing to be reset after push with ack
3082 resetMask |= 1 << i;
3083 }
3084 isActive = false;
3085 break;
3086 case TrackBase::IDLE:
3087 default:
3088 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003089 }
3090
3091 if (isActive) {
3092 // was it previously inactive?
3093 if (!(state->mTrackMask & (1 << j))) {
3094 ExtendedAudioBufferProvider *eabp = track;
3095 VolumeProvider *vp = track;
3096 fastTrack->mBufferProvider = eabp;
3097 fastTrack->mVolumeProvider = vp;
3098 fastTrack->mSampleRate = track->mSampleRate;
3099 fastTrack->mChannelMask = track->mChannelMask;
3100 fastTrack->mGeneration++;
3101 state->mTrackMask |= 1 << j;
3102 didModify = true;
3103 // no acknowledgement required for newly active tracks
3104 }
3105 // cache the combined master volume and stream type volume for fast mixer; this
3106 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3107 track->mCachedVolume = track->isMuted() ?
3108 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3109 ++fastTracks;
3110 } else {
3111 // was it previously active?
3112 if (state->mTrackMask & (1 << j)) {
3113 fastTrack->mBufferProvider = NULL;
3114 fastTrack->mGeneration++;
3115 state->mTrackMask &= ~(1 << j);
3116 didModify = true;
3117 // If any fast tracks were removed, we must wait for acknowledgement
3118 // because we're about to decrement the last sp<> on those tracks.
3119 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003120 } else {
3121 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003122 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003123 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003124 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003125 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003126 }
3127 continue;
3128 }
3129
3130 { // local variable scope to avoid goto warning
3131
Mathias Agopian65ab4712010-07-14 17:59:35 -07003132 audio_track_cblk_t* cblk = track->cblk();
3133
3134 // The first time a track is added we wait
3135 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003136 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003137 // make sure that we have enough frames to mix one full buffer.
3138 // enforce this condition only once to enable draining the buffer in case the client
3139 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003140 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003141 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003142 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003143 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003144 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten1127d652012-11-14 08:44:39 -08003145 if (t->sampleRate() == mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003146 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003147 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003148 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003149 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003150 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003151 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003152 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3153 // the minimum track buffer size is normally twice the number of frames necessary
3154 // to fill one buffer and the resampler should not leave more than one buffer worth
3155 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003156 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003157 }
3158 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003159 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003160 !track->isPaused() && !track->isTerminated())
3161 {
Glenn Kasten8af901c2012-11-01 11:11:38 -07003162 ALOGVV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server,
3163 this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003164
3165 mixedTracks++;
3166
3167 // track->mainBuffer() != mMixBuffer means there is an effect chain
3168 // connected to the track
3169 chain.clear();
3170 if (track->mainBuffer() != mMixBuffer) {
3171 chain = getEffectChain_l(track->sessionId());
3172 // Delegate volume control to effect in track effect chain if needed
3173 if (chain != 0) {
3174 tracksWithEffect++;
3175 } else {
Glenn Kasten8af901c2012-11-01 11:11:38 -07003176 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3177 "session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003178 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003179 }
3180 }
3181
3182
3183 int param = AudioMixer::VOLUME;
3184 if (track->mFillingUpStatus == Track::FS_FILLED) {
3185 // no ramp for the first volume setting
3186 track->mFillingUpStatus = Track::FS_ACTIVE;
3187 if (track->mState == TrackBase::RESUMING) {
3188 track->mState = TrackBase::ACTIVE;
3189 param = AudioMixer::RAMP_VOLUME;
3190 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003191 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003192 } else if (cblk->server != 0) {
3193 // If the track is stopped before the first frame was mixed,
3194 // do not apply ramp
3195 param = AudioMixer::RAMP_VOLUME;
3196 }
3197
3198 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003199 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003200 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003201 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003202 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003203 if (track->isPausing()) {
3204 track->setPaused();
3205 }
3206 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003207
Mathias Agopian65ab4712010-07-14 17:59:35 -07003208 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003209 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003210 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003211 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003212 vl = vlr & 0xFFFF;
3213 vr = vlr >> 16;
3214 // track volumes come from shared memory, so can't be trusted and must be clamped
3215 if (vl > MAX_GAIN_INT) {
3216 ALOGV("Track left volume out of range: %04X", vl);
3217 vl = MAX_GAIN_INT;
3218 }
3219 if (vr > MAX_GAIN_INT) {
3220 ALOGV("Track right volume out of range: %04X", vr);
3221 vr = MAX_GAIN_INT;
3222 }
3223 // now apply the master volume and stream type volume
3224 vl = (uint32_t)(v * vl) << 12;
3225 vr = (uint32_t)(v * vr) << 12;
3226 // assuming master volume and stream type volume each go up to 1.0,
3227 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003228
Glenn Kasten05632a52012-01-03 14:22:33 -08003229 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3230 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003231 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003232 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003233 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003234 }
3235 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003236 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003237 // Delegate volume control to effect in track effect chain if needed
3238 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3239 // Do not ramp volume if volume is controlled by effect
3240 param = AudioMixer::VOLUME;
3241 track->mHasVolumeController = true;
3242 } else {
3243 // force no volume ramp when volume controller was just disabled or removed
3244 // from effect chain to avoid volume spike
3245 if (track->mHasVolumeController) {
3246 param = AudioMixer::VOLUME;
3247 }
3248 track->mHasVolumeController = false;
3249 }
3250
3251 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003252 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003253 vl = (vl + (1 << 11)) >> 12;
Glenn Kastena2049222012-06-22 17:21:07 -07003254 if (vl > MAX_GAIN_INT) {
3255 vl = MAX_GAIN_INT;
3256 }
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003257 vr = (vr + (1 << 11)) >> 12;
Glenn Kastena2049222012-06-22 17:21:07 -07003258 if (vr > MAX_GAIN_INT) {
3259 vr = MAX_GAIN_INT;
3260 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003261
Glenn Kastena2049222012-06-22 17:21:07 -07003262 if (va > MAX_GAIN_INT) {
3263 va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
3264 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003265
Mathias Agopian65ab4712010-07-14 17:59:35 -07003266 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003267 mAudioMixer->setBufferProvider(name, track);
3268 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003269
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003270 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3271 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3272 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003273 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003274 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003275 AudioMixer::TRACK,
3276 AudioMixer::FORMAT, (void *)track->format());
3277 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003278 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003279 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003280 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003281 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003282 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003283 AudioMixer::RESAMPLE,
3284 AudioMixer::SAMPLE_RATE,
3285 (void *)(cblk->sampleRate));
3286 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003287 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003288 AudioMixer::TRACK,
3289 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3290 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003291 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003292 AudioMixer::TRACK,
3293 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3294
3295 // reset retry count
3296 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003297
Eric Laurent27741442012-01-17 19:20:12 -08003298 // If one track is ready, set the mixer ready if:
3299 // - the mixer was not ready during previous round OR
3300 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003301 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003302 mixerStatus != MIXER_TRACKS_ENABLED) {
3303 mixerStatus = MIXER_TRACKS_READY;
3304 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003305 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003306 // clear effect chain input buffer if an active track underruns to avoid sending
3307 // previous audio buffer again to effects
3308 chain = getEffectChain_l(track->sessionId());
3309 if (chain != 0) {
3310 chain->clearInputBuffer();
3311 }
3312
Glenn Kasten8af901c2012-11-01 11:11:38 -07003313 ALOGVV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user,
3314 cblk->server, this);
Glenn Kasten52013e72012-09-26 08:34:10 -07003315 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent83faee02012-04-27 18:24:29 -07003316 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003317 // We have consumed all the buffers of this track.
3318 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003319 // TODO: use actual buffer filling status instead of latency when available from
3320 // audio HAL
Jean-Michel Trivi115b87e2012-10-16 10:29:01 -07003321 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07003322 size_t framesWritten =
3323 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten126c9102012-10-18 15:51:31 -07003324 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003325 if (track->isStopped()) {
3326 track->reset();
3327 }
Eric Laurenta011e352012-03-29 15:51:43 -07003328 tracksToRemove->add(track);
3329 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003330 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003331 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332 // No buffers for this track. Give it a few chances to
3333 // fill a buffer, then remove it from active list.
Glenn Kasten52013e72012-09-26 08:34:10 -07003334 if (--(track->mRetryCount) <= 0) {
3335 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003336 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003337 // indicate to client process that the track was disabled because of underrun;
3338 // it will then automatically call start() when data is available
Glenn Kastend12b0332012-11-05 13:38:15 -08003339 android_atomic_or(CBLK_DISABLED, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003340 // If one track is not ready, mark the mixer also not ready if:
3341 // - the mixer was ready during previous round OR
3342 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003343 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003344 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003345 mixerStatus = MIXER_TRACKS_ENABLED;
3346 }
3347 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003348 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003349 }
Glenn Kasten58912562012-04-03 10:45:00 -07003350
3351 } // local variable scope to avoid goto warning
3352track_is_ready: ;
3353
Mathias Agopian65ab4712010-07-14 17:59:35 -07003354 }
3355
Glenn Kasten288ed212012-04-25 17:52:27 -07003356 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003357 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003358 if (didModify) {
3359 state->mFastTracksGen++;
3360 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3361 if (kUseFastMixer == FastMixer_Dynamic &&
3362 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3363 state->mCommand = FastMixerState::COLD_IDLE;
3364 state->mColdFutexAddr = &mFastMixerFutex;
3365 state->mColdGen++;
3366 mFastMixerFutex = 0;
3367 if (kUseFastMixer == FastMixer_Dynamic) {
3368 mNormalSink = mOutputSink;
3369 }
3370 // If we go into cold idle, need to wait for acknowledgement
3371 // so that fast mixer stops doing I/O.
3372 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003373 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003374 }
3375 sq->end();
3376 }
3377 if (sq != NULL) {
3378 sq->end(didModify);
3379 sq->push(block);
3380 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07003381#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003382 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3383 mAudioWatchdog->pause();
3384 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07003385#endif
Glenn Kasten288ed212012-04-25 17:52:27 -07003386
3387 // Now perform the deferred reset on fast tracks that have stopped
3388 while (resetMask != 0) {
3389 size_t i = __builtin_ctz(resetMask);
3390 ALOG_ASSERT(i < count);
3391 resetMask &= ~(1 << i);
3392 sp<Track> t = mActiveTracks[i].promote();
Glenn Kastena2049222012-06-22 17:21:07 -07003393 if (t == 0) {
3394 continue;
3395 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003396 Track* track = t.get();
3397 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3398 track->reset();
3399 }
Glenn Kasten58912562012-04-03 10:45:00 -07003400
Mathias Agopian65ab4712010-07-14 17:59:35 -07003401 // remove all the tracks that need to be...
3402 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003403 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003404 for (size_t i=0 ; i<count ; i++) {
3405 const sp<Track>& track = tracksToRemove->itemAt(i);
3406 mActiveTracks.remove(track);
3407 if (track->mainBuffer() != mMixBuffer) {
3408 chain = getEffectChain_l(track->sessionId());
3409 if (chain != 0) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07003410 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3411 track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003412 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003413 }
3414 }
3415 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003416 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003417 }
3418 }
3419 }
3420
3421 // mix buffer must be cleared if all tracks are connected to an
3422 // effect chain as in this case the mixer will not write to
3423 // mix buffer and track effects will accumulate into it
Glenn Kasten8af901c2012-11-01 11:11:38 -07003424 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3425 (mixedTracks == 0 && fastTracks > 0)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003426 // FIXME as a performance optimization, should remember previous zero status
3427 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003428 }
3429
Glenn Kasten58912562012-04-03 10:45:00 -07003430 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003431 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003432 if (fastTracks > 0) {
3433 mixerStatus = MIXER_TRACKS_READY;
3434 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003435 return mixerStatus;
3436}
3437
Glenn Kasten66fcab92012-02-24 14:59:21 -08003438/*
3439The derived values that are cached:
3440 - mixBufferSize from frame count * frame size
3441 - activeSleepTime from activeSleepTimeUs()
3442 - idleSleepTime from idleSleepTimeUs()
3443 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3444 - maxPeriod from frame count and sample rate (MIXER only)
3445
3446The parameters that affect these derived values are:
3447 - frame count
3448 - frame size
3449 - sample rate
3450 - device type: A2DP or not
3451 - device latency
3452 - format: PCM or not
3453 - active sleep time
3454 - idle sleep time
3455*/
3456
3457void AudioFlinger::PlaybackThread::cacheParameters_l()
3458{
Glenn Kasten58912562012-04-03 10:45:00 -07003459 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003460 activeSleepTime = activeSleepTimeUs();
3461 idleSleepTime = idleSleepTimeUs();
3462}
3463
Eric Laurent22167852012-06-20 12:26:32 -07003464void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003465{
Steve Block3856b092011-10-20 11:56:00 +01003466 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003467 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003468 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003469
Mathias Agopian65ab4712010-07-14 17:59:35 -07003470 size_t size = mTracks.size();
3471 for (size_t i = 0; i < size; i++) {
3472 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003473 if (t->streamType() == streamType) {
Glenn Kastend12b0332012-11-05 13:38:15 -08003474 android_atomic_or(CBLK_INVALID, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003475 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003476 }
3477 }
3478}
3479
Mathias Agopian65ab4712010-07-14 17:59:35 -07003480// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivicff71372012-09-10 18:58:27 -07003481int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003482{
Jean-Michel Trivicff71372012-09-10 18:58:27 -07003483 return mAudioMixer->getTrackName(channelMask, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003484}
3485
3486// deleteTrackName_l() must be called with ThreadBase::mLock held
3487void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3488{
Steve Block3856b092011-10-20 11:56:00 +01003489 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003490 mAudioMixer->deleteTrackName(name);
3491}
3492
3493// checkForNewParameters_l() must be called with ThreadBase::mLock held
3494bool AudioFlinger::MixerThread::checkForNewParameters_l()
3495{
Glenn Kasten58912562012-04-03 10:45:00 -07003496 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3497 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003498 bool reconfig = false;
3499
3500 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003501
3502 if (mFastMixer != NULL) {
3503 FastMixerStateQueue *sq = mFastMixer->sq();
3504 FastMixerState *state = sq->begin();
3505 if (!(state->mCommand & FastMixerState::IDLE)) {
3506 previousCommand = state->mCommand;
3507 state->mCommand = FastMixerState::HOT_IDLE;
3508 sq->end();
3509 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3510 } else {
3511 sq->end(false /*didModify*/);
3512 }
3513 }
3514
Mathias Agopian65ab4712010-07-14 17:59:35 -07003515 status_t status = NO_ERROR;
3516 String8 keyValuePair = mNewParameters[0];
3517 AudioParameter param = AudioParameter(keyValuePair);
3518 int value;
3519
3520 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3521 reconfig = true;
3522 }
3523 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003524 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003525 status = BAD_VALUE;
3526 } else {
3527 reconfig = true;
3528 }
3529 }
3530 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003531 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003532 status = BAD_VALUE;
3533 } else {
3534 reconfig = true;
3535 }
3536 }
3537 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3538 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003539 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003540 // if frame count is changed after track creation
3541 if (!mTracks.isEmpty()) {
3542 status = INVALID_OPERATION;
3543 } else {
3544 reconfig = true;
3545 }
3546 }
3547 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003548#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003549 // when changing the audio output device, call addBatteryData to notify
3550 // the change
Eric Laurent88959252012-08-28 14:26:53 -07003551 if (mOutDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003552 uint32_t params = 0;
3553 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003554 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003555 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3556 }
3557
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003558 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003559 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003560 // check if any other device (except speaker) is on
3561 if (value & deviceWithoutSpeaker ) {
3562 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3563 }
3564
3565 if (params != 0) {
3566 addBatteryData(params);
3567 }
3568 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003569#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003570
Mathias Agopian65ab4712010-07-14 17:59:35 -07003571 // forward device change to effects that have requested to be
3572 // aware of attached audio device.
Eric Laurent88959252012-08-28 14:26:53 -07003573 mOutDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003574 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent88959252012-08-28 14:26:53 -07003575 mEffectChains[i]->setDevice_l(mOutDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003576 }
3577 }
3578
3579 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003580 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003581 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003582 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003583 mOutput->stream->common.standby(&mOutput->stream->common);
3584 mStandby = true;
3585 mBytesWritten = 0;
3586 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003587 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003588 }
3589 if (status == NO_ERROR && reconfig) {
3590 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003591 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3592 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003593 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003594 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003595 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivicff71372012-09-10 18:58:27 -07003596 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
Glenn Kastena2049222012-06-22 17:21:07 -07003597 if (name < 0) {
3598 break;
3599 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003600 mTracks[i]->mName = name;
3601 // limit track sample rate to 2 x new output sample rate
3602 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3603 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3604 }
3605 }
Eric Laurentef6be0b2012-09-13 11:18:23 -07003606 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003607 }
3608 }
3609
3610 mNewParameters.removeAt(0);
3611
3612 mParamStatus = status;
3613 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003614 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3615 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003616 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003617 }
Glenn Kasten58912562012-04-03 10:45:00 -07003618
3619 if (!(previousCommand & FastMixerState::IDLE)) {
3620 ALOG_ASSERT(mFastMixer != NULL);
3621 FastMixerStateQueue *sq = mFastMixer->sq();
3622 FastMixerState *state = sq->begin();
3623 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3624 state->mCommand = previousCommand;
3625 sq->end();
3626 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3627 }
3628
Mathias Agopian65ab4712010-07-14 17:59:35 -07003629 return reconfig;
3630}
3631
Glenn Kasten8c327342012-09-30 12:29:28 -07003632void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003633{
Glenn Kasten8c327342012-09-30 12:29:28 -07003634 NBAIO_Source *teeSource = source.get();
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003635 if (teeSource != NULL) {
Glenn Kasten8c327342012-09-30 12:29:28 -07003636 char teeTime[16];
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003637 struct timeval tv;
3638 gettimeofday(&tv, NULL);
3639 struct tm tm;
3640 localtime_r(&tv.tv_sec, &tm);
Glenn Kasten8c327342012-09-30 12:29:28 -07003641 strftime(teeTime, sizeof(teeTime), "%T", &tm);
3642 char teePath[64];
3643 sprintf(teePath, "/data/misc/media/%s_%d.wav", teeTime, id);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003644 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3645 if (teeFd >= 0) {
3646 char wavHeader[44];
3647 memcpy(wavHeader,
3648 "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",
3649 sizeof(wavHeader));
3650 NBAIO_Format format = teeSource->format();
3651 unsigned channelCount = Format_channelCount(format);
3652 ALOG_ASSERT(channelCount <= FCC_2);
Glenn Kasten1127d652012-11-14 08:44:39 -08003653 uint32_t sampleRate = Format_sampleRate(format);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003654 wavHeader[22] = channelCount; // number of channels
3655 wavHeader[24] = sampleRate; // sample rate
3656 wavHeader[25] = sampleRate >> 8;
3657 wavHeader[32] = channelCount * 2; // block alignment
3658 write(teeFd, wavHeader, sizeof(wavHeader));
3659 size_t total = 0;
3660 bool firstRead = true;
3661 for (;;) {
3662#define TEE_SINK_READ 1024
3663 short buffer[TEE_SINK_READ * FCC_2];
3664 size_t count = TEE_SINK_READ;
John Grossman2c3b2da2012-08-02 17:08:54 -07003665 ssize_t actual = teeSource->read(buffer, count,
3666 AudioBufferProvider::kInvalidPTS);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003667 bool wasFirstRead = firstRead;
3668 firstRead = false;
3669 if (actual <= 0) {
3670 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3671 continue;
3672 }
3673 break;
3674 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003675 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003676 write(teeFd, buffer, actual * channelCount * sizeof(short));
3677 total += actual;
3678 }
3679 lseek(teeFd, (off_t) 4, SEEK_SET);
3680 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3681 write(teeFd, &temp, sizeof(temp));
3682 lseek(teeFd, (off_t) 40, SEEK_SET);
3683 temp = total * channelCount * sizeof(short);
3684 write(teeFd, &temp, sizeof(temp));
3685 close(teeFd);
3686 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3687 } else {
3688 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3689 }
3690 }
Glenn Kasten8c327342012-09-30 12:29:28 -07003691}
3692
3693void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3694{
3695 const size_t SIZE = 256;
3696 char buffer[SIZE];
3697 String8 result;
3698
3699 PlaybackThread::dumpInternals(fd, args);
3700
3701 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3702 result.append(buffer);
3703 write(fd, result.string(), result.size());
3704
3705 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3706 FastMixerDumpState copy = mFastMixerDumpState;
3707 copy.dump(fd);
3708
3709#ifdef STATE_QUEUE_DUMP
3710 // Similar for state queue
3711 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3712 observerCopy.dump(fd);
3713 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3714 mutatorCopy.dump(fd);
3715#endif
3716
3717 // Write the tee output to a .wav file
3718 dumpTee(fd, mTeeSource, mId);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003719
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07003720#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003721 if (mAudioWatchdog != 0) {
3722 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3723 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3724 wdCopy.dump(fd);
3725 }
Glenn Kasten02e5dbb2012-09-27 13:49:02 -07003726#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003727}
3728
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003729uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003730{
Glenn Kasten58912562012-04-03 10:45:00 -07003731 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003732}
3733
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003734uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003735{
Glenn Kasten58912562012-04-03 10:45:00 -07003736 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003737}
3738
Glenn Kasten66fcab92012-02-24 14:59:21 -08003739void AudioFlinger::MixerThread::cacheParameters_l()
3740{
3741 PlaybackThread::cacheParameters_l();
3742
3743 // FIXME: Relaxed timing because of a certain device that can't meet latency
3744 // Should be reduced to 2x after the vendor fixes the driver issue
3745 // increase threshold again due to low power audio mode. The way this warning
3746 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003747 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003748}
3749
Mathias Agopian65ab4712010-07-14 17:59:35 -07003750// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003751AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003752 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003753 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003754 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003755{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003756}
3757
3758AudioFlinger::DirectOutputThread::~DirectOutputThread()
3759{
3760}
3761
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003762AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3763 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003764)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003765{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003766 sp<Track> trackToRemove;
3767
Glenn Kastenfec279f2012-03-08 07:47:15 -08003768 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003769
Glenn Kasten952eeb22012-03-06 11:30:57 -08003770 // find out which tracks need to be processed
3771 if (mActiveTracks.size() != 0) {
3772 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003773 // The track died recently
Glenn Kastena2049222012-06-22 17:21:07 -07003774 if (t == 0) {
3775 return MIXER_IDLE;
3776 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003777
Glenn Kasten952eeb22012-03-06 11:30:57 -08003778 Track* const track = t.get();
3779 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003780
Glenn Kasten952eeb22012-03-06 11:30:57 -08003781 // The first time a track is added we wait
3782 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003783 uint32_t minFrames;
3784 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3785 minFrames = mNormalFrameCount;
3786 } else {
3787 minFrames = 1;
3788 }
3789 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003790 !track->isPaused() && !track->isTerminated())
3791 {
Glenn Kastencbe4b362012-10-18 15:51:03 -07003792 ALOGVV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003793
Glenn Kasten952eeb22012-03-06 11:30:57 -08003794 if (track->mFillingUpStatus == Track::FS_FILLED) {
3795 track->mFillingUpStatus = Track::FS_ACTIVE;
3796 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003797 if (track->mState == TrackBase::RESUMING) {
3798 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003799 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003800 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003801
Glenn Kasten952eeb22012-03-06 11:30:57 -08003802 // compute volume for this track
3803 float left, right;
3804 if (track->isMuted() || mMasterMute || track->isPausing() ||
3805 mStreamTypes[track->streamType()].mute) {
3806 left = right = 0;
3807 if (track->isPausing()) {
3808 track->setPaused();
3809 }
3810 } else {
3811 float typeVolume = mStreamTypes[track->streamType()].volume;
3812 float v = mMasterVolume * typeVolume;
3813 uint32_t vlr = cblk->getVolumeLR();
3814 float v_clamped = v * (vlr & 0xFFFF);
Glenn Kastena2049222012-06-22 17:21:07 -07003815 if (v_clamped > MAX_GAIN) {
3816 v_clamped = MAX_GAIN;
3817 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003818 left = v_clamped/MAX_GAIN;
3819 v_clamped = v * (vlr >> 16);
Glenn Kastena2049222012-06-22 17:21:07 -07003820 if (v_clamped > MAX_GAIN) {
3821 v_clamped = MAX_GAIN;
3822 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003823 right = v_clamped/MAX_GAIN;
3824 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003825
Glenn Kasten952eeb22012-03-06 11:30:57 -08003826 if (left != mLeftVolFloat || right != mRightVolFloat) {
3827 mLeftVolFloat = left;
3828 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003829
Glenn Kasten952eeb22012-03-06 11:30:57 -08003830 // Convert volumes from float to 8.24
3831 uint32_t vl = (uint32_t)(left * (1 << 24));
3832 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003833
Glenn Kasten952eeb22012-03-06 11:30:57 -08003834 // Delegate volume control to effect in track effect chain if needed
3835 // only one effect chain can be present on DirectOutputThread, so if
3836 // there is one, the track is connected to it
3837 if (!mEffectChains.isEmpty()) {
3838 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003839 mEffectChains[0]->setVolume_l(&vl, &vr);
3840 left = (float)vl / (1 << 24);
3841 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003842 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003843 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003844 }
3845
3846 // reset retry count
3847 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003848 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003849 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003850 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003851 // clear effect chain input buffer if an active track underruns to avoid sending
3852 // previous audio buffer again to effects
3853 if (!mEffectChains.isEmpty()) {
3854 mEffectChains[0]->clearInputBuffer();
3855 }
3856
Glenn Kastencbe4b362012-10-18 15:51:03 -07003857 ALOGVV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten52013e72012-09-26 08:34:10 -07003858 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent67c0a582012-05-01 19:31:12 -07003859 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003860 // We have consumed all the buffers of this track.
3861 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003862 // TODO: implement behavior for compressed audio
Jean-Michel Trivi115b87e2012-10-16 10:29:01 -07003863 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07003864 size_t framesWritten =
3865 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten126c9102012-10-18 15:51:31 -07003866 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003867 if (track->isStopped()) {
3868 track->reset();
3869 }
Eric Laurenta011e352012-03-29 15:51:43 -07003870 trackToRemove = track;
3871 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003872 } else {
3873 // No buffers for this track. Give it a few chances to
3874 // fill a buffer, then remove it from active list.
Glenn Kasten52013e72012-09-26 08:34:10 -07003875 if (--(track->mRetryCount) <= 0) {
3876 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Glenn Kasten952eeb22012-03-06 11:30:57 -08003877 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003878 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003879 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003880 }
3881 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003882 }
3883 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003884
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003885 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003886 // remove all the tracks that need to be...
3887 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003888 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003889 mActiveTracks.remove(trackToRemove);
3890 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003891 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003892 trackToRemove->sessionId());
3893 mEffectChains[0]->decActiveTrackCnt();
3894 }
3895 if (trackToRemove->isTerminated()) {
3896 removeTrack_l(trackToRemove);
3897 }
3898 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003899
Glenn Kastenfec279f2012-03-08 07:47:15 -08003900 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003901}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003902
Glenn Kasten000f0e32012-03-01 17:10:56 -08003903void AudioFlinger::DirectOutputThread::threadLoop_mix()
3904{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003905 AudioBufferProvider::Buffer buffer;
3906 size_t frameCount = mFrameCount;
3907 int8_t *curBuf = (int8_t *)mMixBuffer;
3908 // output audio to hardware
3909 while (frameCount) {
3910 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003911 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003912 if (CC_UNLIKELY(buffer.raw == NULL)) {
3913 memset(curBuf, 0, frameCount * mFrameSize);
3914 break;
3915 }
3916 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3917 frameCount -= buffer.frameCount;
3918 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003919 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003920 }
3921 sleepTime = 0;
3922 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003923 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003924
Glenn Kasten000f0e32012-03-01 17:10:56 -08003925}
3926
3927void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3928{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003929 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003930 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003931 sleepTime = activeSleepTime;
3932 } else {
3933 sleepTime = idleSleepTime;
3934 }
3935 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003936 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003937 sleepTime = 0;
3938 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003939}
3940
3941// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivicff71372012-09-10 18:58:27 -07003942int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3943 int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003944{
3945 return 0;
3946}
3947
3948// deleteTrackName_l() must be called with ThreadBase::mLock held
3949void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3950{
3951}
3952
3953// checkForNewParameters_l() must be called with ThreadBase::mLock held
3954bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3955{
3956 bool reconfig = false;
3957
3958 while (!mNewParameters.isEmpty()) {
3959 status_t status = NO_ERROR;
3960 String8 keyValuePair = mNewParameters[0];
3961 AudioParameter param = AudioParameter(keyValuePair);
3962 int value;
3963
3964 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3965 // do not accept frame count changes if tracks are open as the track buffer
3966 // size depends on frame count and correct behavior would not be garantied
3967 // if frame count is changed after track creation
3968 if (!mTracks.isEmpty()) {
3969 status = INVALID_OPERATION;
3970 } else {
3971 reconfig = true;
3972 }
3973 }
3974 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003975 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003976 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003977 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003978 mOutput->stream->common.standby(&mOutput->stream->common);
3979 mStandby = true;
3980 mBytesWritten = 0;
3981 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003982 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003983 }
3984 if (status == NO_ERROR && reconfig) {
3985 readOutputParameters();
Eric Laurentef6be0b2012-09-13 11:18:23 -07003986 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003987 }
3988 }
3989
3990 mNewParameters.removeAt(0);
3991
3992 mParamStatus = status;
3993 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003994 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3995 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003996 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003997 }
3998 return reconfig;
3999}
4000
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004001uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004002{
4003 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004004 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08004005 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004006 } else {
4007 time = 10000;
4008 }
4009 return time;
4010}
4011
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004012uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004013{
4014 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004015 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07004016 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004017 } else {
4018 time = 10000;
4019 }
4020 return time;
4021}
4022
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004023uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004024{
4025 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07004026 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004027 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
4028 } else {
4029 time = 10000;
4030 }
4031 return time;
4032}
4033
Glenn Kasten66fcab92012-02-24 14:59:21 -08004034void AudioFlinger::DirectOutputThread::cacheParameters_l()
4035{
4036 PlaybackThread::cacheParameters_l();
4037
4038 // use shorter standby delay as on normal output to release
4039 // hardware resources as soon as possible
4040 standbyDelay = microseconds(activeSleepTime*2);
4041}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004042
Mathias Agopian65ab4712010-07-14 17:59:35 -07004043// ----------------------------------------------------------------------------
4044
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004045AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004046 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten8af901c2012-11-01 11:11:38 -07004047 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4048 DUPLICATING),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004049 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004050{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004051 addOutputTrack(mainThread);
4052}
4053
4054AudioFlinger::DuplicatingThread::~DuplicatingThread()
4055{
4056 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4057 mOutputTracks[i]->destroy();
4058 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004059}
4060
Glenn Kasten000f0e32012-03-01 17:10:56 -08004061void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004062{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004063 // mix buffers...
4064 if (outputsReady(outputTracks)) {
4065 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4066 } else {
4067 memset(mMixBuffer, 0, mixBufferSize);
4068 }
4069 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07004070 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004071 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004072}
4073
4074void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4075{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004076 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004077 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004078 sleepTime = activeSleepTime;
4079 } else {
4080 sleepTime = idleSleepTime;
4081 }
4082 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004083 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4084 writeFrames = mNormalFrameCount;
4085 memset(mMixBuffer, 0, mixBufferSize);
4086 } else {
4087 // flush remaining overflow buffers in output tracks
4088 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004089 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004090 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004091 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08004092}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004093
Glenn Kasten000f0e32012-03-01 17:10:56 -08004094void AudioFlinger::DuplicatingThread::threadLoop_write()
4095{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004096 for (size_t i = 0; i < outputTracks.size(); i++) {
4097 outputTracks[i]->write(mMixBuffer, writeFrames);
4098 }
4099 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004100}
Glenn Kasten688a6402012-02-29 07:57:06 -08004101
Glenn Kasten000f0e32012-03-01 17:10:56 -08004102void AudioFlinger::DuplicatingThread::threadLoop_standby()
4103{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004104 // DuplicatingThread implements standby by stopping all tracks
4105 for (size_t i = 0; i < outputTracks.size(); i++) {
4106 outputTracks[i]->stop();
4107 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004108}
4109
Glenn Kastenfa26a852012-03-06 11:28:04 -08004110void AudioFlinger::DuplicatingThread::saveOutputTracks()
4111{
4112 outputTracks = mOutputTracks;
4113}
4114
4115void AudioFlinger::DuplicatingThread::clearOutputTracks()
4116{
4117 outputTracks.clear();
4118}
4119
Mathias Agopian65ab4712010-07-14 17:59:35 -07004120void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4121{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004122 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004123 // FIXME explain this formula
Glenn Kasten7da35f22012-11-14 12:54:39 -08004124 size_t frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004125 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004126 this,
4127 mSampleRate,
4128 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004129 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004130 frameCount);
4131 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004132 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004133 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004134 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004135 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004136 }
4137}
4138
4139void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4140{
4141 Mutex::Autolock _l(mLock);
4142 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004143 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004144 mOutputTracks[i]->destroy();
4145 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004146 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004147 return;
4148 }
4149 }
Steve Block3856b092011-10-20 11:56:00 +01004150 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004151}
4152
Glenn Kasten438b0362012-03-06 11:24:48 -08004153// caller must hold mLock
4154void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004155{
4156 mWaitTimeMs = UINT_MAX;
4157 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4158 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004159 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004160 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4161 if (waitTimeMs < mWaitTimeMs) {
4162 mWaitTimeMs = waitTimeMs;
4163 }
4164 }
4165 }
4166}
4167
4168
Glenn Kasten8af901c2012-11-01 11:11:38 -07004169bool AudioFlinger::DuplicatingThread::outputsReady(
4170 const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004171{
4172 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004173 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004174 if (thread == 0) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07004175 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4176 outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004177 return false;
4178 }
4179 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004180 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004181 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07004182 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4183 thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004184 return false;
4185 }
4186 }
4187 return true;
4188}
4189
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004190uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004191{
4192 return (mWaitTimeMs * 1000) / 2;
4193}
4194
Glenn Kasten66fcab92012-02-24 14:59:21 -08004195void AudioFlinger::DuplicatingThread::cacheParameters_l()
4196{
4197 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4198 updateWaitTime_l();
4199
4200 MixerThread::cacheParameters_l();
4201}
4202
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203// ----------------------------------------------------------------------------
4204
4205// TrackBase constructor must be called with AudioFlinger::mLock held
4206AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004207 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004208 const sp<Client>& client,
4209 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004210 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004211 audio_channel_mask_t channelMask,
Glenn Kasten7da35f22012-11-14 12:54:39 -08004212 size_t frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004213 const sp<IMemory>& sharedBuffer,
4214 int sessionId)
4215 : RefBase(),
4216 mThread(thread),
4217 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004218 mCblk(NULL),
4219 // mBuffer
4220 // mBufferEnd
Glenn Kastene2a05862012-11-13 09:58:55 -08004221 mStepCount(0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004222 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004223 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004224 mFormat(format),
Glenn Kasten520a9af2012-06-21 12:56:37 -07004225 mChannelMask(channelMask),
4226 mChannelCount(popcount(channelMask)),
4227 mFrameSize(audio_is_linear_pcm(format) ?
4228 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004229 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004230 mSessionId(sessionId)
4231{
Glenn Kastenac657262012-11-05 13:39:09 -08004232 // client == 0 implies sharedBuffer == 0
4233 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
4234
Glenn Kasten8af901c2012-11-01 11:11:38 -07004235 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
4236 sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004237
Steve Blockb8a80522011-12-20 16:23:08 +00004238 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004239 size_t size = sizeof(audio_track_cblk_t);
Glenn Kasten520a9af2012-06-21 12:56:37 -07004240 size_t bufferSize = frameCount * mFrameSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004241 if (sharedBuffer == 0) {
4242 size += bufferSize;
4243 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004244
Glenn Kastenac657262012-11-05 13:39:09 -08004245 if (client != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004246 mCblkMemory = client->heap()->allocate(size);
4247 if (mCblkMemory != 0) {
4248 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastenac657262012-11-05 13:39:09 -08004249 // can't assume mCblk != NULL
Mathias Agopian65ab4712010-07-14 17:59:35 -07004250 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004251 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004252 client->heap()->dump("AudioTrack");
4253 return;
4254 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004255 } else {
4256 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenac657262012-11-05 13:39:09 -08004257 // assume mCblk != NULL
4258 }
4259
4260 // construct the shared structure in-place.
4261 if (mCblk != NULL) {
Glenn Kastenea7939a2012-03-14 12:56:26 -07004262 new(mCblk) audio_track_cblk_t();
4263 // clear all buffers
4264 mCblk->frameCount = frameCount;
4265 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004266// uncomment the following lines to quickly test 32-bit wraparound
Glenn Kastenac657262012-11-05 13:39:09 -08004267// mCblk->user = 0xffff0000;
4268// mCblk->server = 0xffff0000;
4269// mCblk->userBase = 0xffff0000;
4270// mCblk->serverBase = 0xffff0000;
Glenn Kastenac657262012-11-05 13:39:09 -08004271 if (sharedBuffer == 0) {
4272 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
Glenn Kasten520a9af2012-06-21 12:56:37 -07004273 memset(mBuffer, 0, bufferSize);
Glenn Kastenac657262012-11-05 13:39:09 -08004274 // Force underrun condition to avoid false underrun callback until first data is
4275 // written to buffer (other flags are cleared)
4276 mCblk->flags = CBLK_UNDERRUN;
4277 } else {
4278 mBuffer = sharedBuffer->pointer();
4279 }
Glenn Kastenea7939a2012-03-14 12:56:26 -07004280 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004281 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004282}
4283
4284AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4285{
Glenn Kastena0d68332012-01-27 16:47:15 -08004286 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004287 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004288 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004289 } else {
4290 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004291 }
4292 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004293 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004294 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004295 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004296 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004297 // If the client's reference count drops to zero, the associated destructor
4298 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4299 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004300 mClient.clear();
4301 }
4302}
4303
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004304// AudioBufferProvider interface
4305// getNextBuffer() = 0;
4306// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004307void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4308{
Glenn Kastene0feee32011-12-13 11:53:26 -08004309 buffer->raw = NULL;
Glenn Kastene2a05862012-11-13 09:58:55 -08004310 mStepCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004311 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004312 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004313 buffer->frameCount = 0;
4314}
4315
4316bool AudioFlinger::ThreadBase::TrackBase::step() {
4317 bool result;
4318 audio_track_cblk_t* cblk = this->cblk();
4319
Glenn Kastene2a05862012-11-13 09:58:55 -08004320 result = cblk->stepServer(mStepCount, isOut());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004321 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004322 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004323 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004324 }
4325 return result;
4326}
4327
4328void AudioFlinger::ThreadBase::TrackBase::reset() {
4329 audio_track_cblk_t* cblk = this->cblk();
4330
4331 cblk->user = 0;
4332 cblk->server = 0;
4333 cblk->userBase = 0;
4334 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004335 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004336 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004337}
4338
Glenn Kasten1127d652012-11-14 08:44:39 -08004339uint32_t AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4340 return mCblk->sampleRate;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004341}
4342
Mathias Agopian65ab4712010-07-14 17:59:35 -07004343void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4344 audio_track_cblk_t* cblk = this->cblk();
Glenn Kasten520a9af2012-06-21 12:56:37 -07004345 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase) * mFrameSize;
4346 int8_t *bufferEnd = bufferStart + frames * mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004347
4348 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004349 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4350 "TrackBase::getBuffer buffer out of range:\n"
4351 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
Glenn Kasten520a9af2012-06-21 12:56:37 -07004352 " server %u, serverBase %u, user %u, userBase %u, frameSize %u",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004353 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Glenn Kasten520a9af2012-06-21 12:56:37 -07004354 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004355
4356 return bufferStart;
4357}
4358
Eric Laurenta011e352012-03-29 15:51:43 -07004359status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4360{
4361 mSyncEvents.add(event);
4362 return NO_ERROR;
4363}
4364
Mathias Agopian65ab4712010-07-14 17:59:35 -07004365// ----------------------------------------------------------------------------
4366
4367// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4368AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004369 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004370 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004371 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004372 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004373 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004374 audio_channel_mask_t channelMask,
Glenn Kasten7da35f22012-11-14 12:54:39 -08004375 size_t frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004376 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004377 int sessionId,
4378 IAudioFlinger::track_flags_t flags)
Glenn Kasten8af901c2012-11-01 11:11:38 -07004379 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer,
4380 sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004381 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004382 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004383 // mRetryCount initialized later when needed
4384 mSharedBuffer(sharedBuffer),
4385 mStreamType(streamType),
4386 mName(-1), // see note below
4387 mMainBuffer(thread->mixBuffer()),
4388 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004389 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004390 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004391 mFlags(flags),
4392 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004393 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004394 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004395{
4396 if (mCblk != NULL) {
Glenn Kasten893a0542012-05-30 10:32:06 -07004397 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivicff71372012-09-10 18:58:27 -07004398 mName = thread->getTrackName_l(channelMask, sessionId);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004399 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004400 if (mName < 0) {
4401 ALOGE("no more track names available");
4402 return;
4403 }
4404 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004405 if (flags & IAudioFlinger::TRACK_FAST) {
Glenn Kasten58912562012-04-03 10:45:00 -07004406 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4407 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004408 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004409 // FIXME This is too eager. We allocate a fast track index before the
4410 // fast track becomes active. Since fast tracks are a scarce resource,
4411 // this means we are potentially denying other more important fast tracks from
4412 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004413 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004414 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004415 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004416 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004417 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004418 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004419 }
Glenn Kasten8af901c2012-11-01 11:11:38 -07004420 ALOGV("Track constructor name %d, calling pid %d", mName,
4421 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004422}
4423
4424AudioFlinger::PlaybackThread::Track::~Track()
4425{
Steve Block3856b092011-10-20 11:56:00 +01004426 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004427}
4428
4429void AudioFlinger::PlaybackThread::Track::destroy()
4430{
4431 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4432 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004433 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004434 // we must acquire a strong reference on this Track before locking mLock
4435 // here so that the destructor is called only when exiting this function.
4436 // On the other hand, as long as Track::destroy() is only called by
4437 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4438 // this Track with its member mTrack.
4439 sp<Track> keep(this);
4440 { // scope for mLock
4441 sp<ThreadBase> thread = mThread.promote();
4442 if (thread != 0) {
4443 if (!isOutputTrack()) {
4444 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004445 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004446
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004447#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004448 // to track the speaker usage
4449 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004450#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004451 }
4452 AudioSystem::releaseOutput(thread->id());
4453 }
4454 Mutex::Autolock _l(thread->mLock);
4455 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4456 playbackThread->destroyTrack_l(this);
4457 }
4458 }
4459}
4460
Glenn Kasten288ed212012-04-25 17:52:27 -07004461/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4462{
Glenn Kastene2a05862012-11-13 09:58:55 -08004463 result.append(" Name Client Type Fmt Chn mask Session StpCnt fCount S M F SRate "
Glenn Kasten8af901c2012-11-01 11:11:38 -07004464 "L dB R dB Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004465}
4466
Mathias Agopian65ab4712010-07-14 17:59:35 -07004467void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4468{
Glenn Kasten83d86532012-01-17 14:39:34 -08004469 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004470 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004471 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004472 } else {
4473 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4474 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004475 track_state state = mState;
4476 char stateChar;
4477 switch (state) {
4478 case IDLE:
4479 stateChar = 'I';
4480 break;
4481 case TERMINATED:
4482 stateChar = 'T';
4483 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004484 case STOPPING_1:
4485 stateChar = 's';
4486 break;
4487 case STOPPING_2:
4488 stateChar = '5';
4489 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004490 case STOPPED:
4491 stateChar = 'S';
4492 break;
4493 case RESUMING:
4494 stateChar = 'R';
4495 break;
4496 case ACTIVE:
4497 stateChar = 'A';
4498 break;
4499 case PAUSING:
4500 stateChar = 'p';
4501 break;
4502 case PAUSED:
4503 stateChar = 'P';
4504 break;
Eric Laurent29864602012-05-08 18:57:51 -07004505 case FLUSHED:
4506 stateChar = 'F';
4507 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004508 default:
4509 stateChar = '?';
4510 break;
4511 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004512 char nowInUnderrun;
4513 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4514 case UNDERRUN_FULL:
4515 nowInUnderrun = ' ';
4516 break;
4517 case UNDERRUN_PARTIAL:
4518 nowInUnderrun = '<';
4519 break;
4520 case UNDERRUN_EMPTY:
4521 nowInUnderrun = '*';
4522 break;
4523 default:
4524 nowInUnderrun = '?';
4525 break;
4526 }
Glenn Kastene213c862012-04-25 13:46:15 -07004527 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4528 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004529 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004530 mStreamType,
4531 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004532 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004533 mSessionId,
Glenn Kastene2a05862012-11-13 09:58:55 -08004534 mStepCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004535 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004536 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004537 mMute,
4538 mFillingUpStatus,
4539 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004540 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4541 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004542 mCblk->server,
4543 mCblk->user,
4544 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004545 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004546 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004547 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004548 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004549}
4550
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004551// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004552status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004553 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004554{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004555 audio_track_cblk_t* cblk = this->cblk();
4556 uint32_t framesReady;
4557 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004558
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004559 // Check if last stepServer failed, try to step now
4560 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004561 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4562 // Since the fast mixer is higher priority than client callback thread,
4563 // it does not result in priority inversion for client.
4564 // But a non-blocking solution would be preferable to avoid
4565 // fast mixer being unable to tryLock(), and
4566 // to avoid the extra context switches if the client wakes up,
4567 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004568 if (!step()) goto getNextBuffer_exit;
4569 ALOGV("stepServer recovered");
4570 mStepServerFailed = false;
4571 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004572
Glenn Kasten288ed212012-04-25 17:52:27 -07004573 // FIXME Same as above
Glenn Kastenba850982012-11-06 16:15:41 -08004574 framesReady = cblk->framesReadyOut();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004575
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004576 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004577 uint32_t s = cblk->server;
4578 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4579
4580 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4581 if (framesReq > framesReady) {
4582 framesReq = framesReady;
4583 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004584 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004585 framesReq = bufferEnd - s;
4586 }
4587
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004588 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004589 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004590 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004591 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004592
4593getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004594 buffer->raw = NULL;
4595 buffer->frameCount = 0;
4596 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4597 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004598}
4599
Glenn Kasten288ed212012-04-25 17:52:27 -07004600// Note that framesReady() takes a mutex on the control block using tryLock().
4601// This could result in priority inversion if framesReady() is called by the normal mixer,
4602// as the normal mixer thread runs at lower
4603// priority than the client's callback thread: there is a short window within framesReady()
4604// during which the normal mixer could be preempted, and the client callback would block.
4605// Another problem can occur if framesReady() is called by the fast mixer:
4606// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4607// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4608size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
Glenn Kastenba850982012-11-06 16:15:41 -08004609 return mCblk->framesReadyOut();
John Grossman4ff14ba2012-02-08 16:37:41 -08004610}
4611
Glenn Kasten288ed212012-04-25 17:52:27 -07004612// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004613bool AudioFlinger::PlaybackThread::Track::isReady() const {
Glenn Kastena2049222012-06-22 17:21:07 -07004614 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
4615 return true;
4616 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004617
John Grossman4ff14ba2012-02-08 16:37:41 -08004618 if (framesReady() >= mCblk->frameCount ||
Glenn Kastend12b0332012-11-05 13:38:15 -08004619 (mCblk->flags & CBLK_FORCEREADY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004620 mFillingUpStatus = FS_FILLED;
Glenn Kastend12b0332012-11-05 13:38:15 -08004621 android_atomic_and(~CBLK_FORCEREADY, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004622 return true;
4623 }
4624 return false;
4625}
4626
Glenn Kasten3acbd052012-02-28 10:39:56 -08004627status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004628 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004629{
4630 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004631 ALOGV("start(%d), calling pid %d session %d",
4632 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004633
Mathias Agopian65ab4712010-07-14 17:59:35 -07004634 sp<ThreadBase> thread = mThread.promote();
4635 if (thread != 0) {
4636 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004637 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004638 // here the track could be either new, or restarted
4639 // in both cases "unstop" the track
4640 if (mState == PAUSED) {
4641 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004642 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004643 } else {
4644 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004645 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004646 }
4647
4648 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4649 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004650 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004651 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004652
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004653#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004654 // to track the speaker usage
4655 if (status == NO_ERROR) {
4656 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4657 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004658#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004659 }
4660 if (status == NO_ERROR) {
4661 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4662 playbackThread->addTrack_l(this);
4663 } else {
4664 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004665 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004666 }
4667 } else {
4668 status = BAD_VALUE;
4669 }
4670 return status;
4671}
4672
4673void AudioFlinger::PlaybackThread::Track::stop()
4674{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004675 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004676 sp<ThreadBase> thread = mThread.promote();
4677 if (thread != 0) {
4678 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004679 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004680 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004681 // If the track is not active (PAUSED and buffers full), flush buffers
4682 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4683 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4684 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004685 mState = STOPPED;
4686 } else if (!isFastTrack()) {
4687 mState = STOPPED;
4688 } else {
4689 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4690 // and then to STOPPED and reset() when presentation is complete
4691 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004692 }
Glenn Kasten8af901c2012-11-01 11:11:38 -07004693 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
4694 playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004695 }
4696 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4697 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004698 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004699 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004700
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004701#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004702 // to track the speaker usage
4703 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004704#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004705 }
4706 }
4707}
4708
4709void AudioFlinger::PlaybackThread::Track::pause()
4710{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004711 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004712 sp<ThreadBase> thread = mThread.promote();
4713 if (thread != 0) {
4714 Mutex::Autolock _l(thread->mLock);
4715 if (mState == ACTIVE || mState == RESUMING) {
4716 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004717 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004718 if (!isOutputTrack()) {
4719 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004720 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004721 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004722
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004723#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004724 // to track the speaker usage
4725 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004726#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004727 }
4728 }
4729 }
4730}
4731
4732void AudioFlinger::PlaybackThread::Track::flush()
4733{
Steve Block3856b092011-10-20 11:56:00 +01004734 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004735 sp<ThreadBase> thread = mThread.promote();
4736 if (thread != 0) {
4737 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004738 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
Glenn Kasten5b78fc92012-11-15 14:13:16 -08004739 mState != PAUSING && mState != IDLE && mState != FLUSHED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004740 return;
4741 }
4742 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004743 // FLUSHED state
4744 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004745 // do not reset the track if it is still in the process of being stopped or paused.
4746 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004747 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004748 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004749 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4750 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4751 reset();
4752 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004753 }
4754}
4755
4756void AudioFlinger::PlaybackThread::Track::reset()
4757{
4758 // Do not reset twice to avoid discarding data written just after a flush and before
4759 // the audioflinger thread detects the track is stopped.
4760 if (!mResetDone) {
4761 TrackBase::reset();
4762 // Force underrun condition to avoid false underrun callback until first data is
4763 // written to buffer
Glenn Kastend12b0332012-11-05 13:38:15 -08004764 android_atomic_and(~CBLK_FORCEREADY, &mCblk->flags);
4765 android_atomic_or(CBLK_UNDERRUN, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004766 mFillingUpStatus = FS_FILLING;
4767 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004768 if (mState == FLUSHED) {
4769 mState = IDLE;
4770 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004771 }
4772}
4773
4774void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4775{
4776 mMute = muted;
4777}
4778
Mathias Agopian65ab4712010-07-14 17:59:35 -07004779status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4780{
4781 status_t status = DEAD_OBJECT;
4782 sp<ThreadBase> thread = mThread.promote();
4783 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004784 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004785 sp<AudioFlinger> af = mClient->audioFlinger();
4786
4787 Mutex::Autolock _l(af->mLock);
4788
4789 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004790
Eric Laurent109347d2012-07-02 12:31:03 -07004791 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004792 Mutex::Autolock _dl(playbackThread->mLock);
4793 Mutex::Autolock _sl(srcThread->mLock);
4794 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4795 if (chain == 0) {
4796 return INVALID_OPERATION;
4797 }
4798
4799 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4800 if (effect == 0) {
4801 return INVALID_OPERATION;
4802 }
4803 srcThread->removeEffect_l(effect);
4804 playbackThread->addEffect_l(effect);
4805 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4806 if (effect->state() == EffectModule::ACTIVE ||
4807 effect->state() == EffectModule::STOPPING) {
4808 effect->start();
4809 }
4810
4811 sp<EffectChain> dstChain = effect->chain().promote();
4812 if (dstChain == 0) {
4813 srcThread->addEffect_l(effect);
4814 return INVALID_OPERATION;
4815 }
4816 AudioSystem::unregisterEffect(effect->id());
4817 AudioSystem::registerEffect(&effect->desc(),
4818 srcThread->id(),
4819 dstChain->strategy(),
4820 AUDIO_SESSION_OUTPUT_MIX,
4821 effect->id());
4822 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004823 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004824 }
4825 return status;
4826}
4827
4828void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4829{
4830 mAuxEffectId = EffectId;
4831 mAuxBuffer = buffer;
4832}
4833
Eric Laurenta011e352012-03-29 15:51:43 -07004834bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4835 size_t audioHalFrames)
4836{
4837 // a track is considered presented when the total number of frames written to audio HAL
4838 // corresponds to the number of frames written when presentationComplete() is called for the
4839 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4840 if (mPresentationCompleteFrames == 0) {
4841 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4842 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4843 mPresentationCompleteFrames, audioHalFrames);
4844 }
4845 if (framesWritten >= mPresentationCompleteFrames) {
4846 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4847 mSessionId, framesWritten);
4848 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004849 return true;
4850 }
4851 return false;
4852}
4853
4854void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4855{
4856 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4857 if (mSyncEvents[i]->type() == type) {
4858 mSyncEvents[i]->trigger();
4859 mSyncEvents.removeAt(i);
4860 i--;
4861 }
4862 }
4863}
4864
Glenn Kasten58912562012-04-03 10:45:00 -07004865// implement VolumeBufferProvider interface
4866
4867uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4868{
4869 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4870 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4871 uint32_t vlr = mCblk->getVolumeLR();
4872 uint32_t vl = vlr & 0xFFFF;
4873 uint32_t vr = vlr >> 16;
4874 // track volumes come from shared memory, so can't be trusted and must be clamped
4875 if (vl > MAX_GAIN_INT) {
4876 vl = MAX_GAIN_INT;
4877 }
4878 if (vr > MAX_GAIN_INT) {
4879 vr = MAX_GAIN_INT;
4880 }
4881 // now apply the cached master volume and stream type volume;
4882 // this is trusted but lacks any synchronization or barrier so may be stale
4883 float v = mCachedVolume;
4884 vl *= v;
4885 vr *= v;
4886 // re-combine into U4.16
4887 vlr = (vr << 16) | (vl & 0xFFFF);
4888 // FIXME look at mute, pause, and stop flags
4889 return vlr;
4890}
Eric Laurenta011e352012-03-29 15:51:43 -07004891
Eric Laurent29864602012-05-08 18:57:51 -07004892status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4893{
4894 if (mState == TERMINATED || mState == PAUSED ||
4895 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4896 (mState == STOPPED)))) {
4897 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4898 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4899 event->cancel();
4900 return INVALID_OPERATION;
4901 }
Glenn Kastend23eedc2012-08-02 13:35:47 -07004902 (void) TrackBase::setSyncEvent(event);
Eric Laurent29864602012-05-08 18:57:51 -07004903 return NO_ERROR;
4904}
4905
Glenn Kastenba850982012-11-06 16:15:41 -08004906bool AudioFlinger::PlaybackThread::Track::isOut() const
4907{
4908 return true;
4909}
4910
John Grossman4ff14ba2012-02-08 16:37:41 -08004911// timed audio tracks
4912
4913sp<AudioFlinger::PlaybackThread::TimedTrack>
4914AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004915 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004916 const sp<Client>& client,
4917 audio_stream_type_t streamType,
4918 uint32_t sampleRate,
4919 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004920 audio_channel_mask_t channelMask,
Glenn Kasten7da35f22012-11-14 12:54:39 -08004921 size_t frameCount,
John Grossman4ff14ba2012-02-08 16:37:41 -08004922 const sp<IMemory>& sharedBuffer,
4923 int sessionId) {
4924 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004925 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004926
Glenn Kastena0356762012-03-19 10:38:51 -07004927 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004928 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4929 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004930}
4931
4932AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004933 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004934 const sp<Client>& client,
4935 audio_stream_type_t streamType,
4936 uint32_t sampleRate,
4937 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004938 audio_channel_mask_t channelMask,
Glenn Kasten7da35f22012-11-14 12:54:39 -08004939 size_t frameCount,
John Grossman4ff14ba2012-02-08 16:37:41 -08004940 const sp<IMemory>& sharedBuffer,
4941 int sessionId)
4942 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004943 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004944 mQueueHeadInFlight(false),
4945 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004946 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004947 mTimedSilenceBuffer(NULL),
4948 mTimedSilenceBufferSize(0),
4949 mTimedAudioOutputOnTime(false),
4950 mMediaTimeTransformValid(false)
4951{
4952 LocalClock lc;
4953 mLocalTimeFreq = lc.getLocalFreq();
4954
4955 mLocalTimeToSampleTransform.a_zero = 0;
4956 mLocalTimeToSampleTransform.b_zero = 0;
4957 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4958 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4959 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4960 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004961
4962 mMediaTimeToSampleTransform.a_zero = 0;
4963 mMediaTimeToSampleTransform.b_zero = 0;
4964 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4965 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4966 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4967 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004968}
4969
4970AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4971 mClient->releaseTimedTrack();
4972 delete [] mTimedSilenceBuffer;
4973}
4974
4975status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4976 size_t size, sp<IMemory>* buffer) {
4977
4978 Mutex::Autolock _l(mTimedBufferQueueLock);
4979
4980 trimTimedBufferQueue_l();
4981
4982 // lazily initialize the shared memory heap for timed buffers
4983 if (mTimedMemoryDealer == NULL) {
4984 const int kTimedBufferHeapSize = 512 << 10;
4985
4986 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4987 "AudioFlingerTimed");
4988 if (mTimedMemoryDealer == NULL)
4989 return NO_MEMORY;
4990 }
4991
4992 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4993 if (newBuffer == NULL) {
4994 newBuffer = mTimedMemoryDealer->allocate(size);
4995 if (newBuffer == NULL)
4996 return NO_MEMORY;
4997 }
4998
4999 *buffer = newBuffer;
5000 return NO_ERROR;
5001}
5002
5003// caller must hold mTimedBufferQueueLock
5004void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
5005 int64_t mediaTimeNow;
5006 {
5007 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5008 if (!mMediaTimeTransformValid)
5009 return;
5010
5011 int64_t targetTimeNow;
5012 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
5013 ? mCCHelper.getCommonTime(&targetTimeNow)
5014 : mCCHelper.getLocalTime(&targetTimeNow);
5015
5016 if (OK != res)
5017 return;
5018
5019 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
5020 &mediaTimeNow)) {
5021 return;
5022 }
5023 }
5024
John Grossman1c345192012-03-27 14:00:17 -07005025 size_t trimEnd;
5026 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07005027 int64_t bufEnd;
5028
John Grossmanc95cfbb2012-04-12 11:53:11 -07005029 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
5030 // We have a next buffer. Just use its PTS as the PTS of the frame
5031 // following the last frame in this buffer. If the stream is sparse
5032 // (ie, there are deliberate gaps left in the stream which should be
5033 // filled with silence by the TimedAudioTrack), then this can result
5034 // in one extra buffer being left un-trimmed when it could have
5035 // been. In general, this is not typical, and we would rather
5036 // optimized away the TS calculation below for the more common case
5037 // where PTSes are contiguous.
5038 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
5039 } else {
5040 // We have no next buffer. Compute the PTS of the frame following
5041 // the last frame in this buffer by computing the duration of of
5042 // this frame in media time units and adding it to the PTS of the
5043 // buffer.
5044 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005045 / mFrameSize;
John Grossmanc95cfbb2012-04-12 11:53:11 -07005046
5047 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
5048 &bufEnd)) {
5049 ALOGE("Failed to convert frame count of %lld to media time"
5050 " duration" " (scale factor %d/%u) in %s",
5051 frameCount,
5052 mMediaTimeToSampleTransform.a_to_b_numer,
5053 mMediaTimeToSampleTransform.a_to_b_denom,
5054 __PRETTY_FUNCTION__);
5055 break;
5056 }
5057 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07005058 }
John Grossman9fbdee12012-03-26 17:51:46 -07005059
5060 if (bufEnd > mediaTimeNow)
5061 break;
5062
5063 // Is the buffer we want to use in the middle of a mix operation right
5064 // now? If so, don't actually trim it. Just wait for the releaseBuffer
5065 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07005066 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07005067 mTrimQueueHeadOnRelease = true;
5068 }
John Grossman4ff14ba2012-02-08 16:37:41 -08005069 }
5070
John Grossman9fbdee12012-03-26 17:51:46 -07005071 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07005072 if (trimStart < trimEnd) {
5073 // Update the bookkeeping for framesReady()
5074 for (size_t i = trimStart; i < trimEnd; ++i) {
5075 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
5076 }
5077
5078 // Now actually remove the buffers from the queue.
5079 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08005080 }
5081}
5082
John Grossman1c345192012-03-27 14:00:17 -07005083void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
5084 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07005085 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
5086 "%s called (reason \"%s\"), but timed buffer queue has no"
5087 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005088
5089 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
5090 mTimedBufferQueue.removeAt(0);
5091}
5092
5093void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
5094 const TimedBuffer& buf,
5095 const char* logTag) {
5096 uint32_t bufBytes = buf.buffer()->size();
5097 uint32_t consumedAlready = buf.position();
5098
Eric Laurentb388e532012-04-14 13:32:48 -07005099 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07005100 "Bad bookkeeping while updating frames pending. Timed buffer is"
5101 " only %u bytes long, but claims to have consumed %u"
5102 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07005103 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005104
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005105 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
John Grossmand3030da2012-04-12 11:56:36 -07005106 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5107 "Bad bookkeeping while updating frames pending. Should have at"
5108 " least %u queued frames, but we think we have only %u. (update"
5109 " reason: \"%s\")",
5110 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005111
5112 mFramesPendingInQueue -= bufFrames;
5113}
5114
John Grossman4ff14ba2012-02-08 16:37:41 -08005115status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5116 const sp<IMemory>& buffer, int64_t pts) {
5117
5118 {
5119 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5120 if (!mMediaTimeTransformValid)
5121 return INVALID_OPERATION;
5122 }
5123
5124 Mutex::Autolock _l(mTimedBufferQueueLock);
5125
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005126 uint32_t bufFrames = buffer->size() / mFrameSize;
John Grossman1c345192012-03-27 14:00:17 -07005127 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005128 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5129
5130 return NO_ERROR;
5131}
5132
5133status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5134 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5135
John Grossman1c345192012-03-27 14:00:17 -07005136 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5137 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5138 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005139
5140 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5141 target == TimedAudioTrack::COMMON_TIME)) {
5142 return BAD_VALUE;
5143 }
5144
5145 Mutex::Autolock lock(mMediaTimeTransformLock);
5146 mMediaTimeTransform = xform;
5147 mMediaTimeTransformTarget = target;
5148 mMediaTimeTransformValid = true;
5149
5150 return NO_ERROR;
5151}
5152
5153#define min(a, b) ((a) < (b) ? (a) : (b))
5154
5155// implementation of getNextBuffer for tracks whose buffers have timestamps
5156status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5157 AudioBufferProvider::Buffer* buffer, int64_t pts)
5158{
5159 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005160 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005161 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005162 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005163 return INVALID_OPERATION;
5164 }
5165
John Grossman4ff14ba2012-02-08 16:37:41 -08005166 Mutex::Autolock _l(mTimedBufferQueueLock);
5167
John Grossman9fbdee12012-03-26 17:51:46 -07005168 ALOG_ASSERT(!mQueueHeadInFlight,
5169 "getNextBuffer called without releaseBuffer!");
5170
John Grossman4ff14ba2012-02-08 16:37:41 -08005171 while (true) {
5172
5173 // if we have no timed buffers, then fail
5174 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005175 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005176 buffer->frameCount = 0;
5177 return NOT_ENOUGH_DATA;
5178 }
5179
5180 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5181
5182 // calculate the PTS of the head of the timed buffer queue expressed in
5183 // local time
5184 int64_t headLocalPTS;
5185 {
5186 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5187
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005188 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005189
5190 if (mMediaTimeTransform.a_to_b_denom == 0) {
5191 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005192 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005193 return NO_ERROR;
5194 }
5195
5196 int64_t transformedPTS;
5197 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5198 &transformedPTS)) {
5199 // the transform failed. this shouldn't happen, but if it does
5200 // then just drop this buffer
5201 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005202 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005203 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005204 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005205 return NO_ERROR;
5206 }
5207
5208 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5209 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5210 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005211 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005212 buffer->frameCount = 0;
5213 return INVALID_OPERATION;
5214 }
5215 } else {
5216 headLocalPTS = transformedPTS;
5217 }
5218 }
5219
5220 // adjust the head buffer's PTS to reflect the portion of the head buffer
5221 // that has already been consumed
5222 int64_t effectivePTS = headLocalPTS +
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005223 ((head.position() / mFrameSize) * mLocalTimeFreq / sampleRate());
John Grossman4ff14ba2012-02-08 16:37:41 -08005224
5225 // Calculate the delta in samples between the head of the input buffer
5226 // queue and the start of the next output buffer that will be written.
5227 // If the transformation fails because of over or underflow, it means
5228 // that the sample's position in the output stream is so far out of
5229 // whack that it should just be dropped.
5230 int64_t sampleDelta;
5231 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5232 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005233 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5234 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005235 continue;
5236 }
5237 if (!mLocalTimeToSampleTransform.doForwardTransform(
5238 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005239 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005240 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005241 continue;
5242 }
5243
John Grossman1c345192012-03-27 14:00:17 -07005244 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5245 " sampleDelta=[%d.%08x]",
5246 head.pts(), head.position(), pts,
5247 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5248 + (sampleDelta >> 32)),
5249 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005250
5251 // if the delta between the ideal placement for the next input sample and
5252 // the current output position is within this threshold, then we will
5253 // concatenate the next input samples to the previous output
5254 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005255 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005256
5257 // if this is the first buffer of audio that we're emitting from this track
5258 // then it should be almost exactly on time.
5259 const int64_t kSampleStartupThreshold = 1LL << 32;
5260
5261 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005262 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005263 // the next input is close enough to being on time, so concatenate it
5264 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005265 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005266
John Grossman1c345192012-03-27 14:00:17 -07005267 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5268 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005269 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005270 }
5271
5272 // Looks like our output is not on time. Reset our on timed status.
5273 // Next time we mix samples from our input queue, then should be within
5274 // the StartupThreshold.
5275 mTimedAudioOutputOnTime = false;
5276 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005277 // the gap between the current output position and the proper start of
5278 // the next input sample is too big, so fill it with silence
5279 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5280
John Grossman9fbdee12012-03-26 17:51:46 -07005281 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005282 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5283 return NO_ERROR;
5284 } else {
5285 // the next input sample is late
5286 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5287 size_t onTimeSamplePosition =
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005288 head.position() + lateFrames * mFrameSize;
John Grossman4ff14ba2012-02-08 16:37:41 -08005289
5290 if (onTimeSamplePosition > head.buffer()->size()) {
5291 // all the remaining samples in the head are too late, so
5292 // drop it and move on
5293 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005294 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005295 continue;
5296 } else {
5297 // skip over the late samples
5298 head.setPosition(onTimeSamplePosition);
5299
5300 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005301 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005302
5303 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5304 return NO_ERROR;
5305 }
5306 }
5307 }
5308}
5309
5310// Yield samples from the timed buffer queue head up to the given output
5311// buffer's capacity.
5312//
5313// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005314void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005315 AudioBufferProvider::Buffer* buffer) {
5316
5317 const TimedBuffer& head = mTimedBufferQueue[0];
5318
5319 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5320 head.position());
5321
5322 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005323 mFrameSize);
John Grossman4ff14ba2012-02-08 16:37:41 -08005324 size_t framesRequested = buffer->frameCount;
5325 buffer->frameCount = min(framesLeftInHead, framesRequested);
5326
John Grossman9fbdee12012-03-26 17:51:46 -07005327 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005328 mTimedAudioOutputOnTime = true;
5329}
5330
5331// Yield samples of silence up to the given output buffer's capacity
5332//
5333// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005334void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005335 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5336
5337 // lazily allocate a buffer filled with silence
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005338 if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005339 delete [] mTimedSilenceBuffer;
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005340 mTimedSilenceBufferSize = numFrames * mFrameSize;
John Grossman4ff14ba2012-02-08 16:37:41 -08005341 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5342 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5343 }
5344
5345 buffer->raw = mTimedSilenceBuffer;
5346 size_t framesRequested = buffer->frameCount;
5347 buffer->frameCount = min(numFrames, framesRequested);
5348
5349 mTimedAudioOutputOnTime = false;
5350}
5351
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005352// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005353void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5354 AudioBufferProvider::Buffer* buffer) {
5355
5356 Mutex::Autolock _l(mTimedBufferQueueLock);
5357
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005358 // If the buffer which was just released is part of the buffer at the head
5359 // of the queue, be sure to update the amt of the buffer which has been
5360 // consumed. If the buffer being returned is not part of the head of the
5361 // queue, its either because the buffer is part of the silence buffer, or
5362 // because the head of the timed queue was trimmed after the mixer called
5363 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005364 if (buffer->raw == mTimedSilenceBuffer) {
5365 ALOG_ASSERT(!mQueueHeadInFlight,
5366 "Queue head in flight during release of silence buffer!");
5367 goto done;
5368 }
5369
5370 ALOG_ASSERT(mQueueHeadInFlight,
5371 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5372 " head in flight.");
5373
5374 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005375 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005376
5377 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005378 void* end = reinterpret_cast<void*>(
5379 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5380 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005381
John Grossman9fbdee12012-03-26 17:51:46 -07005382 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5383 "released buffer not within the head of the timed buffer"
5384 " queue; qHead = [%p, %p], released buffer = %p",
5385 start, end, buffer->raw);
5386
5387 head.setPosition(head.position() +
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005388 (buffer->frameCount * mFrameSize));
John Grossman9fbdee12012-03-26 17:51:46 -07005389 mQueueHeadInFlight = false;
5390
John Grossman1c345192012-03-27 14:00:17 -07005391 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5392 "Bad bookkeeping during releaseBuffer! Should have at"
5393 " least %u queued frames, but we think we have only %u",
5394 buffer->frameCount, mFramesPendingInQueue);
5395
5396 mFramesPendingInQueue -= buffer->frameCount;
5397
John Grossman9fbdee12012-03-26 17:51:46 -07005398 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5399 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005400 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005401 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005402 }
John Grossman9fbdee12012-03-26 17:51:46 -07005403 } else {
5404 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5405 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005406 }
5407
John Grossman9fbdee12012-03-26 17:51:46 -07005408done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005409 buffer->raw = 0;
5410 buffer->frameCount = 0;
5411}
5412
Glenn Kasten288ed212012-04-25 17:52:27 -07005413size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005414 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005415 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005416}
5417
5418AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5419 : mPTS(0), mPosition(0) {}
5420
5421AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5422 const sp<IMemory>& buffer, int64_t pts)
5423 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5424
Mathias Agopian65ab4712010-07-14 17:59:35 -07005425// ----------------------------------------------------------------------------
5426
5427// RecordTrack constructor must be called with AudioFlinger::mLock held
5428AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005429 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005430 const sp<Client>& client,
5431 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005432 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005433 audio_channel_mask_t channelMask,
Glenn Kasten7da35f22012-11-14 12:54:39 -08005434 size_t frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005435 int sessionId)
5436 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005437 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005438 mOverflow(false)
5439{
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005440 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005441}
5442
5443AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5444{
Glenn Kasten510a3d62012-07-16 14:24:34 -07005445 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446}
5447
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005448// AudioBufferProvider interface
Glenn Kasten8af901c2012-11-01 11:11:38 -07005449status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
5450 int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005451{
5452 audio_track_cblk_t* cblk = this->cblk();
5453 uint32_t framesAvail;
5454 uint32_t framesReq = buffer->frameCount;
5455
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005456 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005457 if (mStepServerFailed) {
Glenn Kastena2049222012-06-22 17:21:07 -07005458 if (!step()) {
5459 goto getNextBuffer_exit;
5460 }
Steve Block3856b092011-10-20 11:56:00 +01005461 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005462 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005463 }
5464
Glenn Kastenba850982012-11-06 16:15:41 -08005465 // FIXME lock is not actually held, so overrun is possible
5466 framesAvail = cblk->framesAvailableIn_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005467
Glenn Kastenf6b16782011-12-15 09:51:17 -08005468 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005469 uint32_t s = cblk->server;
5470 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5471
5472 if (framesReq > framesAvail) {
5473 framesReq = framesAvail;
5474 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005475 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005476 framesReq = bufferEnd - s;
5477 }
5478
5479 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005480 buffer->frameCount = framesReq;
5481 return NO_ERROR;
5482 }
5483
5484getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005485 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005486 buffer->frameCount = 0;
5487 return NOT_ENOUGH_DATA;
5488}
5489
Glenn Kasten3acbd052012-02-28 10:39:56 -08005490status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005491 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005492{
5493 sp<ThreadBase> thread = mThread.promote();
5494 if (thread != 0) {
5495 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005496 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005497 } else {
5498 return BAD_VALUE;
5499 }
5500}
5501
5502void AudioFlinger::RecordThread::RecordTrack::stop()
5503{
5504 sp<ThreadBase> thread = mThread.promote();
5505 if (thread != 0) {
5506 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005507 recordThread->mLock.lock();
5508 bool doStop = recordThread->stop_l(this);
5509 if (doStop) {
5510 TrackBase::reset();
5511 // Force overrun condition to avoid false overrun callback until first data is
5512 // read from buffer
Glenn Kastend12b0332012-11-05 13:38:15 -08005513 android_atomic_or(CBLK_UNDERRUN, &mCblk->flags);
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005514 }
5515 recordThread->mLock.unlock();
5516 if (doStop) {
5517 AudioSystem::stopInput(recordThread->id());
5518 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005519 }
5520}
5521
Glenn Kasten510a3d62012-07-16 14:24:34 -07005522/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
5523{
Glenn Kastene2a05862012-11-13 09:58:55 -08005524 result.append(" Clien Fmt Chn mask Session Step S SRate Serv User FrameCount\n");
Glenn Kasten510a3d62012-07-16 14:24:34 -07005525}
5526
Mathias Agopian65ab4712010-07-14 17:59:35 -07005527void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5528{
Jean-Michel Trivi60736462012-09-12 18:48:33 -07005529 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x %05d\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005530 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005531 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005532 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005533 mSessionId,
Glenn Kastene2a05862012-11-13 09:58:55 -08005534 mStepCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005535 mState,
5536 mCblk->sampleRate,
5537 mCblk->server,
Jean-Michel Trivi60736462012-09-12 18:48:33 -07005538 mCblk->user,
5539 mCblk->frameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005540}
5541
Glenn Kastenba850982012-11-06 16:15:41 -08005542bool AudioFlinger::RecordThread::RecordTrack::isOut() const
5543{
5544 return false;
5545}
Mathias Agopian65ab4712010-07-14 17:59:35 -07005546
5547// ----------------------------------------------------------------------------
5548
5549AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005550 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005551 DuplicatingThread *sourceThread,
5552 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005553 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005554 audio_channel_mask_t channelMask,
Glenn Kasten7da35f22012-11-14 12:54:39 -08005555 size_t frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005556 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5557 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Glenn Kasten2f6226a2012-11-08 12:13:58 -08005558 mActive(false), mSourceThread(sourceThread), mBuffers(NULL)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005559{
5560
Mathias Agopian65ab4712010-07-14 17:59:35 -07005561 if (mCblk != NULL) {
Glenn Kasten2f6226a2012-11-08 12:13:58 -08005562 mBuffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005563 mOutBuffer.frameCount = 0;
5564 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005565 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Glenn Kasten1127d652012-11-14 08:44:39 -08005566 "mCblk->frameCount %d, mCblk->sampleRate %u, mChannelMask 0x%08x mBufferEnd %p",
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005567 mCblk, mBuffer, mCblk->buffers,
5568 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005569 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005570 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005571 }
5572}
5573
5574AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5575{
5576 clearBufferQueue();
5577}
5578
Glenn Kasten3acbd052012-02-28 10:39:56 -08005579status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005580 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005581{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005582 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005583 if (status != NO_ERROR) {
5584 return status;
5585 }
5586
5587 mActive = true;
5588 mRetryCount = 127;
5589 return status;
5590}
5591
5592void AudioFlinger::PlaybackThread::OutputTrack::stop()
5593{
5594 Track::stop();
5595 clearBufferQueue();
5596 mOutBuffer.frameCount = 0;
5597 mActive = false;
5598}
5599
5600bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5601{
5602 Buffer *pInBuffer;
5603 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005604 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005605 bool outputBufferFull = false;
5606 inBuffer.frameCount = frames;
5607 inBuffer.i16 = data;
5608
5609 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5610
5611 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005612 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005613 sp<ThreadBase> thread = mThread.promote();
5614 if (thread != 0) {
5615 MixerThread *mixerThread = (MixerThread *)thread.get();
5616 if (mCblk->frameCount > frames){
5617 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5618 uint32_t startFrames = (mCblk->frameCount - frames);
5619 pInBuffer = new Buffer;
5620 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5621 pInBuffer->frameCount = startFrames;
5622 pInBuffer->i16 = pInBuffer->mBuffer;
5623 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5624 mBufferQueue.add(pInBuffer);
5625 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005626 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005627 }
5628 }
5629 }
5630 }
5631
5632 while (waitTimeLeftMs) {
5633 // First write pending buffers, then new data
5634 if (mBufferQueue.size()) {
5635 pInBuffer = mBufferQueue.itemAt(0);
5636 } else {
5637 pInBuffer = &inBuffer;
5638 }
5639
5640 if (pInBuffer->frameCount == 0) {
5641 break;
5642 }
5643
5644 if (mOutBuffer.frameCount == 0) {
5645 mOutBuffer.frameCount = pInBuffer->frameCount;
5646 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005647 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07005648 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this,
5649 mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005650 outputBufferFull = true;
5651 break;
5652 }
5653 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5654 if (waitTimeLeftMs >= waitTimeMs) {
5655 waitTimeLeftMs -= waitTimeMs;
5656 } else {
5657 waitTimeLeftMs = 0;
5658 }
5659 }
5660
Glenn Kasten8af901c2012-11-01 11:11:38 -07005661 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
5662 pInBuffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005663 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
Glenn Kastenba850982012-11-06 16:15:41 -08005664 mCblk->stepUserOut(outFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005665 pInBuffer->frameCount -= outFrames;
5666 pInBuffer->i16 += outFrames * channelCount;
5667 mOutBuffer.frameCount -= outFrames;
5668 mOutBuffer.i16 += outFrames * channelCount;
5669
5670 if (pInBuffer->frameCount == 0) {
5671 if (mBufferQueue.size()) {
5672 mBufferQueue.removeAt(0);
5673 delete [] pInBuffer->mBuffer;
5674 delete pInBuffer;
Glenn Kasten8af901c2012-11-01 11:11:38 -07005675 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
5676 mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005677 } else {
5678 break;
5679 }
5680 }
5681 }
5682
5683 // If we could not write all frames, allocate a buffer and queue it for next time.
5684 if (inBuffer.frameCount) {
5685 sp<ThreadBase> thread = mThread.promote();
5686 if (thread != 0 && !thread->standby()) {
5687 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5688 pInBuffer = new Buffer;
5689 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5690 pInBuffer->frameCount = inBuffer.frameCount;
5691 pInBuffer->i16 = pInBuffer->mBuffer;
Glenn Kasten8af901c2012-11-01 11:11:38 -07005692 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
5693 sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005694 mBufferQueue.add(pInBuffer);
Glenn Kasten8af901c2012-11-01 11:11:38 -07005695 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
5696 mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005697 } else {
Glenn Kasten8af901c2012-11-01 11:11:38 -07005698 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
5699 mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005700 }
5701 }
5702 }
5703
5704 // Calling write() with a 0 length buffer, means that no more data will be written:
5705 // If no more buffers are pending, fill output track buffer to make sure it is started
5706 // by output mixer.
5707 if (frames == 0 && mBufferQueue.size() == 0) {
5708 if (mCblk->user < mCblk->frameCount) {
5709 frames = mCblk->frameCount - mCblk->user;
5710 pInBuffer = new Buffer;
5711 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5712 pInBuffer->frameCount = frames;
5713 pInBuffer->i16 = pInBuffer->mBuffer;
5714 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5715 mBufferQueue.add(pInBuffer);
5716 } else if (mActive) {
5717 stop();
5718 }
5719 }
5720
5721 return outputBufferFull;
5722}
5723
Glenn Kasten8af901c2012-11-01 11:11:38 -07005724status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
5725 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005726{
5727 int active;
5728 status_t result;
5729 audio_track_cblk_t* cblk = mCblk;
5730 uint32_t framesReq = buffer->frameCount;
5731
Glenn Kastencbe4b362012-10-18 15:51:03 -07005732 ALOGVV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005733 buffer->frameCount = 0;
5734
Glenn Kastenba850982012-11-06 16:15:41 -08005735 uint32_t framesAvail = cblk->framesAvailableOut();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005736
5737
5738 if (framesAvail == 0) {
5739 Mutex::Autolock _l(cblk->lock);
5740 goto start_loop_here;
5741 while (framesAvail == 0) {
5742 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005743 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005744 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005745 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005746 }
5747 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5748 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005749 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005750 }
5751 // read the server count again
5752 start_loop_here:
Glenn Kastenba850982012-11-06 16:15:41 -08005753 framesAvail = cblk->framesAvailableOut_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005754 }
5755 }
5756
5757// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005758// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005759// }
5760
5761 if (framesReq > framesAvail) {
5762 framesReq = framesAvail;
5763 }
5764
5765 uint32_t u = cblk->user;
5766 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5767
Marco Nelissena1472d92012-03-30 14:36:54 -07005768 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005769 framesReq = bufferEnd - u;
5770 }
5771
5772 buffer->frameCount = framesReq;
Glenn Kasten5aab59a2012-11-12 07:58:20 -08005773 buffer->raw = cblk->buffer(mBuffers, mFrameSize, u);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005774 return NO_ERROR;
5775}
5776
5777
5778void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5779{
5780 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005781
5782 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005783 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005784 delete [] pBuffer->mBuffer;
5785 delete pBuffer;
5786 }
5787 mBufferQueue.clear();
5788}
5789
5790// ----------------------------------------------------------------------------
5791
5792AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5793 : RefBase(),
5794 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005795 // 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 -07005796 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005797 mPid(pid),
5798 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005799{
5800 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5801}
5802
5803// Client destructor must be called with AudioFlinger::mLock held
5804AudioFlinger::Client::~Client()
5805{
5806 mAudioFlinger->removeClient_l(mPid);
5807}
5808
Glenn Kasten435dbe62012-01-30 10:15:48 -08005809sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005810{
5811 return mMemoryDealer;
5812}
5813
John Grossman4ff14ba2012-02-08 16:37:41 -08005814// Reserve one of the limited slots for a timed audio track associated
5815// with this client
5816bool AudioFlinger::Client::reserveTimedTrack()
5817{
5818 const int kMaxTimedTracksPerClient = 4;
5819
5820 Mutex::Autolock _l(mTimedTrackLock);
5821
5822 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5823 ALOGW("can not create timed track - pid %d has exceeded the limit",
5824 mPid);
5825 return false;
5826 }
5827
5828 mTimedTrackCount++;
5829 return true;
5830}
5831
5832// Release a slot for a timed audio track
5833void AudioFlinger::Client::releaseTimedTrack()
5834{
5835 Mutex::Autolock _l(mTimedTrackLock);
5836 mTimedTrackCount--;
5837}
5838
Mathias Agopian65ab4712010-07-14 17:59:35 -07005839// ----------------------------------------------------------------------------
5840
5841AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5842 const sp<IAudioFlingerClient>& client,
5843 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005844 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005845{
5846}
5847
5848AudioFlinger::NotificationClient::~NotificationClient()
5849{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005850}
5851
5852void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5853{
5854 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005855 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005856}
5857
5858// ----------------------------------------------------------------------------
5859
5860AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5861 : BnAudioTrack(),
5862 mTrack(track)
5863{
5864}
5865
5866AudioFlinger::TrackHandle::~TrackHandle() {
5867 // just stop the track on deletion, associated resources
5868 // will be freed from the main thread once all pending buffers have
5869 // been played. Unless it's not in the active track list, in which
5870 // case we free everything now...
5871 mTrack->destroy();
5872}
5873
Glenn Kasten90716c52012-01-26 13:40:12 -08005874sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5875 return mTrack->getCblk();
5876}
5877
Glenn Kasten3acbd052012-02-28 10:39:56 -08005878status_t AudioFlinger::TrackHandle::start() {
5879 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005880}
5881
5882void AudioFlinger::TrackHandle::stop() {
5883 mTrack->stop();
5884}
5885
5886void AudioFlinger::TrackHandle::flush() {
5887 mTrack->flush();
5888}
5889
5890void AudioFlinger::TrackHandle::mute(bool e) {
5891 mTrack->mute(e);
5892}
5893
5894void AudioFlinger::TrackHandle::pause() {
5895 mTrack->pause();
5896}
5897
Mathias Agopian65ab4712010-07-14 17:59:35 -07005898status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5899{
5900 return mTrack->attachAuxEffect(EffectId);
5901}
5902
John Grossman4ff14ba2012-02-08 16:37:41 -08005903status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5904 sp<IMemory>* buffer) {
5905 if (!mTrack->isTimedTrack())
5906 return INVALID_OPERATION;
5907
5908 PlaybackThread::TimedTrack* tt =
5909 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5910 return tt->allocateTimedBuffer(size, buffer);
5911}
5912
5913status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5914 int64_t pts) {
5915 if (!mTrack->isTimedTrack())
5916 return INVALID_OPERATION;
5917
5918 PlaybackThread::TimedTrack* tt =
5919 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5920 return tt->queueTimedBuffer(buffer, pts);
5921}
5922
5923status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5924 const LinearTransform& xform, int target) {
5925
5926 if (!mTrack->isTimedTrack())
5927 return INVALID_OPERATION;
5928
5929 PlaybackThread::TimedTrack* tt =
5930 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5931 return tt->setMediaTimeTransform(
5932 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5933}
5934
Mathias Agopian65ab4712010-07-14 17:59:35 -07005935status_t AudioFlinger::TrackHandle::onTransact(
5936 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5937{
5938 return BnAudioTrack::onTransact(code, data, reply, flags);
5939}
5940
5941// ----------------------------------------------------------------------------
5942
5943sp<IAudioRecord> AudioFlinger::openRecord(
5944 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005945 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005946 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005947 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005948 audio_channel_mask_t channelMask,
Glenn Kasten7da35f22012-11-14 12:54:39 -08005949 size_t frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005950 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07005951 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005952 int *sessionId,
5953 status_t *status)
5954{
5955 sp<RecordThread::RecordTrack> recordTrack;
5956 sp<RecordHandle> recordHandle;
5957 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958 status_t lStatus;
5959 RecordThread *thread;
5960 size_t inFrameCount;
5961 int lSessionId;
5962
5963 // check calling permissions
5964 if (!recordingAllowed()) {
5965 lStatus = PERMISSION_DENIED;
5966 goto Exit;
5967 }
5968
5969 // add client to list
5970 { // scope for mLock
5971 Mutex::Autolock _l(mLock);
5972 thread = checkRecordThread_l(input);
5973 if (thread == NULL) {
5974 lStatus = BAD_VALUE;
5975 goto Exit;
5976 }
5977
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005978 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005979
5980 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005981 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005982 lSessionId = *sessionId;
5983 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005984 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005985 if (sessionId != NULL) {
5986 *sessionId = lSessionId;
5987 }
5988 }
Glenn Kasten8af901c2012-11-01 11:11:38 -07005989 // create new record track.
5990 // The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07005991 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5992 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005993 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005994 if (lStatus != NO_ERROR) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07005995 // remove local strong reference to Client before deleting the RecordTrack so that the
5996 // Client destructor is called by the TrackBase destructor with mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07005997 client.clear();
5998 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005999 goto Exit;
6000 }
6001
6002 // return to handle to client
6003 recordHandle = new RecordHandle(recordTrack);
6004 lStatus = NO_ERROR;
6005
6006Exit:
6007 if (status) {
6008 *status = lStatus;
6009 }
6010 return recordHandle;
6011}
6012
6013// ----------------------------------------------------------------------------
6014
Glenn Kasten8af901c2012-11-01 11:11:38 -07006015AudioFlinger::RecordHandle::RecordHandle(
6016 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006017 : BnAudioRecord(),
6018 mRecordTrack(recordTrack)
6019{
6020}
6021
6022AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07006023 stop_nonvirtual();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006024 mRecordTrack->destroy();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006025}
6026
Glenn Kasten90716c52012-01-26 13:40:12 -08006027sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
6028 return mRecordTrack->getCblk();
6029}
6030
Glenn Kasten8af901c2012-11-01 11:11:38 -07006031status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
6032 int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01006033 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08006034 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006035}
6036
6037void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07006038 stop_nonvirtual();
6039}
6040
6041void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01006042 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006043 mRecordTrack->stop();
6044}
6045
Mathias Agopian65ab4712010-07-14 17:59:35 -07006046status_t AudioFlinger::RecordHandle::onTransact(
6047 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6048{
6049 return BnAudioRecord::onTransact(code, data, reply, flags);
6050}
6051
6052// ----------------------------------------------------------------------------
6053
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006054AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6055 AudioStreamIn *input,
6056 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07006057 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006058 audio_io_handle_t id,
Glenn Kasten8c327342012-09-30 12:29:28 -07006059 audio_devices_t device,
6060 const sp<NBAIO_Sink>& teeSink) :
Eric Laurent88959252012-08-28 14:26:53 -07006061 ThreadBase(audioFlinger, id, AUDIO_DEVICE_NONE, device, RECORD),
Glenn Kasten510a3d62012-07-16 14:24:34 -07006062 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006063 // mRsmpInIndex and mInputBytes set by readInputParameters()
Glenn Kasten254af182012-07-03 14:59:05 -07006064 mReqChannelCount(popcount(channelMask)),
Glenn Kasten8c327342012-09-30 12:29:28 -07006065 mReqSampleRate(sampleRate),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006066 // mBytesRead is only meaningful while active, and so is cleared in start()
6067 // (but might be better to also clear here for dump?)
Glenn Kasten8c327342012-09-30 12:29:28 -07006068 mTeeSink(teeSink)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006069{
Glenn Kasten480b4682012-02-28 12:30:08 -08006070 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07006071
Mathias Agopian65ab4712010-07-14 17:59:35 -07006072 readInputParameters();
Glenn Kasten8c327342012-09-30 12:29:28 -07006073
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074}
6075
6076
6077AudioFlinger::RecordThread::~RecordThread()
6078{
6079 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08006080 delete mResampler;
6081 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006082}
6083
6084void AudioFlinger::RecordThread::onFirstRef()
6085{
Eric Laurentfeb0db62011-07-22 09:04:31 -07006086 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006087}
6088
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006089status_t AudioFlinger::RecordThread::readyToRun()
6090{
6091 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00006092 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006093 return status;
6094}
6095
Mathias Agopian65ab4712010-07-14 17:59:35 -07006096bool AudioFlinger::RecordThread::threadLoop()
6097{
6098 AudioBufferProvider::Buffer buffer;
6099 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006100 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006101
Eric Laurent44d98482010-09-30 16:12:31 -07006102 nsecs_t lastWarning = 0;
6103
Glenn Kastene4e2a372012-07-23 12:55:09 -07006104 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07006105 acquireWakeLock();
6106
Jean-Michel Trivi89b44702012-09-13 11:44:00 -07006107 // used to verify we've read at least once before evaluating how many bytes were read
Jean-Michel Trivi60736462012-09-12 18:48:33 -07006108 bool readOnce = false;
6109
Mathias Agopian65ab4712010-07-14 17:59:35 -07006110 // start recording
6111 while (!exitPending()) {
6112
6113 processConfigEvents();
6114
6115 { // scope for mLock
6116 Mutex::Autolock _l(mLock);
6117 checkForNewParameters_l();
6118 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006119 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120
Glenn Kastena2049222012-06-22 17:21:07 -07006121 if (exitPending()) {
6122 break;
6123 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006124
Eric Laurentfeb0db62011-07-22 09:04:31 -07006125 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01006126 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006127 // go to sleep
6128 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006129 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006130 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006131 continue;
6132 }
6133 if (mActiveTrack != 0) {
6134 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006135 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006136 mActiveTrack.clear();
6137 mStartStopCond.broadcast();
6138 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6139 if (mReqChannelCount != mActiveTrack->channelCount()) {
6140 mActiveTrack.clear();
6141 mStartStopCond.broadcast();
Jean-Michel Trivi60736462012-09-12 18:48:33 -07006142 } else if (readOnce) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006143 // record start succeeds only if first read from audio input
6144 // succeeds
Jean-Michel Trivi60736462012-09-12 18:48:33 -07006145 if (mBytesRead >= 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006146 mActiveTrack->mState = TrackBase::ACTIVE;
6147 } else {
6148 mActiveTrack.clear();
6149 }
6150 mStartStopCond.broadcast();
6151 }
6152 mStandby = false;
Glenn Kasten510a3d62012-07-16 14:24:34 -07006153 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
6154 removeTrack_l(mActiveTrack);
6155 mActiveTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006156 }
6157 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006158 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006159 }
6160
6161 if (mActiveTrack != 0) {
6162 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6163 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006164 unlockEffectChains(effectChains);
6165 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006166 continue;
6167 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006168 for (size_t i = 0; i < effectChains.size(); i ++) {
6169 effectChains[i]->process_l();
6170 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006171
Mathias Agopian65ab4712010-07-14 17:59:35 -07006172 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006173 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Jean-Michel Trivi60736462012-09-12 18:48:33 -07006174 readOnce = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006175 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006176 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006177 // no resampling
6178 while (framesOut) {
6179 size_t framesIn = mFrameCount - mRsmpInIndex;
6180 if (framesIn) {
6181 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
Glenn Kasten8af901c2012-11-01 11:11:38 -07006182 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
Glenn Kasten5aab59a2012-11-12 07:58:20 -08006183 mActiveTrack->mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006184 if (framesIn > framesOut)
6185 framesIn = framesOut;
6186 mRsmpInIndex += framesIn;
6187 framesOut -= framesIn;
6188 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006189 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006190 memcpy(dst, src, framesIn * mFrameSize);
6191 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006192 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006193 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6194 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006195 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006196 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6197 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006198 }
6199 }
6200 }
6201 if (framesOut && mFrameCount == mRsmpInIndex) {
Glenn Kasten8c327342012-09-30 12:29:28 -07006202 void *readInto;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006203 if (framesOut == mFrameCount &&
Glenn Kasten8af901c2012-11-01 11:11:38 -07006204 ((int)mChannelCount == mReqChannelCount ||
6205 mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Glenn Kasten8c327342012-09-30 12:29:28 -07006206 readInto = buffer.raw;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006207 framesOut = 0;
6208 } else {
Glenn Kasten8c327342012-09-30 12:29:28 -07006209 readInto = mRsmpInBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006210 mRsmpInIndex = 0;
6211 }
Glenn Kasten8c327342012-09-30 12:29:28 -07006212 mBytesRead = mInput->stream->read(mInput->stream, readInto, mInputBytes);
Jean-Michel Trivi60736462012-09-12 18:48:33 -07006213 if (mBytesRead <= 0) {
6214 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
6215 {
6216 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006217 // Force input into standby so that it tries to
6218 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006219 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006220 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006221 }
6222 mRsmpInIndex = mFrameCount;
6223 framesOut = 0;
6224 buffer.frameCount = 0;
Glenn Kasten8c327342012-09-30 12:29:28 -07006225 } else if (mTeeSink != 0) {
6226 (void) mTeeSink->write(readInto,
6227 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006228 }
6229 }
6230 }
6231 } else {
6232 // resampling
6233
6234 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6235 // alter output frame count as if we were expecting stereo samples
6236 if (mChannelCount == 1 && mReqChannelCount == 1) {
6237 framesOut >>= 1;
6238 }
Glenn Kasten8af901c2012-11-01 11:11:38 -07006239 mResampler->resample(mRsmpOutBuffer, framesOut,
6240 this /* AudioBufferProvider* */);
6241 // ditherAndClamp() works as long as all buffers returned by
6242 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006243 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006244 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Glenn Kasten8af901c2012-11-01 11:11:38 -07006245 // the resampler always outputs stereo samples:
6246 // do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006247 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6248 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006249 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006250 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006251 }
6252
6253 }
Eric Laurenta011e352012-03-29 15:51:43 -07006254 if (mFramestoDrop == 0) {
6255 mActiveTrack->releaseBuffer(&buffer);
6256 } else {
6257 if (mFramestoDrop > 0) {
6258 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006259 if (mFramestoDrop <= 0) {
6260 clearSyncStartEvent();
6261 }
6262 } else {
6263 mFramestoDrop += buffer.frameCount;
6264 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6265 mSyncStartEvent->isCancelled()) {
6266 ALOGW("Synced record %s, session %d, trigger session %d",
6267 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6268 mActiveTrack->sessionId(),
6269 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6270 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006271 }
6272 }
6273 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006274 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006275 }
6276 // client isn't retrieving buffers fast enough
6277 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006278 if (!mActiveTrack->setOverflow()) {
6279 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006280 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006281 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006282 lastWarning = now;
6283 }
6284 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006285 // Release the processor for a while before asking for a new buffer.
6286 // This will give the application more chance to read from the buffer and
6287 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006288 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006289 }
6290 }
Eric Laurentec437d82011-07-26 20:54:46 -07006291 // enable changes in effect chain
6292 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006293 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006294 }
6295
Glenn Kastene4e2a372012-07-23 12:55:09 -07006296 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006297
Glenn Kasten33e6e352012-07-16 15:56:57 -07006298 {
6299 Mutex::Autolock _l(mLock);
6300 mActiveTrack.clear();
6301 mStartStopCond.broadcast();
6302 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006303
Eric Laurentfeb0db62011-07-22 09:04:31 -07006304 releaseWakeLock();
6305
Steve Block3856b092011-10-20 11:56:00 +01006306 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006307 return false;
6308}
6309
Glenn Kastene4e2a372012-07-23 12:55:09 -07006310void AudioFlinger::RecordThread::standby()
6311{
6312 if (!mStandby) {
6313 inputStandBy();
6314 mStandby = true;
6315 }
6316}
6317
6318void AudioFlinger::RecordThread::inputStandBy()
6319{
6320 mInput->stream->common.standby(&mInput->stream->common);
6321}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006322
6323sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6324 const sp<AudioFlinger::Client>& client,
6325 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006326 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006327 audio_channel_mask_t channelMask,
Glenn Kasten7da35f22012-11-14 12:54:39 -08006328 size_t frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006329 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006330 IAudioFlinger::track_flags_t flags,
6331 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006332 status_t *status)
6333{
6334 sp<RecordTrack> track;
6335 status_t lStatus;
6336
6337 lStatus = initCheck();
6338 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006339 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006340 goto Exit;
6341 }
6342
Glenn Kasten1879fff2012-07-11 15:36:59 -07006343 // FIXME use flags and tid similar to createTrack_l()
6344
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006345 { // scope for mLock
6346 Mutex::Autolock _l(mLock);
6347
6348 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006349 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006350
Glenn Kasten7378ca52012-01-20 13:44:40 -08006351 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006352 lStatus = NO_MEMORY;
6353 goto Exit;
6354 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006355 mTracks.add(track);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006356
Eric Laurent59bd0da2011-08-01 09:52:20 -07006357 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurent88959252012-08-28 14:26:53 -07006358 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006359 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006360 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6361 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006362 }
6363 lStatus = NO_ERROR;
6364
6365Exit:
6366 if (status) {
6367 *status = lStatus;
6368 }
6369 return track;
6370}
6371
Eric Laurenta011e352012-03-29 15:51:43 -07006372status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006373 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006374 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006375{
Glenn Kasten58912562012-04-03 10:45:00 -07006376 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006377 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006378 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006379
6380 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006381 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006382 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6383 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6384 triggerSession,
6385 recordTrack->sessionId(),
6386 syncStartEventCallback,
6387 this);
Eric Laurent29864602012-05-08 18:57:51 -07006388 // Sync event can be cancelled by the trigger session if the track is not in a
6389 // compatible state in which case we start record immediately
6390 if (mSyncStartEvent->isCancelled()) {
6391 clearSyncStartEvent();
6392 } else {
6393 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6394 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6395 }
Eric Laurenta011e352012-03-29 15:51:43 -07006396 }
6397
Mathias Agopian65ab4712010-07-14 17:59:35 -07006398 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006399 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006400 if (mActiveTrack != 0) {
6401 if (recordTrack != mActiveTrack.get()) {
6402 status = -EBUSY;
6403 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6404 mActiveTrack->mState = TrackBase::ACTIVE;
6405 }
6406 return status;
6407 }
6408
6409 recordTrack->mState = TrackBase::IDLE;
6410 mActiveTrack = recordTrack;
6411 mLock.unlock();
6412 status_t status = AudioSystem::startInput(mId);
6413 mLock.lock();
6414 if (status != NO_ERROR) {
6415 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006416 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006417 return status;
6418 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006419 mRsmpInIndex = mFrameCount;
6420 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006421 if (mResampler != NULL) {
6422 mResampler->reset();
6423 }
6424 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006425 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006426 ALOGV("Signal record thread");
Eric Laurent67d8ac32012-09-24 15:02:17 -07006427 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006428 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006429 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006430 mActiveTrack.clear();
6431 status = INVALID_OPERATION;
6432 goto startError;
6433 }
6434 mStartStopCond.wait(mLock);
6435 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006436 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006437 status = BAD_VALUE;
6438 goto startError;
6439 }
Steve Block3856b092011-10-20 11:56:00 +01006440 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006441 return status;
6442 }
6443startError:
6444 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006445 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006446 return status;
6447}
6448
Eric Laurenta011e352012-03-29 15:51:43 -07006449void AudioFlinger::RecordThread::clearSyncStartEvent()
6450{
6451 if (mSyncStartEvent != 0) {
6452 mSyncStartEvent->cancel();
6453 }
6454 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006455 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006456}
6457
6458void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6459{
6460 sp<SyncEvent> strongEvent = event.promote();
6461
6462 if (strongEvent != 0) {
6463 RecordThread *me = (RecordThread *)strongEvent->cookie();
6464 me->handleSyncStartEvent(strongEvent);
6465 }
6466}
6467
6468void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6469{
Eric Laurent29864602012-05-08 18:57:51 -07006470 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006471 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6472 // from audio HAL
6473 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006474 }
6475}
6476
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006477bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006478 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006479 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
6480 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006481 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006482 recordTrack->mState = TrackBase::PAUSING;
6483 // do not wait for mStartStopCond if exiting
6484 if (exitPending()) {
6485 return true;
6486 }
6487 mStartStopCond.wait(mLock);
6488 // if we have been restarted, recordTrack == mActiveTrack.get() here
6489 if (exitPending() || recordTrack != mActiveTrack.get()) {
6490 ALOGV("Record stopped OK");
6491 return true;
6492 }
6493 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006494}
6495
Glenn Kasten106e8a42012-08-02 13:37:12 -07006496bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07006497{
6498 return false;
6499}
6500
6501status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6502{
Glenn Kasten7f7d27e2012-08-02 16:37:07 -07006503#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 -07006504 if (!isValidSyncEvent(event)) {
6505 return BAD_VALUE;
6506 }
6507
Glenn Kasten510a3d62012-07-16 14:24:34 -07006508 int eventSession = event->triggerSession();
6509 status_t ret = NAME_NOT_FOUND;
6510
Eric Laurenta011e352012-03-29 15:51:43 -07006511 Mutex::Autolock _l(mLock);
6512
Glenn Kasten510a3d62012-07-16 14:24:34 -07006513 for (size_t i = 0; i < mTracks.size(); i++) {
6514 sp<RecordTrack> track = mTracks[i];
6515 if (eventSession == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07006516 (void) track->setSyncEvent(event);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006517 ret = NO_ERROR;
6518 }
Eric Laurenta011e352012-03-29 15:51:43 -07006519 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006520 return ret;
Glenn Kasten7f7d27e2012-08-02 16:37:07 -07006521#else
6522 return BAD_VALUE;
6523#endif
Glenn Kasten510a3d62012-07-16 14:24:34 -07006524}
6525
6526void AudioFlinger::RecordThread::RecordTrack::destroy()
6527{
6528 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
6529 sp<RecordTrack> keep(this);
6530 {
6531 sp<ThreadBase> thread = mThread.promote();
6532 if (thread != 0) {
6533 if (mState == ACTIVE || mState == RESUMING) {
6534 AudioSystem::stopInput(thread->id());
6535 }
6536 AudioSystem::releaseInput(thread->id());
6537 Mutex::Autolock _l(thread->mLock);
6538 RecordThread *recordThread = (RecordThread *) thread.get();
6539 recordThread->destroyTrack_l(this);
6540 }
6541 }
6542}
6543
6544// destroyTrack_l() must be called with ThreadBase::mLock held
6545void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6546{
6547 track->mState = TrackBase::TERMINATED;
6548 // active tracks are removed by threadLoop()
6549 if (mActiveTrack != track) {
6550 removeTrack_l(track);
6551 }
6552}
6553
6554void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6555{
6556 mTracks.remove(track);
6557 // need anything related to effects here?
Eric Laurenta011e352012-03-29 15:51:43 -07006558}
6559
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07006560void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006561{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006562 dumpInternals(fd, args);
6563 dumpTracks(fd, args);
6564 dumpEffectChains(fd, args);
6565}
6566
6567void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6568{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006569 const size_t SIZE = 256;
6570 char buffer[SIZE];
6571 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006572
6573 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6574 result.append(buffer);
6575
6576 if (mActiveTrack != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006577 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6578 result.append(buffer);
6579 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6580 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006581 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006582 result.append(buffer);
6583 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6584 result.append(buffer);
Glenn Kasten1127d652012-11-14 08:44:39 -08006585 snprintf(buffer, SIZE, "Out sample rate: %u\n", mReqSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006586 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006587 } else {
Glenn Kasten510a3d62012-07-16 14:24:34 -07006588 result.append("No active record client\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006589 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006590
Mathias Agopian65ab4712010-07-14 17:59:35 -07006591 write(fd, result.string(), result.size());
6592
6593 dumpBase(fd, args);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006594}
6595
6596void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
6597{
6598 const size_t SIZE = 256;
6599 char buffer[SIZE];
6600 String8 result;
6601
6602 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
6603 result.append(buffer);
6604 RecordTrack::appendDumpHeader(result);
6605 for (size_t i = 0; i < mTracks.size(); ++i) {
6606 sp<RecordTrack> track = mTracks[i];
6607 if (track != 0) {
6608 track->dump(buffer, SIZE);
6609 result.append(buffer);
6610 }
6611 }
6612
6613 if (mActiveTrack != 0) {
6614 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
6615 result.append(buffer);
6616 RecordTrack::appendDumpHeader(result);
6617 mActiveTrack->dump(buffer, SIZE);
6618 result.append(buffer);
6619
6620 }
6621 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006622}
6623
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006624// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006625status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006626{
6627 size_t framesReq = buffer->frameCount;
6628 size_t framesReady = mFrameCount - mRsmpInIndex;
6629 int channelCount;
6630
6631 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006632 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Jean-Michel Trivi89b44702012-09-13 11:44:00 -07006633 if (mBytesRead <= 0) {
6634 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
6635 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006636 // Force input into standby so that it tries to
6637 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006638 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006639 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006640 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006641 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006642 buffer->frameCount = 0;
6643 return NOT_ENOUGH_DATA;
6644 }
6645 mRsmpInIndex = 0;
6646 framesReady = mFrameCount;
6647 }
6648
6649 if (framesReq > framesReady) {
6650 framesReq = framesReady;
6651 }
6652
6653 if (mChannelCount == 1 && mReqChannelCount == 2) {
6654 channelCount = 1;
6655 } else {
6656 channelCount = 2;
6657 }
6658 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6659 buffer->frameCount = framesReq;
6660 return NO_ERROR;
6661}
6662
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006663// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006664void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6665{
6666 mRsmpInIndex += buffer->frameCount;
6667 buffer->frameCount = 0;
6668}
6669
6670bool AudioFlinger::RecordThread::checkForNewParameters_l()
6671{
6672 bool reconfig = false;
6673
6674 while (!mNewParameters.isEmpty()) {
6675 status_t status = NO_ERROR;
6676 String8 keyValuePair = mNewParameters[0];
6677 AudioParameter param = AudioParameter(keyValuePair);
6678 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006679 audio_format_t reqFormat = mFormat;
Glenn Kasten1127d652012-11-14 08:44:39 -08006680 uint32_t reqSamplingRate = mReqSampleRate;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006681 int reqChannelCount = mReqChannelCount;
6682
6683 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6684 reqSamplingRate = value;
6685 reconfig = true;
6686 }
6687 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006688 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006689 reconfig = true;
6690 }
6691 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006692 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006693 reconfig = true;
6694 }
6695 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6696 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006697 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006698 // if frame count is changed after track creation
6699 if (mActiveTrack != 0) {
6700 status = INVALID_OPERATION;
6701 } else {
6702 reconfig = true;
6703 }
6704 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006705 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6706 // forward device change to effects that have requested to be
6707 // aware of attached audio device.
6708 for (size_t i = 0; i < mEffectChains.size(); i++) {
6709 mEffectChains[i]->setDevice_l(value);
6710 }
Eric Laurent88959252012-08-28 14:26:53 -07006711
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006712 // store input device and output device but do not forward output device to audio HAL.
6713 // Note that status is ignored by the caller for output device
6714 // (see AudioFlinger::setParameters()
Eric Laurent88959252012-08-28 14:26:53 -07006715 if (audio_is_output_devices(value)) {
6716 mOutDevice = value;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006717 status = BAD_VALUE;
6718 } else {
Eric Laurent88959252012-08-28 14:26:53 -07006719 mInDevice = value;
Glenn Kasten8af901c2012-11-01 11:11:38 -07006720 // disable AEC and NS if the device is a BT SCO headset supporting those
6721 // pre processings
Glenn Kasten510a3d62012-07-16 14:24:34 -07006722 if (mTracks.size() > 0) {
Eric Laurent88959252012-08-28 14:26:53 -07006723 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6724 mAudioFlinger->btNrecIsOff();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006725 for (size_t i = 0; i < mTracks.size(); i++) {
6726 sp<RecordTrack> track = mTracks[i];
6727 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6728 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6729 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07006730 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006731 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006732 }
Eric Laurent2e9b0f22012-08-31 17:44:06 -07006733 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6734 mAudioSource != (audio_source_t)value) {
6735 // forward device change to effects that have requested to be
6736 // aware of attached audio device.
6737 for (size_t i = 0; i < mEffectChains.size(); i++) {
6738 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
6739 }
6740 mAudioSource = (audio_source_t)value;
6741 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006742 if (status == NO_ERROR) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07006743 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6744 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006745 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006746 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006747 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6748 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006749 }
6750 if (reconfig) {
6751 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006752 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006753 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kasten8af901c2012-11-01 11:11:38 -07006754 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common)
6755 <= (2 * reqSamplingRate)) &&
6756 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
6757 <= FCC_2 &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006758 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006759 status = NO_ERROR;
6760 }
6761 if (status == NO_ERROR) {
6762 readInputParameters();
Eric Laurentef6be0b2012-09-13 11:18:23 -07006763 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006764 }
6765 }
6766 }
6767
6768 mNewParameters.removeAt(0);
6769
6770 mParamStatus = status;
6771 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006772 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6773 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006774 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006775 }
6776 return reconfig;
6777}
6778
6779String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6780{
Dima Zavinfce7a472011-04-19 22:30:36 -07006781 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006782 String8 out_s8 = String8();
6783
6784 Mutex::Autolock _l(mLock);
6785 if (initCheck() != NO_ERROR) {
6786 return out_s8;
6787 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006788
Dima Zavin799a70e2011-04-18 16:57:27 -07006789 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006790 out_s8 = String8(s);
6791 free(s);
6792 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006793}
6794
6795void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6796 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006797 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006798
6799 switch (event) {
6800 case AudioSystem::INPUT_OPENED:
6801 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006802 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006803 desc.samplingRate = mSampleRate;
6804 desc.format = mFormat;
6805 desc.frameCount = mFrameCount;
6806 desc.latency = 0;
6807 param2 = &desc;
6808 break;
6809
6810 case AudioSystem::INPUT_CLOSED:
6811 default:
6812 break;
6813 }
6814 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6815}
6816
6817void AudioFlinger::RecordThread::readInputParameters()
6818{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006819 delete mRsmpInBuffer;
6820 // mRsmpInBuffer is always assigned a new[] below
6821 delete mRsmpOutBuffer;
6822 mRsmpOutBuffer = NULL;
6823 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006824 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006825
Dima Zavin799a70e2011-04-18 16:57:27 -07006826 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006827 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6828 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006829 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006830 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006831 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006832 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006833 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006834 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6835
Glenn Kasten53d76db2012-03-08 12:32:47 -08006836 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006837 {
6838 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006839 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6840 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006841 if (mChannelCount == 1 && mReqChannelCount == 2) {
6842 channelCount = 1;
6843 } else {
6844 channelCount = 2;
6845 }
6846 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6847 mResampler->setSampleRate(mSampleRate);
6848 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6849 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6850
Glenn Kasten8af901c2012-11-01 11:11:38 -07006851 // optmization: if mono to mono, alter input frame count as if we were inputing
6852 // stereo samples
Mathias Agopian65ab4712010-07-14 17:59:35 -07006853 if (mChannelCount == 1 && mReqChannelCount == 1) {
6854 mFrameCount >>= 1;
6855 }
6856
6857 }
6858 mRsmpInIndex = mFrameCount;
6859}
6860
6861unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6862{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006863 Mutex::Autolock _l(mLock);
6864 if (initCheck() != NO_ERROR) {
6865 return 0;
6866 }
6867
Dima Zavin799a70e2011-04-18 16:57:27 -07006868 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006869}
6870
Glenn Kasten106e8a42012-08-02 13:37:12 -07006871uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006872{
6873 Mutex::Autolock _l(mLock);
6874 uint32_t result = 0;
6875 if (getEffectChain_l(sessionId) != 0) {
6876 result = EFFECT_SESSION;
6877 }
6878
Glenn Kasten510a3d62012-07-16 14:24:34 -07006879 for (size_t i = 0; i < mTracks.size(); ++i) {
6880 if (sessionId == mTracks[i]->sessionId()) {
6881 result |= TRACK_SESSION;
6882 break;
6883 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006884 }
6885
6886 return result;
6887}
6888
Glenn Kasten106e8a42012-08-02 13:37:12 -07006889KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent59bd0da2011-08-01 09:52:20 -07006890{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006891 KeyedVector<int, bool> ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006892 Mutex::Autolock _l(mLock);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006893 for (size_t j = 0; j < mTracks.size(); ++j) {
6894 sp<RecordThread::RecordTrack> track = mTracks[j];
6895 int sessionId = track->sessionId();
6896 if (ids.indexOfKey(sessionId) < 0) {
6897 ids.add(sessionId, true);
6898 }
6899 }
6900 return ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006901}
6902
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006903AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6904{
6905 Mutex::Autolock _l(mLock);
6906 AudioStreamIn *input = mInput;
6907 mInput = NULL;
6908 return input;
6909}
6910
6911// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006912audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006913{
6914 if (mInput == NULL) {
6915 return NULL;
6916 }
6917 return &mInput->stream->common;
6918}
6919
6920
Mathias Agopian65ab4712010-07-14 17:59:35 -07006921// ----------------------------------------------------------------------------
6922
Eric Laurenta4c5a552012-03-29 10:12:40 -07006923audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6924{
6925 if (!settingsAllowed()) {
6926 return 0;
6927 }
6928 Mutex::Autolock _l(mLock);
6929 return loadHwModule_l(name);
6930}
6931
6932// loadHwModule_l() must be called with AudioFlinger::mLock held
6933audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6934{
6935 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6936 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6937 ALOGW("loadHwModule() module %s already loaded", name);
6938 return mAudioHwDevs.keyAt(i);
6939 }
6940 }
6941
Eric Laurenta4c5a552012-03-29 10:12:40 -07006942 audio_hw_device_t *dev;
6943
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006944 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006945 if (rc) {
6946 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6947 return 0;
6948 }
6949
6950 mHardwareStatus = AUDIO_HW_INIT;
6951 rc = dev->init_check(dev);
6952 mHardwareStatus = AUDIO_HW_IDLE;
6953 if (rc) {
6954 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6955 return 0;
6956 }
6957
John Grossmanee578c02012-07-23 17:05:46 -07006958 // Check and cache this HAL's level of support for master mute and master
6959 // volume. If this is the first HAL opened, and it supports the get
6960 // methods, use the initial values provided by the HAL as the current
6961 // master mute and volume settings.
6962
6963 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
6964 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07006965 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07006966
6967 if (0 == mAudioHwDevs.size()) {
6968 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6969 if (NULL != dev->get_master_volume) {
6970 float mv;
6971 if (OK == dev->get_master_volume(dev, &mv)) {
6972 mMasterVolume = mv;
6973 }
6974 }
6975
6976 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
6977 if (NULL != dev->get_master_mute) {
6978 bool mm;
6979 if (OK == dev->get_master_mute(dev, &mm)) {
6980 mMasterMute = mm;
6981 }
6982 }
6983 }
6984
Eric Laurenta4c5a552012-03-29 10:12:40 -07006985 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07006986 if ((NULL != dev->set_master_volume) &&
6987 (OK == dev->set_master_volume(dev, mMasterVolume))) {
6988 flags = static_cast<AudioHwDevice::Flags>(flags |
6989 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
6990 }
6991
6992 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
6993 if ((NULL != dev->set_master_mute) &&
6994 (OK == dev->set_master_mute(dev, mMasterMute))) {
6995 flags = static_cast<AudioHwDevice::Flags>(flags |
6996 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
6997 }
6998
Eric Laurenta4c5a552012-03-29 10:12:40 -07006999 mHardwareStatus = AUDIO_HW_IDLE;
7000 }
7001
7002 audio_module_handle_t handle = nextUniqueId();
John Grossmanee578c02012-07-23 17:05:46 -07007003 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07007004
7005 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007006 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007007
7008 return handle;
7009
7010}
7011
Glenn Kasten4c6db4c2012-09-24 11:27:18 -07007012// ----------------------------------------------------------------------------
7013
Glenn Kasten1127d652012-11-14 08:44:39 -08007014uint32_t AudioFlinger::getPrimaryOutputSamplingRate()
Glenn Kasten4c6db4c2012-09-24 11:27:18 -07007015{
7016 Mutex::Autolock _l(mLock);
7017 PlaybackThread *thread = primaryPlaybackThread_l();
7018 return thread != NULL ? thread->sampleRate() : 0;
7019}
7020
Glenn Kasten7da35f22012-11-14 12:54:39 -08007021size_t AudioFlinger::getPrimaryOutputFrameCount()
Glenn Kasten4c6db4c2012-09-24 11:27:18 -07007022{
7023 Mutex::Autolock _l(mLock);
7024 PlaybackThread *thread = primaryPlaybackThread_l();
7025 return thread != NULL ? thread->frameCountHAL() : 0;
7026}
7027
7028// ----------------------------------------------------------------------------
7029
Eric Laurenta4c5a552012-03-29 10:12:40 -07007030audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
7031 audio_devices_t *pDevices,
7032 uint32_t *pSamplingRate,
7033 audio_format_t *pFormat,
7034 audio_channel_mask_t *pChannelMask,
7035 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007036 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007037{
7038 status_t status;
7039 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007040 struct audio_config config = {
7041 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7042 channel_mask: pChannelMask ? *pChannelMask : 0,
7043 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7044 };
7045 audio_stream_out_t *outStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007046 AudioHwDevice *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007047
Eric Laurenta4c5a552012-03-29 10:12:40 -07007048 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
7049 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007050 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007051 config.sample_rate,
7052 config.format,
7053 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07007054 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007055
7056 if (pDevices == NULL || *pDevices == 0) {
7057 return 0;
7058 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007059
Mathias Agopian65ab4712010-07-14 17:59:35 -07007060 Mutex::Autolock _l(mLock);
7061
Eric Laurenta4c5a552012-03-29 10:12:40 -07007062 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007063 if (outHwDev == NULL)
7064 return 0;
7065
John Grossmanee578c02012-07-23 17:05:46 -07007066 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007067 audio_io_handle_t id = nextUniqueId();
7068
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007069 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007070
John Grossmanee578c02012-07-23 17:05:46 -07007071 status = hwDevHal->open_output_stream(hwDevHal,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007072 id,
7073 *pDevices,
7074 (audio_output_flags_t)flags,
7075 &config,
7076 &outStream);
7077
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007078 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8af901c2012-11-01 11:11:38 -07007079 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, "
7080 "Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007081 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007082 config.sample_rate,
7083 config.format,
7084 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007085 status);
7086
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007087 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007088 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007089
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007090 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007091 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
7092 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007093 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007094 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007095 } else {
7096 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007097 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007098 }
7099 mPlaybackThreads.add(id, thread);
7100
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007101 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
7102 if (pFormat != NULL) *pFormat = config.format;
7103 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08007104 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007105
7106 // notify client processes of the new output creation
7107 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007108
7109 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007110 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07007111 ALOGI("Using module %d has the primary audio interface", module);
7112 mPrimaryHardwareDev = outHwDev;
7113
7114 AutoMutex lock(mHardwareLock);
7115 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -07007116 hwDevHal->set_mode(hwDevHal, mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007117 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007118 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007119 return id;
7120 }
7121
7122 return 0;
7123}
7124
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007125audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
7126 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007127{
7128 Mutex::Autolock _l(mLock);
7129 MixerThread *thread1 = checkMixerThread_l(output1);
7130 MixerThread *thread2 = checkMixerThread_l(output2);
7131
7132 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07007133 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
7134 output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007135 return 0;
7136 }
7137
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007138 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007139 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
7140 thread->addOutputTrack(thread2);
7141 mPlaybackThreads.add(id, thread);
7142 // notify client processes of the new output creation
7143 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7144 return id;
7145}
7146
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007147status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007148{
Glenn Kastend96c5722012-04-25 13:44:49 -07007149 return closeOutput_nonvirtual(output);
7150}
7151
7152status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
7153{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007154 // keep strong reference on the playback thread so that
7155 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007156 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007157 {
7158 Mutex::Autolock _l(mLock);
7159 thread = checkPlaybackThread_l(output);
7160 if (thread == NULL) {
7161 return BAD_VALUE;
7162 }
7163
Steve Block3856b092011-10-20 11:56:00 +01007164 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007165
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007166 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007167 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007168 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07007169 DuplicatingThread *dupThread =
7170 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007171 dupThread->removeOutputTrack((MixerThread *)thread.get());
7172 }
7173 }
7174 }
Glenn Kastena1117922012-01-26 10:53:32 -08007175 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007176 mPlaybackThreads.removeItem(output);
7177 }
7178 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007179 // The thread entity (active unit of execution) is no longer running here,
7180 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007181
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007182 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007183 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007184 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007185 // from now on thread->mOutput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007186 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007187 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007188 }
7189 return NO_ERROR;
7190}
7191
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007192status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007193{
7194 Mutex::Autolock _l(mLock);
7195 PlaybackThread *thread = checkPlaybackThread_l(output);
7196
7197 if (thread == NULL) {
7198 return BAD_VALUE;
7199 }
7200
Steve Block3856b092011-10-20 11:56:00 +01007201 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007202 thread->suspend();
7203
7204 return NO_ERROR;
7205}
7206
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007207status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007208{
7209 Mutex::Autolock _l(mLock);
7210 PlaybackThread *thread = checkPlaybackThread_l(output);
7211
7212 if (thread == NULL) {
7213 return BAD_VALUE;
7214 }
7215
Steve Block3856b092011-10-20 11:56:00 +01007216 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007217
7218 thread->restore();
7219
7220 return NO_ERROR;
7221}
7222
Eric Laurenta4c5a552012-03-29 10:12:40 -07007223audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
7224 audio_devices_t *pDevices,
7225 uint32_t *pSamplingRate,
7226 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07007227 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007228{
7229 status_t status;
7230 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007231 struct audio_config config = {
7232 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7233 channel_mask: pChannelMask ? *pChannelMask : 0,
7234 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7235 };
7236 uint32_t reqSamplingRate = config.sample_rate;
7237 audio_format_t reqFormat = config.format;
7238 audio_channel_mask_t reqChannels = config.channel_mask;
7239 audio_stream_in_t *inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007240 AudioHwDevice *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007241
7242 if (pDevices == NULL || *pDevices == 0) {
7243 return 0;
7244 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007245
Mathias Agopian65ab4712010-07-14 17:59:35 -07007246 Mutex::Autolock _l(mLock);
7247
Eric Laurenta4c5a552012-03-29 10:12:40 -07007248 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007249 if (inHwDev == NULL)
7250 return 0;
7251
John Grossmanee578c02012-07-23 17:05:46 -07007252 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007253 audio_io_handle_t id = nextUniqueId();
7254
John Grossmanee578c02012-07-23 17:05:46 -07007255 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007256 &inStream);
Glenn Kasten8af901c2012-11-01 11:11:38 -07007257 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, "
7258 "status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007259 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007260 config.sample_rate,
7261 config.format,
7262 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007263 status);
7264
Glenn Kasten8af901c2012-11-01 11:11:38 -07007265 // If the input could not be opened with the requested parameters and we can handle the
7266 // conversion internally, try to open again with the proposed parameters. The AudioFlinger can
7267 // resample the input and do mono to stereo or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007268 if (status == BAD_VALUE &&
7269 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7270 (config.sample_rate <= 2 * reqSamplingRate) &&
7271 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007272 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007273 inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007274 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007275 }
7276
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007277 if (status == NO_ERROR && inStream != NULL) {
Glenn Kasten8c327342012-09-30 12:29:28 -07007278
7279 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
7280 // or (re-)create if current Pipe is idle and does not match the new format
7281 sp<NBAIO_Sink> teeSink;
7282#ifdef TEE_SINK_INPUT_FRAMES
7283 enum {
7284 TEE_SINK_NO, // don't copy input
7285 TEE_SINK_NEW, // copy input using a new pipe
7286 TEE_SINK_OLD, // copy input using an existing pipe
7287 } kind;
7288 NBAIO_Format format = Format_from_SR_C(inStream->common.get_sample_rate(&inStream->common),
7289 popcount(inStream->common.get_channels(&inStream->common)));
7290 if (format == Format_Invalid) {
7291 kind = TEE_SINK_NO;
7292 } else if (mRecordTeeSink == 0) {
7293 kind = TEE_SINK_NEW;
7294 } else if (mRecordTeeSink->getStrongCount() != 1) {
7295 kind = TEE_SINK_NO;
7296 } else if (format == mRecordTeeSink->format()) {
7297 kind = TEE_SINK_OLD;
7298 } else {
7299 kind = TEE_SINK_NEW;
7300 }
7301 switch (kind) {
7302 case TEE_SINK_NEW: {
7303 Pipe *pipe = new Pipe(TEE_SINK_INPUT_FRAMES, format);
7304 size_t numCounterOffers = 0;
7305 const NBAIO_Format offers[1] = {format};
7306 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7307 ALOG_ASSERT(index == 0);
7308 PipeReader *pipeReader = new PipeReader(*pipe);
7309 numCounterOffers = 0;
7310 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7311 ALOG_ASSERT(index == 0);
7312 mRecordTeeSink = pipe;
7313 mRecordTeeSource = pipeReader;
7314 teeSink = pipe;
7315 }
7316 break;
7317 case TEE_SINK_OLD:
7318 teeSink = mRecordTeeSink;
7319 break;
7320 case TEE_SINK_NO:
7321 default:
7322 break;
7323 }
7324#endif
Dima Zavin799a70e2011-04-18 16:57:27 -07007325 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7326
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007327 // Start record thread
7328 // RecorThread require both input and output device indication to forward to audio
7329 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007330 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Glenn Kasten8c327342012-09-30 12:29:28 -07007331
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007332 thread = new RecordThread(this,
7333 input,
7334 reqSamplingRate,
7335 reqChannels,
7336 id,
Glenn Kasten8c327342012-09-30 12:29:28 -07007337 device, teeSink);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007338 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007339 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007340 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007341 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007342 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007343
Mathias Agopian65ab4712010-07-14 17:59:35 -07007344 // notify client processes of the new input creation
7345 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7346 return id;
7347 }
7348
7349 return 0;
7350}
7351
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007352status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007353{
Glenn Kastend96c5722012-04-25 13:44:49 -07007354 return closeInput_nonvirtual(input);
7355}
7356
7357status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7358{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007359 // keep strong reference on the record thread so that
7360 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007361 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007362 {
7363 Mutex::Autolock _l(mLock);
7364 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007365 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007366 return BAD_VALUE;
7367 }
7368
Steve Block3856b092011-10-20 11:56:00 +01007369 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007370 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007371 mRecordThreads.removeItem(input);
7372 }
7373 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007374 // The thread entity (active unit of execution) is no longer running here,
7375 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007376
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007377 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007378 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007379 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007380 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007381 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007382
7383 return NO_ERROR;
7384}
7385
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007386status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007387{
7388 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007389 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007390
7391 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7392 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007393 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007394 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007395
7396 return NO_ERROR;
7397}
7398
7399
7400int AudioFlinger::newAudioSessionId()
7401{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007402 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007403}
7404
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007405void AudioFlinger::acquireAudioSessionId(int audioSession)
7406{
7407 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007408 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007409 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007410 size_t num = mAudioSessionRefs.size();
7411 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007412 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007413 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7414 ref->mCnt++;
7415 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007416 return;
7417 }
7418 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007419 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7420 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007421}
7422
7423void AudioFlinger::releaseAudioSessionId(int audioSession)
7424{
7425 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007426 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007427 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007428 size_t num = mAudioSessionRefs.size();
7429 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007430 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007431 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7432 ref->mCnt--;
7433 ALOGV(" decremented refcount to %d", ref->mCnt);
7434 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007435 mAudioSessionRefs.removeAt(i);
7436 delete ref;
7437 purgeStaleEffects_l();
7438 }
7439 return;
7440 }
7441 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007442 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007443}
7444
7445void AudioFlinger::purgeStaleEffects_l() {
7446
Steve Block3856b092011-10-20 11:56:00 +01007447 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007448
7449 Vector< sp<EffectChain> > chains;
7450
7451 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7452 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7453 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7454 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007455 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7456 chains.push(ec);
7457 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007458 }
7459 }
7460 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7461 sp<RecordThread> t = mRecordThreads.valueAt(i);
7462 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7463 sp<EffectChain> ec = t->mEffectChains[j];
7464 chains.push(ec);
7465 }
7466 }
7467
7468 for (size_t i = 0; i < chains.size(); i++) {
7469 sp<EffectChain> ec = chains[i];
7470 int sessionid = ec->sessionId();
7471 sp<ThreadBase> t = ec->mThread.promote();
7472 if (t == 0) {
7473 continue;
7474 }
7475 size_t numsessionrefs = mAudioSessionRefs.size();
7476 bool found = false;
7477 for (size_t k = 0; k < numsessionrefs; k++) {
7478 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007479 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007480 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007481 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007482 found = true;
7483 break;
7484 }
7485 }
7486 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007487 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007488 // remove all effects from the chain
7489 while (ec->mEffects.size()) {
7490 sp<EffectModule> effect = ec->mEffects[0];
7491 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007492 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007493 if (effect->purgeHandles()) {
7494 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007495 }
7496 AudioSystem::unregisterEffect(effect->id());
7497 }
7498 }
7499 }
7500 return;
7501}
7502
Mathias Agopian65ab4712010-07-14 17:59:35 -07007503// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007504AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007505{
Glenn Kastena1117922012-01-26 10:53:32 -08007506 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007507}
7508
7509// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007510AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007511{
7512 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007513 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007514}
7515
7516// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007517AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007518{
Glenn Kastena1117922012-01-26 10:53:32 -08007519 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007520}
7521
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007522uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007523{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007524 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007525}
7526
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007527AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007528{
7529 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7530 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007531 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07007532 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007533 return thread;
7534 }
7535 }
7536 return NULL;
7537}
7538
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007539audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007540{
7541 PlaybackThread *thread = primaryPlaybackThread_l();
7542
7543 if (thread == NULL) {
7544 return 0;
7545 }
7546
Eric Laurent88959252012-08-28 14:26:53 -07007547 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007548}
7549
Eric Laurenta011e352012-03-29 15:51:43 -07007550sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7551 int triggerSession,
7552 int listenerSession,
7553 sync_event_callback_t callBack,
7554 void *cookie)
7555{
7556 Mutex::Autolock _l(mLock);
7557
7558 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7559 status_t playStatus = NAME_NOT_FOUND;
7560 status_t recStatus = NAME_NOT_FOUND;
7561 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7562 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7563 if (playStatus == NO_ERROR) {
7564 return event;
7565 }
7566 }
7567 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7568 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7569 if (recStatus == NO_ERROR) {
7570 return event;
7571 }
7572 }
7573 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7574 mPendingSyncEvents.add(event);
7575 } else {
7576 ALOGV("createSyncEvent() invalid event %d", event->type());
7577 event.clear();
7578 }
7579 return event;
7580}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007581
Mathias Agopian65ab4712010-07-14 17:59:35 -07007582// ----------------------------------------------------------------------------
7583// Effect management
7584// ----------------------------------------------------------------------------
7585
7586
Glenn Kastenf587ba52012-01-26 16:25:10 -08007587status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007588{
7589 Mutex::Autolock _l(mLock);
7590 return EffectQueryNumberEffects(numEffects);
7591}
7592
Glenn Kastenf587ba52012-01-26 16:25:10 -08007593status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007594{
7595 Mutex::Autolock _l(mLock);
7596 return EffectQueryEffect(index, descriptor);
7597}
7598
Glenn Kasten5e92a782012-01-30 07:40:52 -08007599status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007600 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007601{
7602 Mutex::Autolock _l(mLock);
7603 return EffectGetDescriptor(pUuid, descriptor);
7604}
7605
7606
Mathias Agopian65ab4712010-07-14 17:59:35 -07007607sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7608 effect_descriptor_t *pDesc,
7609 const sp<IEffectClient>& effectClient,
7610 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007611 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007612 int sessionId,
7613 status_t *status,
7614 int *id,
7615 int *enabled)
7616{
7617 status_t lStatus = NO_ERROR;
7618 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007619 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007620
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007621 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007622 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007623
7624 if (pDesc == NULL) {
7625 lStatus = BAD_VALUE;
7626 goto Exit;
7627 }
7628
Eric Laurent84e9a102010-09-23 16:10:16 -07007629 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007630 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007631 lStatus = PERMISSION_DENIED;
7632 goto Exit;
7633 }
7634
Dima Zavinfce7a472011-04-19 22:30:36 -07007635 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007636 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007637 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007638 lStatus = PERMISSION_DENIED;
7639 goto Exit;
7640 }
7641
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007642 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007643 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007644 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007645 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007646 lStatus = BAD_VALUE;
7647 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007648 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007649 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007650 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007651 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007652 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007653 }
7654 }
7655
Mathias Agopian65ab4712010-07-14 17:59:35 -07007656 {
7657 Mutex::Autolock _l(mLock);
7658
Mathias Agopian65ab4712010-07-14 17:59:35 -07007659
7660 if (!EffectIsNullUuid(&pDesc->uuid)) {
7661 // if uuid is specified, request effect descriptor
7662 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7663 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007664 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007665 goto Exit;
7666 }
7667 } else {
7668 // if uuid is not specified, look for an available implementation
7669 // of the required type in effect factory
7670 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007671 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007672 lStatus = BAD_VALUE;
7673 goto Exit;
7674 }
7675 uint32_t numEffects = 0;
7676 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007677 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007678 bool found = false;
7679
7680 lStatus = EffectQueryNumberEffects(&numEffects);
7681 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007682 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007683 goto Exit;
7684 }
7685 for (uint32_t i = 0; i < numEffects; i++) {
7686 lStatus = EffectQueryEffect(i, &desc);
7687 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007688 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007689 continue;
7690 }
7691 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7692 // If matching type found save effect descriptor. If the session is
7693 // 0 and the effect is not auxiliary, continue enumeration in case
7694 // an auxiliary version of this effect type is available
7695 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08007696 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07007697 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007698 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7699 break;
7700 }
7701 }
7702 }
7703 if (!found) {
7704 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007705 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007706 goto Exit;
7707 }
7708 // For same effect type, chose auxiliary version over insert version if
7709 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007710 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007711 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08007712 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007713 }
7714 }
7715
7716 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007717 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007718 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7719 lStatus = INVALID_OPERATION;
7720 goto Exit;
7721 }
7722
Eric Laurent59255e42011-07-27 19:49:51 -07007723 // check recording permission for visualizer
7724 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7725 !recordingAllowed()) {
7726 lStatus = PERMISSION_DENIED;
7727 goto Exit;
7728 }
7729
Mathias Agopian65ab4712010-07-14 17:59:35 -07007730 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08007731 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007732
7733 // If output is not specified try to find a matching audio session ID in one of the
7734 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007735 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7736 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007737 // Note: io is never 0 when creating an effect on an input
7738 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007739 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007740 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7741 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007742 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007743 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007744 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007745 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007746 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007747 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7748 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7749 io = mRecordThreads.keyAt(i);
7750 break;
7751 }
7752 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007753 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007754 // If no output thread contains the requested session ID, default to
7755 // first output. The effect chain will be moved to the correct output
7756 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007757 if (io == 0 && mPlaybackThreads.size()) {
7758 io = mPlaybackThreads.keyAt(0);
7759 }
Steve Block3856b092011-10-20 11:56:00 +01007760 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007761 }
7762 ThreadBase *thread = checkRecordThread_l(io);
7763 if (thread == NULL) {
7764 thread = checkPlaybackThread_l(io);
7765 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007766 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007767 lStatus = BAD_VALUE;
7768 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007769 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007770 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007771
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007772 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007773
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007774 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007775 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7776 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007777 if (handle != 0 && id != NULL) {
7778 *id = handle->id();
7779 }
7780 }
7781
7782Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007783 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007784 *status = lStatus;
7785 }
7786 return handle;
7787}
7788
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007789status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7790 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007791{
Steve Block3856b092011-10-20 11:56:00 +01007792 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007793 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007794 Mutex::Autolock _l(mLock);
7795 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007796 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007797 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007798 }
Eric Laurentde070132010-07-13 04:45:46 -07007799 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7800 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007801 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007802 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007803 }
Eric Laurentde070132010-07-13 04:45:46 -07007804 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7805 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007806 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007807 return BAD_VALUE;
7808 }
7809
7810 Mutex::Autolock _dl(dstThread->mLock);
7811 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007812 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007813
Mathias Agopian65ab4712010-07-14 17:59:35 -07007814 return NO_ERROR;
7815}
7816
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007817// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007818status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007819 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007820 AudioFlinger::PlaybackThread *dstThread,
7821 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007822{
Steve Block3856b092011-10-20 11:56:00 +01007823 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007824 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007825
Eric Laurent59255e42011-07-27 19:49:51 -07007826 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007827 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007828 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007829 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007830 return INVALID_OPERATION;
7831 }
7832
Eric Laurent39e94f82010-07-28 01:32:47 -07007833 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007834 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007835 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007836 // removed.
7837 srcThread->removeEffectChain_l(chain);
7838
7839 // transfer all effects one by one so that new effect chain is created on new thread with
7840 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007841 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007842 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007843 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007844 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7845 while (effect != 0) {
7846 srcThread->removeEffect_l(effect);
7847 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007848 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7849 if (effect->state() == EffectModule::ACTIVE ||
7850 effect->state() == EffectModule::STOPPING) {
7851 effect->start();
7852 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007853 // if the move request is not received from audio policy manager, the effect must be
7854 // re-registered with the new strategy and output
7855 if (dstChain == 0) {
7856 dstChain = effect->chain().promote();
7857 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007858 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007859 srcThread->addEffect_l(effect);
7860 return NO_INIT;
7861 }
7862 strategy = dstChain->strategy();
7863 }
7864 if (reRegister) {
7865 AudioSystem::unregisterEffect(effect->id());
7866 AudioSystem::registerEffect(&effect->desc(),
7867 dstOutput,
7868 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007869 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007870 effect->id());
7871 }
Eric Laurentde070132010-07-13 04:45:46 -07007872 effect = chain->getEffectFromId_l(0);
7873 }
7874
7875 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007876}
7877
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007878
Mathias Agopian65ab4712010-07-14 17:59:35 -07007879// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007880sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007881 const sp<AudioFlinger::Client>& client,
7882 const sp<IEffectClient>& effectClient,
7883 int32_t priority,
7884 int sessionId,
7885 effect_descriptor_t *desc,
7886 int *enabled,
7887 status_t *status
7888 )
7889{
7890 sp<EffectModule> effect;
7891 sp<EffectHandle> handle;
7892 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007893 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007894 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007895 bool effectCreated = false;
7896 bool effectRegistered = false;
7897
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007898 lStatus = initCheck();
7899 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007900 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007901 goto Exit;
7902 }
7903
7904 // Do not allow effects with session ID 0 on direct output or duplicating threads
7905 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007906 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007907 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007908 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007909 lStatus = BAD_VALUE;
7910 goto Exit;
7911 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007912 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007913 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007914 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007915 desc->name, desc->flags, mType);
7916 lStatus = BAD_VALUE;
7917 goto Exit;
7918 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007919
Steve Block3856b092011-10-20 11:56:00 +01007920 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007921
7922 { // scope for mLock
7923 Mutex::Autolock _l(mLock);
7924
7925 // check for existing effect chain with the requested audio session
7926 chain = getEffectChain_l(sessionId);
7927 if (chain == 0) {
7928 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007929 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007930 chain = new EffectChain(this, sessionId);
7931 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007932 chain->setStrategy(getStrategyForSession_l(sessionId));
7933 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007934 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007935 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007936 }
7937
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007938 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007939
7940 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007941 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007942 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007943 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007944 if (lStatus != NO_ERROR) {
7945 goto Exit;
7946 }
7947 effectRegistered = true;
7948 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007949 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007950 lStatus = effect->status();
7951 if (lStatus != NO_ERROR) {
7952 goto Exit;
7953 }
Eric Laurentcab11242010-07-15 12:50:15 -07007954 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007955 if (lStatus != NO_ERROR) {
7956 goto Exit;
7957 }
7958 effectCreated = true;
7959
Eric Laurent88959252012-08-28 14:26:53 -07007960 effect->setDevice(mOutDevice);
7961 effect->setDevice(mInDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007962 effect->setMode(mAudioFlinger->getMode());
Eric Laurent2e9b0f22012-08-31 17:44:06 -07007963 effect->setAudioSource(mAudioSource);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007964 }
7965 // create effect handle and connect it to effect module
7966 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007967 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007968 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007969 *enabled = (int)effect->isEnabled();
7970 }
7971 }
7972
7973Exit:
7974 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007975 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007976 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007977 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007978 }
7979 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007980 AudioSystem::unregisterEffect(effect->id());
7981 }
7982 if (chainCreated) {
7983 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007984 }
7985 handle.clear();
7986 }
7987
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007988 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007989 *status = lStatus;
7990 }
7991 return handle;
7992}
7993
Eric Laurent717e1282012-06-29 16:36:52 -07007994sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7995{
7996 Mutex::Autolock _l(mLock);
7997 return getEffect_l(sessionId, effectId);
7998}
7999
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008000sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
8001{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008002 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08008003 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008004}
8005
Eric Laurentde070132010-07-13 04:45:46 -07008006// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
8007// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008008status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07008009{
8010 // check for existing effect chain with the requested audio session
8011 int sessionId = effect->sessionId();
8012 sp<EffectChain> chain = getEffectChain_l(sessionId);
8013 bool chainCreated = false;
8014
8015 if (chain == 0) {
8016 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01008017 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07008018 chain = new EffectChain(this, sessionId);
8019 addEffectChain_l(chain);
8020 chain->setStrategy(getStrategyForSession_l(sessionId));
8021 chainCreated = true;
8022 }
Steve Block3856b092011-10-20 11:56:00 +01008023 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07008024
8025 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008026 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07008027 this, effect->desc().name, chain.get());
8028 return BAD_VALUE;
8029 }
8030
8031 status_t status = chain->addEffect_l(effect);
8032 if (status != NO_ERROR) {
8033 if (chainCreated) {
8034 removeEffectChain_l(chain);
8035 }
8036 return status;
8037 }
8038
Eric Laurent88959252012-08-28 14:26:53 -07008039 effect->setDevice(mOutDevice);
8040 effect->setDevice(mInDevice);
Eric Laurentde070132010-07-13 04:45:46 -07008041 effect->setMode(mAudioFlinger->getMode());
Eric Laurent2e9b0f22012-08-31 17:44:06 -07008042 effect->setAudioSource(mAudioSource);
Eric Laurentde070132010-07-13 04:45:46 -07008043 return NO_ERROR;
8044}
8045
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008046void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07008047
Steve Block3856b092011-10-20 11:56:00 +01008048 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008049 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07008050 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8051 detachAuxEffect_l(effect->id());
8052 }
8053
8054 sp<EffectChain> chain = effect->chain().promote();
8055 if (chain != 0) {
8056 // remove effect chain if removing last effect
8057 if (chain->removeEffect_l(effect) == 0) {
8058 removeEffectChain_l(chain);
8059 }
8060 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00008061 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07008062 }
8063}
8064
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008065void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008066 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008067{
8068 effectChains = mEffectChains;
8069 for (size_t i = 0; i < mEffectChains.size(); i++) {
8070 mEffectChains[i]->lock();
8071 }
8072}
8073
8074void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008075 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008076{
8077 for (size_t i = 0; i < effectChains.size(); i++) {
8078 effectChains[i]->unlock();
8079 }
8080}
8081
8082sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
8083{
8084 Mutex::Autolock _l(mLock);
8085 return getEffectChain_l(sessionId);
8086}
8087
Glenn Kasten106e8a42012-08-02 13:37:12 -07008088sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008089{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008090 size_t size = mEffectChains.size();
8091 for (size_t i = 0; i < size; i++) {
8092 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008093 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008094 }
8095 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008096 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008097}
8098
Glenn Kastenf78aee72012-01-04 11:00:47 -08008099void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008100{
8101 Mutex::Autolock _l(mLock);
8102 size_t size = mEffectChains.size();
8103 for (size_t i = 0; i < size; i++) {
8104 mEffectChains[i]->setMode_l(mode);
8105 }
8106}
8107
8108void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008109 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08008110 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07008111
Mathias Agopian65ab4712010-07-14 17:59:35 -07008112 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008113 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008114 // delete the effect module if removing last handle on it
8115 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008116 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008117 removeEffect_l(effect);
8118 AudioSystem::unregisterEffect(effect->id());
8119 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008120 }
8121}
8122
8123status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
8124{
8125 int session = chain->sessionId();
8126 int16_t *buffer = mMixBuffer;
8127 bool ownsBuffer = false;
8128
Steve Block3856b092011-10-20 11:56:00 +01008129 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008130 if (session > 0) {
8131 // Only one effect chain can be present in direct output thread and it uses
8132 // the mix buffer as input
8133 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07008134 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008135 buffer = new int16_t[numSamples];
8136 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01008137 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008138 ownsBuffer = true;
8139 }
8140
8141 // Attach all tracks with same session ID to this chain.
8142 for (size_t i = 0; i < mTracks.size(); ++i) {
8143 sp<Track> track = mTracks[i];
8144 if (session == track->sessionId()) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07008145 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
8146 buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008147 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008148 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008149 }
8150 }
8151
8152 // indicate all active tracks in the chain
8153 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8154 sp<Track> track = mActiveTracks[i].promote();
Glenn Kastena2049222012-06-22 17:21:07 -07008155 if (track == 0) {
8156 continue;
8157 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008158 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008159 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07008160 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008161 }
8162 }
8163 }
8164
8165 chain->setInBuffer(buffer, ownsBuffer);
8166 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07008167 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07008168 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008169 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
8170 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008171 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07008172 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
8173 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07008174 // Effect chain for other sessions are inserted at beginning of effect
8175 // chains list to be processed before output mix effects. Relative order between other
8176 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07008177 size_t size = mEffectChains.size();
8178 size_t i = 0;
8179 for (i = 0; i < size; i++) {
Glenn Kastena2049222012-06-22 17:21:07 -07008180 if (mEffectChains[i]->sessionId() < session) {
8181 break;
8182 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008183 }
8184 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008185 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008186
8187 return NO_ERROR;
8188}
8189
8190size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
8191{
8192 int session = chain->sessionId();
8193
Steve Block3856b092011-10-20 11:56:00 +01008194 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008195
8196 for (size_t i = 0; i < mEffectChains.size(); i++) {
8197 if (chain == mEffectChains[i]) {
8198 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07008199 // detach all active tracks from the chain
8200 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8201 sp<Track> track = mActiveTracks[i].promote();
Glenn Kastena2049222012-06-22 17:21:07 -07008202 if (track == 0) {
8203 continue;
8204 }
Eric Laurentb469b942011-05-09 12:09:06 -07008205 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008206 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07008207 chain.get(), session);
8208 chain->decActiveTrackCnt();
8209 }
8210 }
8211
Mathias Agopian65ab4712010-07-14 17:59:35 -07008212 // detach all tracks with same session ID from this chain
8213 for (size_t i = 0; i < mTracks.size(); ++i) {
8214 sp<Track> track = mTracks[i];
8215 if (session == track->sessionId()) {
8216 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008217 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008218 }
8219 }
Eric Laurentde070132010-07-13 04:45:46 -07008220 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008221 }
8222 }
8223 return mEffectChains.size();
8224}
8225
Eric Laurentde070132010-07-13 04:45:46 -07008226status_t AudioFlinger::PlaybackThread::attachAuxEffect(
8227 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008228{
8229 Mutex::Autolock _l(mLock);
8230 return attachAuxEffect_l(track, EffectId);
8231}
8232
Eric Laurentde070132010-07-13 04:45:46 -07008233status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
8234 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008235{
8236 status_t status = NO_ERROR;
8237
8238 if (EffectId == 0) {
8239 track->setAuxBuffer(0, NULL);
8240 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07008241 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
8242 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008243 if (effect != 0) {
8244 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8245 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
8246 } else {
8247 status = INVALID_OPERATION;
8248 }
8249 } else {
8250 status = BAD_VALUE;
8251 }
8252 }
8253 return status;
8254}
8255
8256void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
8257{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008258 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008259 sp<Track> track = mTracks[i];
8260 if (track->auxEffectId() == effectId) {
8261 attachAuxEffect_l(track, 0);
8262 }
8263 }
8264}
8265
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008266status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8267{
8268 // only one chain per input thread
8269 if (mEffectChains.size() != 0) {
8270 return INVALID_OPERATION;
8271 }
Steve Block3856b092011-10-20 11:56:00 +01008272 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008273
8274 chain->setInBuffer(NULL);
8275 chain->setOutBuffer(NULL);
8276
Eric Laurent59255e42011-07-27 19:49:51 -07008277 checkSuspendOnAddEffectChain_l(chain);
8278
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008279 mEffectChains.add(chain);
8280
8281 return NO_ERROR;
8282}
8283
8284size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8285{
Steve Block3856b092011-10-20 11:56:00 +01008286 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00008287 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008288 "removeEffectChain_l() %p invalid chain size %d on thread %p",
8289 chain.get(), mEffectChains.size(), this);
8290 if (mEffectChains.size() == 1) {
8291 mEffectChains.removeAt(0);
8292 }
8293 return 0;
8294}
8295
Mathias Agopian65ab4712010-07-14 17:59:35 -07008296// ----------------------------------------------------------------------------
8297// EffectModule implementation
8298// ----------------------------------------------------------------------------
8299
8300#undef LOG_TAG
8301#define LOG_TAG "AudioFlinger::EffectModule"
8302
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008303AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008304 const wp<AudioFlinger::EffectChain>& chain,
8305 effect_descriptor_t *desc,
8306 int id,
8307 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07008308 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
8309 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07008310 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07008311 // mConfig is set by configure() and not used before then
8312 mEffectInterface(NULL),
8313 mStatus(NO_INIT), mState(IDLE),
8314 // mMaxDisableWaitCnt is set by configure() and not used before then
8315 // mDisableWaitCnt is set by process() and updateState() and not used before then
8316 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008317{
Steve Block3856b092011-10-20 11:56:00 +01008318 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008319 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008320
8321 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008322 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008323
8324 if (mStatus != NO_ERROR) {
8325 return;
8326 }
8327 lStatus = init();
8328 if (lStatus < 0) {
8329 mStatus = lStatus;
8330 goto Error;
8331 }
8332
Steve Block3856b092011-10-20 11:56:00 +01008333 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008334 return;
8335Error:
8336 EffectRelease(mEffectInterface);
8337 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008338 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008339}
8340
8341AudioFlinger::EffectModule::~EffectModule()
8342{
Steve Block3856b092011-10-20 11:56:00 +01008343 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008344 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008345 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8346 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8347 sp<ThreadBase> thread = mThread.promote();
8348 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008349 audio_stream_t *stream = thread->stream();
8350 if (stream != NULL) {
8351 stream->remove_audio_effect(stream, mEffectInterface);
8352 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008353 }
8354 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008355 // release effect engine
8356 EffectRelease(mEffectInterface);
8357 }
8358}
8359
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008360status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008361{
8362 status_t status;
8363
8364 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008365 int priority = handle->priority();
8366 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008367 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008368 size_t i;
8369 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008370 EffectHandle *h = mHandles[i];
Glenn Kastena2049222012-06-22 17:21:07 -07008371 if (h == NULL || h->destroyed_l()) {
8372 continue;
8373 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008374 // first non destroyed handle is considered in control
8375 if (controlHandle == NULL)
8376 controlHandle = h;
Glenn Kastena2049222012-06-22 17:21:07 -07008377 if (h->priority() <= priority) {
8378 break;
8379 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008380 }
8381 // if inserted in first place, move effect control from previous owner to this handle
8382 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008383 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008384 if (controlHandle != NULL) {
8385 enabled = controlHandle->enabled();
8386 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008387 }
Eric Laurent59255e42011-07-27 19:49:51 -07008388 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008389 status = NO_ERROR;
8390 } else {
8391 status = ALREADY_EXISTS;
8392 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008393 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008394 mHandles.insertAt(handle, i);
8395 return status;
8396}
8397
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008398size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008399{
8400 Mutex::Autolock _l(mLock);
8401 size_t size = mHandles.size();
8402 size_t i;
8403 for (i = 0; i < size; i++) {
Glenn Kastena2049222012-06-22 17:21:07 -07008404 if (mHandles[i] == handle) {
8405 break;
8406 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008407 }
8408 if (i == size) {
8409 return size;
8410 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008411 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008412
Mathias Agopian65ab4712010-07-14 17:59:35 -07008413 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008414 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008415 if (i == 0) {
8416 EffectHandle *h = controlHandle_l();
8417 if (h != NULL) {
8418 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008419 }
8420 }
8421
Eric Laurentec437d82011-07-26 20:54:46 -07008422 // Prevent calls to process() and other functions on effect interface from now on.
8423 // The effect engine will be released by the destructor when the last strong reference on
8424 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008425 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008426 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008427 }
8428
Eric Laurente65c8912012-07-20 15:57:23 -07008429 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008430}
8431
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008432// must be called with EffectModule::mLock held
8433AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008434{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008435 // the first valid handle in the list has control over the module
8436 for (size_t i = 0; i < mHandles.size(); i++) {
8437 EffectHandle *h = mHandles[i];
8438 if (h != NULL && !h->destroyed_l()) {
8439 return h;
8440 }
8441 }
8442
8443 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008444}
8445
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008446size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008447{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008448 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008449 // keep a strong reference on this EffectModule to avoid calling the
8450 // destructor before we exit
8451 sp<EffectModule> keep(this);
8452 {
8453 sp<ThreadBase> thread = mThread.promote();
8454 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008455 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008456 }
8457 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008458 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008459}
8460
8461void AudioFlinger::EffectModule::updateState() {
8462 Mutex::Autolock _l(mLock);
8463
8464 switch (mState) {
8465 case RESTART:
8466 reset_l();
8467 // FALL THROUGH
8468
8469 case STARTING:
8470 // clear auxiliary effect input buffer for next accumulation
8471 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8472 memset(mConfig.inputCfg.buffer.raw,
8473 0,
8474 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8475 }
8476 start_l();
8477 mState = ACTIVE;
8478 break;
8479 case STOPPING:
8480 stop_l();
8481 mDisableWaitCnt = mMaxDisableWaitCnt;
8482 mState = STOPPED;
8483 break;
8484 case STOPPED:
8485 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8486 // turn off sequence.
8487 if (--mDisableWaitCnt == 0) {
8488 reset_l();
8489 mState = IDLE;
8490 }
8491 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008492 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008493 break;
8494 }
8495}
8496
8497void AudioFlinger::EffectModule::process()
8498{
8499 Mutex::Autolock _l(mLock);
8500
Eric Laurentec437d82011-07-26 20:54:46 -07008501 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008502 mConfig.inputCfg.buffer.raw == NULL ||
8503 mConfig.outputCfg.buffer.raw == NULL) {
8504 return;
8505 }
8506
Eric Laurent8f45bd72010-08-31 13:50:07 -07008507 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008508 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8509 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008510 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008511 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008512 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008513 }
8514
8515 // do the actual processing in the effect engine
8516 int ret = (*mEffectInterface)->process(mEffectInterface,
8517 &mConfig.inputCfg.buffer,
8518 &mConfig.outputCfg.buffer);
8519
8520 // force transition to IDLE state when engine is ready
8521 if (mState == STOPPED && ret == -ENODATA) {
8522 mDisableWaitCnt = 1;
8523 }
8524
8525 // clear auxiliary effect input buffer for next accumulation
8526 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008527 memset(mConfig.inputCfg.buffer.raw, 0,
8528 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008529 }
8530 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008531 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8532 // If an insert effect is idle and input buffer is different from output buffer,
8533 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008534 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008535 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008536 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8537 int16_t *in = mConfig.inputCfg.buffer.s16;
8538 int16_t *out = mConfig.outputCfg.buffer.s16;
8539 for (size_t i = 0; i < frameCnt; i++) {
8540 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008541 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008542 }
8543 }
8544}
8545
8546void AudioFlinger::EffectModule::reset_l()
8547{
8548 if (mEffectInterface == NULL) {
8549 return;
8550 }
8551 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8552}
8553
8554status_t AudioFlinger::EffectModule::configure()
8555{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008556 if (mEffectInterface == NULL) {
8557 return NO_INIT;
8558 }
8559
8560 sp<ThreadBase> thread = mThread.promote();
8561 if (thread == 0) {
8562 return DEAD_OBJECT;
8563 }
8564
8565 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07008566 audio_channel_mask_t channelMask = thread->channelMask();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008567
8568 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008569 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008570 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07008571 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008572 }
Glenn Kasten254af182012-07-03 14:59:05 -07008573 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07008574 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8575 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008576 mConfig.inputCfg.samplingRate = thread->sampleRate();
8577 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8578 mConfig.inputCfg.bufferProvider.cookie = NULL;
8579 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8580 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8581 mConfig.outputCfg.bufferProvider.cookie = NULL;
8582 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8583 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8584 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8585 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008586 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008587 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008588 // - in other sessions:
8589 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8590 // other effect: overwrites output buffer: input buffer == output buffer
8591 // Auxiliary effect:
8592 // accumulates in output buffer: input buffer != output buffer
8593 // Therefore: accumulate <=> input buffer != output buffer
8594 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8595 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8596 } else {
8597 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8598 }
8599 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8600 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8601 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8602 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8603
Steve Block3856b092011-10-20 11:56:00 +01008604 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008605 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8606
Mathias Agopian65ab4712010-07-14 17:59:35 -07008607 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008608 uint32_t size = sizeof(int);
8609 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008610 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008611 sizeof(effect_config_t),
8612 &mConfig,
8613 &size,
8614 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008615 if (status == 0) {
8616 status = cmdStatus;
8617 }
8618
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008619 if (status == 0 &&
8620 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8621 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8622 effect_param_t *p = (effect_param_t *)buf32;
8623
8624 p->psize = sizeof(uint32_t);
8625 p->vsize = sizeof(uint32_t);
8626 size = sizeof(int);
8627 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8628
8629 uint32_t latency = 0;
8630 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8631 if (pbt != NULL) {
8632 latency = pbt->latency_l();
8633 }
8634
8635 *((int32_t *)p->data + 1)= latency;
8636 (*mEffectInterface)->command(mEffectInterface,
8637 EFFECT_CMD_SET_PARAM,
8638 sizeof(effect_param_t) + 8,
8639 &buf32,
8640 &size,
8641 &cmdStatus);
8642 }
8643
Mathias Agopian65ab4712010-07-14 17:59:35 -07008644 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8645 (1000 * mConfig.outputCfg.buffer.frameCount);
8646
8647 return status;
8648}
8649
8650status_t AudioFlinger::EffectModule::init()
8651{
8652 Mutex::Autolock _l(mLock);
8653 if (mEffectInterface == NULL) {
8654 return NO_INIT;
8655 }
8656 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008657 uint32_t size = sizeof(status_t);
8658 status_t status = (*mEffectInterface)->command(mEffectInterface,
8659 EFFECT_CMD_INIT,
8660 0,
8661 NULL,
8662 &size,
8663 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008664 if (status == 0) {
8665 status = cmdStatus;
8666 }
8667 return status;
8668}
8669
Eric Laurentec35a142011-10-05 17:42:25 -07008670status_t AudioFlinger::EffectModule::start()
8671{
8672 Mutex::Autolock _l(mLock);
8673 return start_l();
8674}
8675
Mathias Agopian65ab4712010-07-14 17:59:35 -07008676status_t AudioFlinger::EffectModule::start_l()
8677{
8678 if (mEffectInterface == NULL) {
8679 return NO_INIT;
8680 }
8681 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008682 uint32_t size = sizeof(status_t);
8683 status_t status = (*mEffectInterface)->command(mEffectInterface,
8684 EFFECT_CMD_ENABLE,
8685 0,
8686 NULL,
8687 &size,
8688 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008689 if (status == 0) {
8690 status = cmdStatus;
8691 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008692 if (status == 0 &&
8693 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8694 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8695 sp<ThreadBase> thread = mThread.promote();
8696 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008697 audio_stream_t *stream = thread->stream();
8698 if (stream != NULL) {
8699 stream->add_audio_effect(stream, mEffectInterface);
8700 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008701 }
8702 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008703 return status;
8704}
8705
Eric Laurentec437d82011-07-26 20:54:46 -07008706status_t AudioFlinger::EffectModule::stop()
8707{
8708 Mutex::Autolock _l(mLock);
8709 return stop_l();
8710}
8711
Mathias Agopian65ab4712010-07-14 17:59:35 -07008712status_t AudioFlinger::EffectModule::stop_l()
8713{
8714 if (mEffectInterface == NULL) {
8715 return NO_INIT;
8716 }
8717 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008718 uint32_t size = sizeof(status_t);
8719 status_t status = (*mEffectInterface)->command(mEffectInterface,
8720 EFFECT_CMD_DISABLE,
8721 0,
8722 NULL,
8723 &size,
8724 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008725 if (status == 0) {
8726 status = cmdStatus;
8727 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008728 if (status == 0 &&
8729 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8730 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8731 sp<ThreadBase> thread = mThread.promote();
8732 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008733 audio_stream_t *stream = thread->stream();
8734 if (stream != NULL) {
8735 stream->remove_audio_effect(stream, mEffectInterface);
8736 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008737 }
8738 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008739 return status;
8740}
8741
Eric Laurent25f43952010-07-28 05:40:18 -07008742status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8743 uint32_t cmdSize,
8744 void *pCmdData,
8745 uint32_t *replySize,
8746 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008747{
8748 Mutex::Autolock _l(mLock);
Glenn Kastencbe4b362012-10-18 15:51:03 -07008749 ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008750
Eric Laurentec437d82011-07-26 20:54:46 -07008751 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008752 return NO_INIT;
8753 }
Eric Laurent25f43952010-07-28 05:40:18 -07008754 status_t status = (*mEffectInterface)->command(mEffectInterface,
8755 cmdCode,
8756 cmdSize,
8757 pCmdData,
8758 replySize,
8759 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008760 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008761 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008762 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008763 EffectHandle *h = mHandles[i];
8764 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008765 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8766 }
8767 }
8768 }
8769 return status;
8770}
8771
8772status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8773{
8774 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008775 return setEnabled_l(enabled);
8776}
8777
8778// must be called with EffectModule::mLock held
8779status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8780{
8781
Steve Block3856b092011-10-20 11:56:00 +01008782 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008783
8784 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008785 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8786 if (enabled && status != NO_ERROR) {
8787 return status;
8788 }
8789
Mathias Agopian65ab4712010-07-14 17:59:35 -07008790 switch (mState) {
8791 // going from disabled to enabled
8792 case IDLE:
8793 mState = STARTING;
8794 break;
8795 case STOPPED:
8796 mState = RESTART;
8797 break;
8798 case STOPPING:
8799 mState = ACTIVE;
8800 break;
8801
8802 // going from enabled to disabled
8803 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008804 mState = STOPPED;
8805 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008806 case STARTING:
8807 mState = IDLE;
8808 break;
8809 case ACTIVE:
8810 mState = STOPPING;
8811 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008812 case DESTROYED:
8813 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008814 }
8815 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008816 EffectHandle *h = mHandles[i];
8817 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008818 h->setEnabled(enabled);
8819 }
8820 }
8821 }
8822 return NO_ERROR;
8823}
8824
Glenn Kastenc59c0042012-02-02 14:06:11 -08008825bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008826{
8827 switch (mState) {
8828 case RESTART:
8829 case STARTING:
8830 case ACTIVE:
8831 return true;
8832 case IDLE:
8833 case STOPPING:
8834 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008835 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008836 default:
8837 return false;
8838 }
8839}
8840
Glenn Kastenc59c0042012-02-02 14:06:11 -08008841bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008842{
8843 switch (mState) {
8844 case RESTART:
8845 case ACTIVE:
8846 case STOPPING:
8847 case STOPPED:
8848 return true;
8849 case IDLE:
8850 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008851 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008852 default:
8853 return false;
8854 }
8855}
8856
Mathias Agopian65ab4712010-07-14 17:59:35 -07008857status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8858{
8859 Mutex::Autolock _l(mLock);
8860 status_t status = NO_ERROR;
8861
8862 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8863 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008864 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008865 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8866 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008867 status_t cmdStatus;
8868 uint32_t volume[2];
8869 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008870 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008871 volume[0] = *left;
8872 volume[1] = *right;
8873 if (controller) {
8874 pVolume = volume;
8875 }
Eric Laurent25f43952010-07-28 05:40:18 -07008876 status = (*mEffectInterface)->command(mEffectInterface,
8877 EFFECT_CMD_SET_VOLUME,
8878 size,
8879 volume,
8880 &size,
8881 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008882 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8883 *left = volume[0];
8884 *right = volume[1];
8885 }
8886 }
8887 return status;
8888}
8889
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008890status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008891{
Eric Laurent88959252012-08-28 14:26:53 -07008892 if (device == AUDIO_DEVICE_NONE) {
8893 return NO_ERROR;
8894 }
8895
Mathias Agopian65ab4712010-07-14 17:59:35 -07008896 Mutex::Autolock _l(mLock);
8897 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008898 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Eric Laurent88959252012-08-28 14:26:53 -07008899 status_t cmdStatus;
8900 uint32_t size = sizeof(status_t);
8901 uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE :
8902 EFFECT_CMD_SET_INPUT_DEVICE;
8903 status = (*mEffectInterface)->command(mEffectInterface,
8904 cmd,
8905 sizeof(uint32_t),
8906 &device,
8907 &size,
8908 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008909 }
8910 return status;
8911}
8912
Glenn Kastenf78aee72012-01-04 11:00:47 -08008913status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008914{
8915 Mutex::Autolock _l(mLock);
8916 status_t status = NO_ERROR;
8917 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008918 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008919 uint32_t size = sizeof(status_t);
8920 status = (*mEffectInterface)->command(mEffectInterface,
8921 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008922 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008923 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008924 &size,
8925 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008926 if (status == NO_ERROR) {
8927 status = cmdStatus;
8928 }
8929 }
8930 return status;
8931}
8932
Eric Laurent2e9b0f22012-08-31 17:44:06 -07008933status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
8934{
8935 Mutex::Autolock _l(mLock);
8936 status_t status = NO_ERROR;
8937 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
8938 uint32_t size = 0;
8939 status = (*mEffectInterface)->command(mEffectInterface,
8940 EFFECT_CMD_SET_AUDIO_SOURCE,
8941 sizeof(audio_source_t),
8942 &source,
8943 &size,
8944 NULL);
8945 }
8946 return status;
8947}
8948
Eric Laurent59255e42011-07-27 19:49:51 -07008949void AudioFlinger::EffectModule::setSuspended(bool suspended)
8950{
8951 Mutex::Autolock _l(mLock);
8952 mSuspended = suspended;
8953}
Glenn Kastena3a85482012-01-04 11:01:11 -08008954
8955bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008956{
8957 Mutex::Autolock _l(mLock);
8958 return mSuspended;
8959}
8960
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008961bool AudioFlinger::EffectModule::purgeHandles()
8962{
8963 bool enabled = false;
8964 Mutex::Autolock _l(mLock);
8965 for (size_t i = 0; i < mHandles.size(); i++) {
8966 EffectHandle *handle = mHandles[i];
8967 if (handle != NULL && !handle->destroyed_l()) {
8968 handle->effect().clear();
8969 if (handle->hasControl()) {
8970 enabled = handle->enabled();
8971 }
8972 }
8973 }
8974 return enabled;
8975}
8976
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07008977void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008978{
8979 const size_t SIZE = 256;
8980 char buffer[SIZE];
8981 String8 result;
8982
8983 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8984 result.append(buffer);
8985
8986 bool locked = tryLock(mLock);
8987 // failed to lock - AudioFlinger is probably deadlocked
8988 if (!locked) {
8989 result.append("\t\tCould not lock Fx mutex:\n");
8990 }
8991
8992 result.append("\t\tSession Status State Engine:\n");
8993 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8994 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8995 result.append(buffer);
8996
8997 result.append("\t\tDescriptor:\n");
8998 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8999 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
Glenn Kasten8af901c2012-11-01 11:11:38 -07009000 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],
9001 mDescriptor.uuid.node[2],
Mathias Agopian65ab4712010-07-14 17:59:35 -07009002 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
9003 result.append(buffer);
9004 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
Glenn Kasten8af901c2012-11-01 11:11:38 -07009005 mDescriptor.type.timeLow, mDescriptor.type.timeMid,
9006 mDescriptor.type.timeHiAndVersion,
9007 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],
9008 mDescriptor.type.node[2],
Mathias Agopian65ab4712010-07-14 17:59:35 -07009009 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
9010 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07009011 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009012 mDescriptor.apiVersion,
9013 mDescriptor.flags);
9014 result.append(buffer);
9015 snprintf(buffer, SIZE, "\t\t- name: %s\n",
9016 mDescriptor.name);
9017 result.append(buffer);
9018 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
9019 mDescriptor.implementor);
9020 result.append(buffer);
9021
9022 result.append("\t\t- Input configuration:\n");
9023 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
9024 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
9025 (uint32_t)mConfig.inputCfg.buffer.raw,
9026 mConfig.inputCfg.buffer.frameCount,
9027 mConfig.inputCfg.samplingRate,
9028 mConfig.inputCfg.channels,
9029 mConfig.inputCfg.format);
9030 result.append(buffer);
9031
9032 result.append("\t\t- Output configuration:\n");
9033 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
9034 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
9035 (uint32_t)mConfig.outputCfg.buffer.raw,
9036 mConfig.outputCfg.buffer.frameCount,
9037 mConfig.outputCfg.samplingRate,
9038 mConfig.outputCfg.channels,
9039 mConfig.outputCfg.format);
9040 result.append(buffer);
9041
9042 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
9043 result.append(buffer);
9044 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
9045 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009046 EffectHandle *handle = mHandles[i];
9047 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009048 handle->dump(buffer, SIZE);
9049 result.append(buffer);
9050 }
9051 }
9052
9053 result.append("\n");
9054
9055 write(fd, result.string(), result.length());
9056
9057 if (locked) {
9058 mLock.unlock();
9059 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009060}
9061
9062// ----------------------------------------------------------------------------
9063// EffectHandle implementation
9064// ----------------------------------------------------------------------------
9065
9066#undef LOG_TAG
9067#define LOG_TAG "AudioFlinger::EffectHandle"
9068
9069AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
9070 const sp<AudioFlinger::Client>& client,
9071 const sp<IEffectClient>& effectClient,
9072 int32_t priority)
9073 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009074 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009075 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009076{
Steve Block3856b092011-10-20 11:56:00 +01009077 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009078
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009079 if (client == 0) {
9080 return;
9081 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009082 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
9083 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
9084 if (mCblkMemory != 0) {
9085 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
9086
Glenn Kastena0d68332012-01-27 16:47:15 -08009087 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009088 new(mCblk) effect_param_cblk_t();
9089 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009090 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009091 } else {
Glenn Kasten8af901c2012-11-01 11:11:38 -07009092 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE +
9093 sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07009094 return;
9095 }
9096}
9097
9098AudioFlinger::EffectHandle::~EffectHandle()
9099{
Steve Block3856b092011-10-20 11:56:00 +01009100 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009101
9102 if (mEffect == 0) {
9103 mDestroyed = true;
9104 return;
9105 }
9106 mEffect->lock();
9107 mDestroyed = true;
9108 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009109 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009110}
9111
9112status_t AudioFlinger::EffectHandle::enable()
9113{
Steve Block3856b092011-10-20 11:56:00 +01009114 ALOGV("enable %p", this);
Glenn Kastena2049222012-06-22 17:21:07 -07009115 if (!mHasControl) {
9116 return INVALID_OPERATION;
9117 }
9118 if (mEffect == 0) {
9119 return DEAD_OBJECT;
9120 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009121
Eric Laurentdb7c0792011-08-10 10:37:50 -07009122 if (mEnabled) {
9123 return NO_ERROR;
9124 }
9125
Eric Laurent59255e42011-07-27 19:49:51 -07009126 mEnabled = true;
9127
9128 sp<ThreadBase> thread = mEffect->thread().promote();
9129 if (thread != 0) {
9130 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
9131 }
9132
9133 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
9134 if (mEffect->suspended()) {
9135 return NO_ERROR;
9136 }
9137
Eric Laurentdb7c0792011-08-10 10:37:50 -07009138 status_t status = mEffect->setEnabled(true);
9139 if (status != NO_ERROR) {
9140 if (thread != 0) {
9141 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9142 }
9143 mEnabled = false;
9144 }
9145 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009146}
9147
9148status_t AudioFlinger::EffectHandle::disable()
9149{
Steve Block3856b092011-10-20 11:56:00 +01009150 ALOGV("disable %p", this);
Glenn Kastena2049222012-06-22 17:21:07 -07009151 if (!mHasControl) {
9152 return INVALID_OPERATION;
9153 }
9154 if (mEffect == 0) {
9155 return DEAD_OBJECT;
9156 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009157
Eric Laurentdb7c0792011-08-10 10:37:50 -07009158 if (!mEnabled) {
9159 return NO_ERROR;
9160 }
Eric Laurent59255e42011-07-27 19:49:51 -07009161 mEnabled = false;
9162
9163 if (mEffect->suspended()) {
9164 return NO_ERROR;
9165 }
9166
9167 status_t status = mEffect->setEnabled(false);
9168
9169 sp<ThreadBase> thread = mEffect->thread().promote();
9170 if (thread != 0) {
9171 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9172 }
9173
9174 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009175}
9176
9177void AudioFlinger::EffectHandle::disconnect()
9178{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009179 disconnect(true);
9180}
9181
Glenn Kasten58123c32012-02-03 10:32:24 -08009182void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009183{
Glenn Kasten58123c32012-02-03 10:32:24 -08009184 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009185 if (mEffect == 0) {
9186 return;
9187 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009188 // restore suspended effects if the disconnected handle was enabled and the last one.
9189 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009190 sp<ThreadBase> thread = mEffect->thread().promote();
9191 if (thread != 0) {
9192 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9193 }
Eric Laurent59255e42011-07-27 19:49:51 -07009194 }
9195
Mathias Agopian65ab4712010-07-14 17:59:35 -07009196 // release sp on module => module destructor can be called now
9197 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009198 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08009199 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08009200 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009201 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
9202 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08009203 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08009204 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07009205 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
9206 mClient.clear();
9207 }
9208}
9209
Eric Laurent25f43952010-07-28 05:40:18 -07009210status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
9211 uint32_t cmdSize,
9212 void *pCmdData,
9213 uint32_t *replySize,
9214 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009215{
Glenn Kastencbe4b362012-10-18 15:51:03 -07009216 ALOGVV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
9217 cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07009218
9219 // only get parameter command is permitted for applications not controlling the effect
9220 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
9221 return INVALID_OPERATION;
9222 }
Glenn Kastena2049222012-06-22 17:21:07 -07009223 if (mEffect == 0) {
9224 return DEAD_OBJECT;
9225 }
9226 if (mClient == 0) {
9227 return INVALID_OPERATION;
9228 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009229
9230 // handle commands that are not forwarded transparently to effect engine
9231 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07009232 // No need to trylock() here as this function is executed in the binder thread serving a
9233 // particular client process: no risk to block the whole media server process or mixer
9234 // threads if we are stuck here
Mathias Agopian65ab4712010-07-14 17:59:35 -07009235 Mutex::Autolock _l(mCblk->lock);
9236 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
9237 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
9238 mCblk->serverIndex = 0;
9239 mCblk->clientIndex = 0;
9240 return BAD_VALUE;
9241 }
9242 status_t status = NO_ERROR;
9243 while (mCblk->serverIndex < mCblk->clientIndex) {
9244 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07009245 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009246 int *p = (int *)(mBuffer + mCblk->serverIndex);
9247 int size = *p++;
9248 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009249 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009250 break;
9251 }
9252 effect_param_t *param = (effect_param_t *)p;
9253 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009254 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009255 mCblk->serverIndex += size;
9256 continue;
9257 }
Eric Laurent25f43952010-07-28 05:40:18 -07009258 uint32_t psize = sizeof(effect_param_t) +
9259 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
9260 param->vsize;
9261 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
9262 psize,
9263 p,
9264 &rsize,
9265 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07009266 // stop at first error encountered
9267 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009268 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07009269 *(int *)pReplyData = reply;
9270 break;
9271 } else if (reply != NO_ERROR) {
9272 *(int *)pReplyData = reply;
9273 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009274 }
9275 mCblk->serverIndex += size;
9276 }
9277 mCblk->serverIndex = 0;
9278 mCblk->clientIndex = 0;
9279 return status;
9280 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009281 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009282 return enable();
9283 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009284 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009285 return disable();
9286 }
9287
9288 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9289}
9290
Eric Laurent59255e42011-07-27 19:49:51 -07009291void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009292{
Steve Block3856b092011-10-20 11:56:00 +01009293 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009294
9295 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07009296 mEnabled = enabled;
9297
Mathias Agopian65ab4712010-07-14 17:59:35 -07009298 if (signal && mEffectClient != 0) {
9299 mEffectClient->controlStatusChanged(hasControl);
9300 }
9301}
9302
Eric Laurent25f43952010-07-28 05:40:18 -07009303void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
9304 uint32_t cmdSize,
9305 void *pCmdData,
9306 uint32_t replySize,
9307 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009308{
9309 if (mEffectClient != 0) {
9310 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9311 }
9312}
9313
9314
9315
9316void AudioFlinger::EffectHandle::setEnabled(bool enabled)
9317{
9318 if (mEffectClient != 0) {
9319 mEffectClient->enableStatusChanged(enabled);
9320 }
9321}
9322
9323status_t AudioFlinger::EffectHandle::onTransact(
9324 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9325{
9326 return BnEffect::onTransact(code, data, reply, flags);
9327}
9328
9329
9330void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
9331{
Glenn Kastena0d68332012-01-27 16:47:15 -08009332 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009333
9334 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08009335 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07009336 mPriority,
9337 mHasControl,
9338 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009339 mCblk ? mCblk->clientIndex : 0,
9340 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07009341 );
9342
9343 if (locked) {
9344 mCblk->lock.unlock();
9345 }
9346}
9347
9348#undef LOG_TAG
9349#define LOG_TAG "AudioFlinger::EffectChain"
9350
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009351AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009352 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009353 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07009354 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9355 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009356{
Dima Zavinfce7a472011-04-19 22:30:36 -07009357 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009358 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009359 return;
9360 }
9361 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9362 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009363}
9364
9365AudioFlinger::EffectChain::~EffectChain()
9366{
9367 if (mOwnInBuffer) {
9368 delete mInBuffer;
9369 }
9370
9371}
9372
Eric Laurent59255e42011-07-27 19:49:51 -07009373// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Glenn Kasten8af901c2012-11-01 11:11:38 -07009374sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(
9375 effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009376{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009377 size_t size = mEffects.size();
9378
9379 for (size_t i = 0; i < size; i++) {
9380 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009381 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009382 }
9383 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009384 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009385}
9386
Eric Laurent59255e42011-07-27 19:49:51 -07009387// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009388sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009389{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009390 size_t size = mEffects.size();
9391
9392 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009393 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9394 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009395 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009396 }
9397 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009398 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009399}
9400
Eric Laurent59255e42011-07-27 19:49:51 -07009401// getEffectFromType_l() must be called with ThreadBase::mLock held
9402sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9403 const effect_uuid_t *type)
9404{
Eric Laurent59255e42011-07-27 19:49:51 -07009405 size_t size = mEffects.size();
9406
9407 for (size_t i = 0; i < size; i++) {
9408 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009409 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009410 }
9411 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009412 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009413}
9414
Eric Laurent91b14c42012-05-30 12:30:29 -07009415void AudioFlinger::EffectChain::clearInputBuffer()
9416{
9417 Mutex::Autolock _l(mLock);
9418 sp<ThreadBase> thread = mThread.promote();
9419 if (thread == 0) {
9420 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9421 return;
9422 }
9423 clearInputBuffer_l(thread);
9424}
9425
9426// Must be called with EffectChain::mLock locked
9427void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9428{
9429 size_t numSamples = thread->frameCount() * thread->channelCount();
9430 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9431
9432}
9433
Mathias Agopian65ab4712010-07-14 17:59:35 -07009434// Must be called with EffectChain::mLock locked
9435void AudioFlinger::EffectChain::process_l()
9436{
Eric Laurentdac69112010-09-28 14:09:57 -07009437 sp<ThreadBase> thread = mThread.promote();
9438 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009439 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009440 return;
9441 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009442 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9443 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009444 // always process effects unless no more tracks are on the session and the effect tail
9445 // has been rendered
9446 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009447 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009448 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009449
Eric Laurent544fe9b2011-11-11 15:42:52 -08009450 if (!tracksOnSession && mTailBufferCount == 0) {
9451 doProcess = false;
9452 }
9453
9454 if (activeTrackCnt() == 0) {
9455 // if no track is active and the effect tail has not been rendered,
9456 // the input buffer must be cleared here as the mixer process will not do it
9457 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009458 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009459 if (mTailBufferCount > 0) {
9460 mTailBufferCount--;
9461 }
9462 }
9463 }
Eric Laurentdac69112010-09-28 14:09:57 -07009464 }
9465
Mathias Agopian65ab4712010-07-14 17:59:35 -07009466 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009467 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009468 for (size_t i = 0; i < size; i++) {
9469 mEffects[i]->process();
9470 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009471 }
9472 for (size_t i = 0; i < size; i++) {
9473 mEffects[i]->updateState();
9474 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009475}
9476
Eric Laurentcab11242010-07-15 12:50:15 -07009477// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009478status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009479{
9480 effect_descriptor_t desc = effect->desc();
9481 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9482
9483 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009484 effect->setChain(this);
9485 sp<ThreadBase> thread = mThread.promote();
9486 if (thread == 0) {
9487 return NO_INIT;
9488 }
9489 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009490
9491 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9492 // Auxiliary effects are inserted at the beginning of mEffects vector as
9493 // they are processed first and accumulated in chain input buffer
9494 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009495
Mathias Agopian65ab4712010-07-14 17:59:35 -07009496 // the input buffer for auxiliary effect contains mono samples in
9497 // 32 bit format. This is to avoid saturation in AudoMixer
9498 // accumulation stage. Saturation is done in EffectModule::process() before
9499 // calling the process in effect engine
9500 size_t numSamples = thread->frameCount();
9501 int32_t *buffer = new int32_t[numSamples];
9502 memset(buffer, 0, numSamples * sizeof(int32_t));
9503 effect->setInBuffer((int16_t *)buffer);
9504 // auxiliary effects output samples to chain input buffer for further processing
9505 // by insert effects
9506 effect->setOutBuffer(mInBuffer);
9507 } else {
9508 // Insert effects are inserted at the end of mEffects vector as they are processed
9509 // after track and auxiliary effects.
9510 // Insert effect order as a function of indicated preference:
9511 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9512 // another effect is present
9513 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9514 // last effect claiming first position
9515 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9516 // first effect claiming last position
9517 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9518 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9519 // already present
9520
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009521 size_t size = mEffects.size();
9522 size_t idx_insert = size;
9523 ssize_t idx_insert_first = -1;
9524 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009525
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009526 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009527 effect_descriptor_t d = mEffects[i]->desc();
9528 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9529 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9530 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9531 // check invalid effect chaining combinations
9532 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9533 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Glenn Kasten8af901c2012-11-01 11:11:38 -07009534 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s",
9535 desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009536 return INVALID_OPERATION;
9537 }
9538 // remember position of first insert effect and by default
9539 // select this as insert position for new effect
9540 if (idx_insert == size) {
9541 idx_insert = i;
9542 }
9543 // remember position of last insert effect claiming
9544 // first position
9545 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9546 idx_insert_first = i;
9547 }
9548 // remember position of first insert effect claiming
9549 // last position
9550 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9551 idx_insert_last == -1) {
9552 idx_insert_last = i;
9553 }
9554 }
9555 }
9556
9557 // modify idx_insert from first position if needed
9558 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9559 if (idx_insert_last != -1) {
9560 idx_insert = idx_insert_last;
9561 } else {
9562 idx_insert = size;
9563 }
9564 } else {
9565 if (idx_insert_first != -1) {
9566 idx_insert = idx_insert_first + 1;
9567 }
9568 }
9569
9570 // always read samples from chain input buffer
9571 effect->setInBuffer(mInBuffer);
9572
9573 // if last effect in the chain, output samples to chain
9574 // output buffer, otherwise to chain input buffer
9575 if (idx_insert == size) {
9576 if (idx_insert != 0) {
9577 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9578 mEffects[idx_insert-1]->configure();
9579 }
9580 effect->setOutBuffer(mOutBuffer);
9581 } else {
9582 effect->setOutBuffer(mInBuffer);
9583 }
9584 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009585
Glenn Kasten8af901c2012-11-01 11:11:38 -07009586 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this,
9587 idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009588 }
9589 effect->configure();
9590 return NO_ERROR;
9591}
9592
Eric Laurentcab11242010-07-15 12:50:15 -07009593// removeEffect_l() must be called with PlaybackThread::mLock held
9594size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009595{
9596 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009597 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009598 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9599
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009600 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009601 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009602 // calling stop here will remove pre-processing effect from the audio HAL.
9603 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9604 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009605 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9606 mEffects[i]->state() == EffectModule::STOPPING) {
9607 mEffects[i]->stop();
9608 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009609 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9610 delete[] effect->inBuffer();
9611 } else {
9612 if (i == size - 1 && i != 0) {
9613 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9614 mEffects[i - 1]->configure();
9615 }
9616 }
9617 mEffects.removeAt(i);
Glenn Kasten8af901c2012-11-01 11:11:38 -07009618 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(),
9619 this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009620 break;
9621 }
9622 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009623
9624 return mEffects.size();
9625}
9626
Eric Laurentcab11242010-07-15 12:50:15 -07009627// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009628void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009629{
9630 size_t size = mEffects.size();
9631 for (size_t i = 0; i < size; i++) {
9632 mEffects[i]->setDevice(device);
9633 }
9634}
9635
Eric Laurentcab11242010-07-15 12:50:15 -07009636// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009637void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009638{
9639 size_t size = mEffects.size();
9640 for (size_t i = 0; i < size; i++) {
9641 mEffects[i]->setMode(mode);
9642 }
9643}
9644
Eric Laurent2e9b0f22012-08-31 17:44:06 -07009645// setAudioSource_l() must be called with PlaybackThread::mLock held
9646void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
9647{
9648 size_t size = mEffects.size();
9649 for (size_t i = 0; i < size; i++) {
9650 mEffects[i]->setAudioSource(source);
9651 }
9652}
9653
Eric Laurentcab11242010-07-15 12:50:15 -07009654// setVolume_l() must be called with PlaybackThread::mLock held
9655bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009656{
9657 uint32_t newLeft = *left;
9658 uint32_t newRight = *right;
9659 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009660 int ctrlIdx = -1;
9661 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009662
Eric Laurentcab11242010-07-15 12:50:15 -07009663 // first update volume controller
9664 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009665 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009666 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9667 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009668 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009669 break;
9670 }
9671 }
9672
9673 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009674 if (hasControl) {
9675 *left = mNewLeftVolume;
9676 *right = mNewRightVolume;
9677 }
9678 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009679 }
9680
9681 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009682 mLeftVolume = newLeft;
9683 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009684
9685 // second get volume update from volume controller
9686 if (ctrlIdx >= 0) {
9687 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009688 mNewLeftVolume = newLeft;
9689 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009690 }
9691 // then indicate volume to all other effects in chain.
9692 // Pass altered volume to effects before volume controller
9693 // and requested volume to effects after controller
9694 uint32_t lVol = newLeft;
9695 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009696
Mathias Agopian65ab4712010-07-14 17:59:35 -07009697 for (size_t i = 0; i < size; i++) {
Glenn Kastena2049222012-06-22 17:21:07 -07009698 if ((int)i == ctrlIdx) {
9699 continue;
9700 }
Eric Laurentcab11242010-07-15 12:50:15 -07009701 // this also works for ctrlIdx == -1 when there is no volume controller
9702 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009703 lVol = *left;
9704 rVol = *right;
9705 }
9706 mEffects[i]->setVolume(&lVol, &rVol, false);
9707 }
9708 *left = newLeft;
9709 *right = newRight;
9710
9711 return hasControl;
9712}
9713
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009714void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009715{
9716 const size_t SIZE = 256;
9717 char buffer[SIZE];
9718 String8 result;
9719
9720 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9721 result.append(buffer);
9722
9723 bool locked = tryLock(mLock);
9724 // failed to lock - AudioFlinger is probably deadlocked
9725 if (!locked) {
9726 result.append("\tCould not lock mutex:\n");
9727 }
9728
Eric Laurentcab11242010-07-15 12:50:15 -07009729 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9730 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009731 mEffects.size(),
9732 (uint32_t)mInBuffer,
9733 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009734 mActiveTrackCnt);
9735 result.append(buffer);
9736 write(fd, result.string(), result.size());
9737
9738 for (size_t i = 0; i < mEffects.size(); ++i) {
9739 sp<EffectModule> effect = mEffects[i];
9740 if (effect != 0) {
9741 effect->dump(fd, args);
9742 }
9743 }
9744
9745 if (locked) {
9746 mLock.unlock();
9747 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009748}
9749
Eric Laurent59255e42011-07-27 19:49:51 -07009750// must be called with ThreadBase::mLock held
9751void AudioFlinger::EffectChain::setEffectSuspended_l(
9752 const effect_uuid_t *type, bool suspend)
9753{
9754 sp<SuspendedEffectDesc> desc;
9755 // use effect type UUID timelow as key as there is no real risk of identical
9756 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009757 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009758 if (suspend) {
9759 if (index >= 0) {
9760 desc = mSuspendedEffects.valueAt(index);
9761 } else {
9762 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -08009763 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07009764 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009765 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009766 }
9767 if (desc->mRefCount++ == 0) {
9768 sp<EffectModule> effect = getEffectIfEnabled(type);
9769 if (effect != 0) {
9770 desc->mEffect = effect;
9771 effect->setSuspended(true);
9772 effect->setEnabled(false);
9773 }
9774 }
9775 } else {
9776 if (index < 0) {
9777 return;
9778 }
9779 desc = mSuspendedEffects.valueAt(index);
9780 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009781 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009782 desc->mRefCount = 1;
9783 }
9784 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009785 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009786 if (desc->mEffect != 0) {
9787 sp<EffectModule> effect = desc->mEffect.promote();
9788 if (effect != 0) {
9789 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009790 effect->lock();
9791 EffectHandle *handle = effect->controlHandle_l();
9792 if (handle != NULL && !handle->destroyed_l()) {
9793 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009794 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009795 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009796 }
9797 desc->mEffect.clear();
9798 }
9799 mSuspendedEffects.removeItemsAt(index);
9800 }
9801 }
9802}
9803
9804// must be called with ThreadBase::mLock held
9805void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9806{
9807 sp<SuspendedEffectDesc> desc;
9808
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009809 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009810 if (suspend) {
9811 if (index >= 0) {
9812 desc = mSuspendedEffects.valueAt(index);
9813 } else {
9814 desc = new SuspendedEffectDesc();
9815 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009816 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009817 }
9818 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009819 Vector< sp<EffectModule> > effects;
9820 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009821 for (size_t i = 0; i < effects.size(); i++) {
9822 setEffectSuspended_l(&effects[i]->desc().type, true);
9823 }
9824 }
9825 } else {
9826 if (index < 0) {
9827 return;
9828 }
9829 desc = mSuspendedEffects.valueAt(index);
9830 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009831 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009832 desc->mRefCount = 1;
9833 }
9834 if (--desc->mRefCount == 0) {
9835 Vector<const effect_uuid_t *> types;
9836 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9837 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9838 continue;
9839 }
9840 types.add(&mSuspendedEffects.valueAt(i)->mType);
9841 }
9842 for (size_t i = 0; i < types.size(); i++) {
9843 setEffectSuspended_l(types[i], false);
9844 }
Glenn Kasten8af901c2012-11-01 11:11:38 -07009845 ALOGV("setEffectSuspendedAll_l() remove entry for %08x",
9846 mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009847 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9848 }
9849 }
9850}
9851
Eric Laurent6bffdb82011-09-23 08:40:41 -07009852
9853// The volume effect is used for automated tests only
9854#ifndef OPENSL_ES_H_
9855static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9856 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9857const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9858#endif //OPENSL_ES_H_
9859
Eric Laurentdb7c0792011-08-10 10:37:50 -07009860bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9861{
9862 // auxiliary effects and visualizer are never suspended on output mix
9863 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9864 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009865 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9866 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009867 return false;
9868 }
9869 return true;
9870}
9871
Glenn Kasten8af901c2012-11-01 11:11:38 -07009872void AudioFlinger::EffectChain::getSuspendEligibleEffects(
9873 Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009874{
Glenn Kastend0539712012-01-30 12:56:03 -08009875 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009876 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009877 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9878 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009879 }
Eric Laurent59255e42011-07-27 19:49:51 -07009880 }
Eric Laurent59255e42011-07-27 19:49:51 -07009881}
9882
9883sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9884 const effect_uuid_t *type)
9885{
Glenn Kasten090f0192012-01-30 13:00:02 -08009886 sp<EffectModule> effect = getEffectFromType_l(type);
9887 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009888}
9889
9890void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9891 bool enabled)
9892{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009893 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009894 if (enabled) {
9895 if (index < 0) {
9896 // if the effect is not suspend check if all effects are suspended
9897 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9898 if (index < 0) {
9899 return;
9900 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009901 if (!isEffectEligibleForSuspend(effect->desc())) {
9902 return;
9903 }
Eric Laurent59255e42011-07-27 19:49:51 -07009904 setEffectSuspended_l(&effect->desc().type, enabled);
9905 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009906 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009907 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009908 return;
9909 }
Eric Laurent59255e42011-07-27 19:49:51 -07009910 }
Steve Block3856b092011-10-20 11:56:00 +01009911 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009912 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009913 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9914 // if effect is requested to suspended but was not yet enabled, supend it now.
9915 if (desc->mEffect == 0) {
9916 desc->mEffect = effect;
9917 effect->setEnabled(false);
9918 effect->setSuspended(true);
9919 }
9920 } else {
9921 if (index < 0) {
9922 return;
9923 }
Steve Block3856b092011-10-20 11:56:00 +01009924 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009925 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009926 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9927 desc->mEffect.clear();
9928 effect->setSuspended(false);
9929 }
9930}
9931
Mathias Agopian65ab4712010-07-14 17:59:35 -07009932#undef LOG_TAG
9933#define LOG_TAG "AudioFlinger"
9934
9935// ----------------------------------------------------------------------------
9936
9937status_t AudioFlinger::onTransact(
9938 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9939{
9940 return BnAudioFlinger::onTransact(code, data, reply, flags);
9941}
9942
Mathias Agopian65ab4712010-07-14 17:59:35 -07009943}; // namespace android