blob: 1ce47a3a2d8e2a914620fafbef893f14d33a106a [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070030#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070031#include <binder/Parcel.h>
32#include <binder/IPCThreadState.h>
33#include <utils/String16.h>
34#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070035#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070036
Dima Zavinfce7a472011-04-19 22:30:36 -070037#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080039#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040
Glenn Kastend3cee2f2012-03-13 17:55:35 -070041#undef ADD_BATTERY_DATA
42
43#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080044#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080045#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070046#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070047
48#include <private/media/AudioTrackShared.h>
49#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070050
Dima Zavin64760242011-05-11 14:15:23 -070051#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070052#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
54#include "AudioMixer.h"
55#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080056#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070059#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070060#include <audio_effects/effect_ns.h>
61#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Glenn Kasten3b21c502011-12-15 09:52:39 -080063#include <audio_utils/primitives.h>
64
Eric Laurentfeb0db62011-07-22 09:04:31 -070065#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080066
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070067// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080068#ifdef DEBUG_CPU_USAGE
69#include <cpustats/CentralTendencyStatistics.h>
70#include <cpustats/ThreadCpuUsage.h>
71#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070072
John Grossman4ff14ba2012-02-08 16:37:41 -080073#include <common_time/cc_helper.h>
74#include <common_time/local_clock.h>
75
Glenn Kasten58912562012-04-03 10:45:00 -070076#include "FastMixer.h"
77
78// NBAIO implementations
Glenn Kasten2dd4bdd2012-08-29 11:10:32 -070079#include <media/nbaio/AudioStreamOutSink.h>
80#include <media/nbaio/MonoPipe.h>
81#include <media/nbaio/MonoPipeReader.h>
82#include <media/nbaio/Pipe.h>
83#include <media/nbaio/PipeReader.h>
84#include <media/nbaio/SourceAudioBufferProvider.h>
Glenn Kasten58912562012-04-03 10:45:00 -070085
Glenn Kasten1dc28b72012-04-24 10:01:03 -070086#include "SchedulingPolicyService.h"
Glenn Kasten58912562012-04-03 10:45:00 -070087
Mathias Agopian65ab4712010-07-14 17:59:35 -070088// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
John Grossman1c345192012-03-27 14:00:17 -070090// Note: the following macro is used for extremely verbose logging message. In
91// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
92// 0; but one side effect of this is to turn all LOGV's as well. Some messages
93// are so verbose that we want to suppress them even when we have ALOG_ASSERT
94// turned on. Do not uncomment the #def below unless you really know what you
95// are doing and want to see all of the extremely verbose messages.
96//#define VERY_VERY_VERBOSE_LOGGING
97#ifdef VERY_VERY_VERBOSE_LOGGING
98#define ALOGVV ALOGV
99#else
100#define ALOGVV(a...) do { } while(0)
101#endif
Eric Laurentde070132010-07-13 04:45:46 -0700102
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103namespace android {
104
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800105static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
106static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700107
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800109static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110
111// retry counts for buffer fill timeout
112// 50 * ~20msecs = 1 second
113static const int8_t kMaxTrackRetries = 50;
114static const int8_t kMaxTrackStartupRetries = 50;
115// allow less retry attempts on direct output thread.
116// direct outputs can be a scarce resource in audio hardware and should
117// be released as quickly as possible.
118static const int8_t kMaxTrackRetriesDirect = 2;
119
120static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800121static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700122
Glenn Kasten7dede872011-12-13 11:04:14 -0800123// don't warn about blocked writes or record buffer overflows more often than this
124static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700125
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700126// RecordThread loop sleep time upon application overrun or audio HAL read error
127static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128
Glenn Kasten7dede872011-12-13 11:04:14 -0800129// maximum time to wait for setParameters to complete
130static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700131
Eric Laurent7cafbb32011-11-22 18:50:29 -0800132// minimum sleep time for the mixer thread loop when tracks are active but in underrun
133static const uint32_t kMinThreadSleepTimeUs = 5000;
134// maximum divider applied to the active sleep time in the mixer thread loop
135static const uint32_t kMaxThreadSleepTimeShift = 2;
136
Glenn Kasten58912562012-04-03 10:45:00 -0700137// minimum normal mix buffer size, expressed in milliseconds rather than frames
138static const uint32_t kMinNormalMixBufferSizeMs = 20;
Glenn Kasten4adcede2012-05-14 12:26:02 -0700139// maximum normal mix buffer size
140static const uint32_t kMaxNormalMixBufferSizeMs = 24;
Glenn Kasten58912562012-04-03 10:45:00 -0700141
John Grossman4ff14ba2012-02-08 16:37:41 -0800142nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800143
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700144// Whether to use fast mixer
145static const enum {
146 FastMixer_Never, // never initialize or use: for debugging only
147 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
148 // normal mixer multiplier is 1
149 FastMixer_Static, // initialize if needed, then use all the time if initialized,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700150 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700151 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700152 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700153 // FIXME for FastMixer_Dynamic:
154 // Supporting this option will require fixing HALs that can't handle large writes.
155 // For example, one HAL implementation returns an error from a large write,
156 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
157 // We could either fix the HAL implementations, or provide a wrapper that breaks
158 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
159} kUseFastMixer = FastMixer_Static;
160
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700161static uint32_t gScreenState; // incremented by 2 when screen state changes, bit 0 == 1 means "off"
162 // AudioFlinger::setParameters() updates, other threads read w/o lock
163
Glenn Kastenfd4e20c2012-06-04 11:51:12 -0700164// Priorities for requestPriority
165static const int kPriorityAudioApp = 2;
166static const int kPriorityFastMixer = 3;
167
Glenn Kasten3ed29202012-08-07 15:24:44 -0700168// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
169// for the track. The client then sub-divides this into smaller buffers for its use.
170// Currently the client uses double-buffering by default, but doesn't tell us about that.
171// So for now we just assume that client is double-buffered.
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700172// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
173// N-buffering, so AudioFlinger could allocate the right amount of memory.
Glenn Kasten3ed29202012-08-07 15:24:44 -0700174// See the client's minBufCount and mNotificationFramesAct calculations for details.
175static const int kFastTrackMultiplier = 2;
176
Mathias Agopian65ab4712010-07-14 17:59:35 -0700177// ----------------------------------------------------------------------------
178
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700179#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800180// To collect the amplifier usage
181static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800182 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
183 if (service == NULL) {
184 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800185 return;
186 }
187
188 service->addBatteryData(params);
189}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700190#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800191
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700192static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700193{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700194 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700195 int rc;
196
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700197 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
198 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
199 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
200 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700201 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700202 }
203 rc = audio_hw_device_open(mod, dev);
204 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
205 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
206 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700207 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700208 }
Bumble-Bee146029d2012-11-29 16:26:40 +0000209#if !defined(ICS_AUDIO_BLOB) && !defined(MR0_AUDIO_BLOB)
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700210 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
211 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
212 rc = BAD_VALUE;
213 goto out;
214 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +0100215#endif
Dima Zavin799a70e2011-04-18 16:57:27 -0700216 return 0;
217
218out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700219 *dev = NULL;
220 return rc;
221}
222
Mathias Agopian65ab4712010-07-14 17:59:35 -0700223// ----------------------------------------------------------------------------
224
225AudioFlinger::AudioFlinger()
226 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800227 mPrimaryHardwareDev(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700228 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800229 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800230 mMasterMute(false),
231 mNextUniqueId(1),
232 mMode(AUDIO_MODE_INVALID),
233 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700234{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700235}
236
237void AudioFlinger::onFirstRef()
238{
Dima Zavin799a70e2011-04-18 16:57:27 -0700239 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700240
Eric Laurent93575202011-01-18 18:39:02 -0800241 Mutex::Autolock _l(mLock);
242
Dima Zavin799a70e2011-04-18 16:57:27 -0700243 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800244 char val_str[PROPERTY_VALUE_MAX] = { 0 };
245 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
246 uint32_t int_val;
247 if (1 == sscanf(val_str, "%u", &int_val)) {
248 mStandbyTimeInNsecs = milliseconds(int_val);
249 ALOGI("Using %u mSec as standby time.", int_val);
250 } else {
251 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
252 ALOGI("Using default %u mSec as standby time.",
253 (uint32_t)(mStandbyTimeInNsecs / 1000000));
254 }
255 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700256
Eric Laurenta4c5a552012-03-29 10:12:40 -0700257 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700258}
259
260AudioFlinger::~AudioFlinger()
261{
262 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700263 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700264 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700265 }
266 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700267 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700268 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700269 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700270
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800271 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
272 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700273 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
274 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700275 }
276}
277
Eric Laurenta4c5a552012-03-29 10:12:40 -0700278static const char * const audio_interfaces[] = {
279 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
280 AUDIO_HARDWARE_MODULE_ID_A2DP,
281 AUDIO_HARDWARE_MODULE_ID_USB,
282};
283#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
284
John Grossmanee578c02012-07-23 17:05:46 -0700285AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
286 audio_module_handle_t module,
287 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700288{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700289 // if module is 0, the request comes from an old policy manager and we should load
290 // well known modules
291 if (module == 0) {
292 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
293 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
294 loadHwModule_l(audio_interfaces[i]);
295 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700296 // then try to find a module supporting the requested device.
297 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
298 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
299 audio_hw_device_t *dev = audioHwDevice->hwDevice();
300 if ((dev->get_supported_devices != NULL) &&
301 (dev->get_supported_devices(dev) & devices) == devices)
302 return audioHwDevice;
303 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700304 } else {
305 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700306 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
307 if (audioHwDevice != NULL) {
308 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700309 }
310 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700311
Dima Zavin799a70e2011-04-18 16:57:27 -0700312 return NULL;
313}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700314
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700315void AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700316{
317 const size_t SIZE = 256;
318 char buffer[SIZE];
319 String8 result;
320
321 result.append("Clients:\n");
322 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800323 sp<Client> client = mClients.valueAt(i).promote();
324 if (client != 0) {
325 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
326 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700327 }
328 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700329
330 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800331 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700332 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
333 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800334 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700335 result.append(buffer);
336 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700337 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700338}
339
340
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700341void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700342{
343 const size_t SIZE = 256;
344 char buffer[SIZE];
345 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800346 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700347
John Grossman4ff14ba2012-02-08 16:37:41 -0800348 snprintf(buffer, SIZE, "Hardware status: %d\n"
349 "Standby Time mSec: %u\n",
350 hardwareStatus,
351 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700352 result.append(buffer);
353 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700354}
355
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700356void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700357{
358 const size_t SIZE = 256;
359 char buffer[SIZE];
360 String8 result;
361 snprintf(buffer, SIZE, "Permission Denial: "
362 "can't dump AudioFlinger from pid=%d, uid=%d\n",
363 IPCThreadState::self()->getCallingPid(),
364 IPCThreadState::self()->getCallingUid());
365 result.append(buffer);
366 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700367}
368
369static bool tryLock(Mutex& mutex)
370{
371 bool locked = false;
372 for (int i = 0; i < kDumpLockRetries; ++i) {
373 if (mutex.tryLock() == NO_ERROR) {
374 locked = true;
375 break;
376 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800377 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700378 }
379 return locked;
380}
381
382status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
383{
Glenn Kasten44deb052012-02-05 18:09:08 -0800384 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700385 dumpPermissionDenial(fd, args);
386 } else {
387 // get state of hardware lock
388 bool hardwareLocked = tryLock(mHardwareLock);
389 if (!hardwareLocked) {
390 String8 result(kHardwareLockedString);
391 write(fd, result.string(), result.size());
392 } else {
393 mHardwareLock.unlock();
394 }
395
396 bool locked = tryLock(mLock);
397
398 // failed to lock - AudioFlinger is probably deadlocked
399 if (!locked) {
400 String8 result(kDeadlockedString);
401 write(fd, result.string(), result.size());
402 }
403
404 dumpClients(fd, args);
405 dumpInternals(fd, args);
406
407 // dump playback threads
408 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
409 mPlaybackThreads.valueAt(i)->dump(fd, args);
410 }
411
412 // dump record threads
413 for (size_t i = 0; i < mRecordThreads.size(); i++) {
414 mRecordThreads.valueAt(i)->dump(fd, args);
415 }
416
Dima Zavin799a70e2011-04-18 16:57:27 -0700417 // dump all hardware devs
418 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700419 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700420 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700421 }
422 if (locked) mLock.unlock();
423 }
424 return NO_ERROR;
425}
426
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800427sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
428{
429 // If pid is already in the mClients wp<> map, then use that entry
430 // (for which promote() is always != 0), otherwise create a new entry and Client.
431 sp<Client> client = mClients.valueFor(pid).promote();
432 if (client == 0) {
433 client = new Client(this, pid);
434 mClients.add(pid, client);
435 }
436
437 return client;
438}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700439
440// IAudioFlinger interface
441
442
443sp<IAudioTrack> AudioFlinger::createTrack(
444 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800445 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700446 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800447 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700448 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700449 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800450 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700451 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800452 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800453 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700454 int *sessionId,
455 status_t *status)
456{
457 sp<PlaybackThread::Track> track;
458 sp<TrackHandle> trackHandle;
459 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700460 status_t lStatus;
461 int lSessionId;
462
Glenn Kasten263709e2012-01-06 08:40:01 -0800463 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
464 // but if someone uses binder directly they could bypass that and cause us to crash
465 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000466 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700467 lStatus = BAD_VALUE;
468 goto Exit;
469 }
470
471 {
472 Mutex::Autolock _l(mLock);
473 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700474 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700475 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000476 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700477 lStatus = BAD_VALUE;
478 goto Exit;
479 }
480
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800481 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700482
Steve Block3856b092011-10-20 11:56:00 +0100483 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700484 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700485 // check if an effect chain with the same session ID is present on another
486 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700487 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700488 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
489 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700490 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700491 if (sessions & PlaybackThread::EFFECT_SESSION) {
492 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700493 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700494 }
Eric Laurentde070132010-07-13 04:45:46 -0700495 }
496 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700497 lSessionId = *sessionId;
498 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700499 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700500 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700501 if (sessionId != NULL) {
502 *sessionId = lSessionId;
503 }
504 }
Steve Block3856b092011-10-20 11:56:00 +0100505 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700506
507 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800508 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700509
510 // move effect chain to this output thread if an effect on same session was waiting
511 // for a track to be created
512 if (lStatus == NO_ERROR && effectThread != NULL) {
513 Mutex::Autolock _dl(thread->mLock);
514 Mutex::Autolock _sl(effectThread->mLock);
515 moveEffectChain_l(lSessionId, effectThread, thread, true);
516 }
Eric Laurenta011e352012-03-29 15:51:43 -0700517
518 // Look for sync events awaiting for a session to be used.
519 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
520 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
521 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700522 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700523 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700524 } else {
525 mPendingSyncEvents[i]->cancel();
526 }
Eric Laurenta011e352012-03-29 15:51:43 -0700527 mPendingSyncEvents.removeAt(i);
528 i--;
529 }
530 }
531 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700532 }
533 if (lStatus == NO_ERROR) {
534 trackHandle = new TrackHandle(track);
535 } else {
536 // remove local strong reference to Client before deleting the Track so that the Client
537 // destructor is called by the TrackBase destructor with mLock held
538 client.clear();
539 track.clear();
540 }
541
542Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700543 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700544 *status = lStatus;
545 }
546 return trackHandle;
547}
548
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800549uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700550{
551 Mutex::Autolock _l(mLock);
552 PlaybackThread *thread = checkPlaybackThread_l(output);
553 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000554 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700555 return 0;
556 }
557 return thread->sampleRate();
558}
559
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800560int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700561{
562 Mutex::Autolock _l(mLock);
563 PlaybackThread *thread = checkPlaybackThread_l(output);
564 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000565 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700566 return 0;
567 }
568 return thread->channelCount();
569}
570
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800571audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700572{
573 Mutex::Autolock _l(mLock);
574 PlaybackThread *thread = checkPlaybackThread_l(output);
575 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000576 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800577 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578 }
579 return thread->format();
580}
581
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800582size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700583{
584 Mutex::Autolock _l(mLock);
585 PlaybackThread *thread = checkPlaybackThread_l(output);
586 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000587 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700588 return 0;
589 }
Glenn Kasten58912562012-04-03 10:45:00 -0700590 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
591 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700592 return thread->frameCount();
593}
594
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800595uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700596{
597 Mutex::Autolock _l(mLock);
598 PlaybackThread *thread = checkPlaybackThread_l(output);
599 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000600 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700601 return 0;
602 }
603 return thread->latency();
604}
605
606status_t AudioFlinger::setMasterVolume(float value)
607{
Eric Laurenta1884f92011-08-23 08:25:03 -0700608 status_t ret = initCheck();
609 if (ret != NO_ERROR) {
610 return ret;
611 }
612
Mathias Agopian65ab4712010-07-14 17:59:35 -0700613 // check calling permissions
614 if (!settingsAllowed()) {
615 return PERMISSION_DENIED;
616 }
617
Eric Laurenta4c5a552012-03-29 10:12:40 -0700618 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700619 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700620
John Grossmanee578c02012-07-23 17:05:46 -0700621 // Set master volume in the HALs which support it.
622 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
623 AutoMutex lock(mHardwareLock);
624 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800625
John Grossmanee578c02012-07-23 17:05:46 -0700626 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
627 if (dev->canSetMasterVolume()) {
628 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800629 }
John Grossmanee578c02012-07-23 17:05:46 -0700630 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700631 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700632
John Grossmanee578c02012-07-23 17:05:46 -0700633 // Now set the master volume in each playback thread. Playback threads
634 // assigned to HALs which do not have master volume support will apply
635 // master volume during the mix operation. Threads with HALs which do
636 // support master volume will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800637 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700638 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700639
640 return NO_ERROR;
641}
642
Glenn Kastenf78aee72012-01-04 11:00:47 -0800643status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700644{
Eric Laurenta1884f92011-08-23 08:25:03 -0700645 status_t ret = initCheck();
646 if (ret != NO_ERROR) {
647 return ret;
648 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700649
650 // check calling permissions
651 if (!settingsAllowed()) {
652 return PERMISSION_DENIED;
653 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800654 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000655 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700656 return BAD_VALUE;
657 }
658
659 { // scope for the lock
660 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700661 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700662 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700663 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700664 mHardwareStatus = AUDIO_HW_IDLE;
665 }
666
667 if (NO_ERROR == ret) {
668 Mutex::Autolock _l(mLock);
669 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800670 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700671 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700672 }
673
674 return ret;
675}
676
677status_t AudioFlinger::setMicMute(bool state)
678{
Eric Laurenta1884f92011-08-23 08:25:03 -0700679 status_t ret = initCheck();
680 if (ret != NO_ERROR) {
681 return ret;
682 }
683
Mathias Agopian65ab4712010-07-14 17:59:35 -0700684 // check calling permissions
685 if (!settingsAllowed()) {
686 return PERMISSION_DENIED;
687 }
688
689 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700690 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700691 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700692 ret = dev->set_mic_mute(dev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700693 mHardwareStatus = AUDIO_HW_IDLE;
694 return ret;
695}
696
697bool AudioFlinger::getMicMute() const
698{
Eric Laurenta1884f92011-08-23 08:25:03 -0700699 status_t ret = initCheck();
700 if (ret != NO_ERROR) {
701 return false;
702 }
703
Dima Zavinfce7a472011-04-19 22:30:36 -0700704 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800705 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700706 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700707 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700708 dev->get_mic_mute(dev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700709 mHardwareStatus = AUDIO_HW_IDLE;
710 return state;
711}
712
713status_t AudioFlinger::setMasterMute(bool muted)
714{
John Grossmand8f178d2012-07-20 14:51:35 -0700715 status_t ret = initCheck();
716 if (ret != NO_ERROR) {
717 return ret;
718 }
719
Mathias Agopian65ab4712010-07-14 17:59:35 -0700720 // check calling permissions
721 if (!settingsAllowed()) {
722 return PERMISSION_DENIED;
723 }
724
John Grossmanee578c02012-07-23 17:05:46 -0700725 Mutex::Autolock _l(mLock);
726 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700727
John Grossmanee578c02012-07-23 17:05:46 -0700728 // Set master mute in the HALs which support it.
Ricardo Cerqueira59199b12012-07-11 23:39:44 +0100729#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -0700730 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
731 AutoMutex lock(mHardwareLock);
732 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700733
John Grossmanee578c02012-07-23 17:05:46 -0700734 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
735 if (dev->canSetMasterMute()) {
736 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700737 }
John Grossmanee578c02012-07-23 17:05:46 -0700738 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700739 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +0100740#endif
John Grossmand8f178d2012-07-20 14:51:35 -0700741
John Grossmanee578c02012-07-23 17:05:46 -0700742 // Now set the master mute in each playback thread. Playback threads
743 // assigned to HALs which do not have master mute support will apply master
744 // mute during the mix operation. Threads with HALs which do support master
745 // mute will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800746 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700747 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700748
749 return NO_ERROR;
750}
751
752float AudioFlinger::masterVolume() const
753{
Glenn Kasten98067102011-12-13 11:47:54 -0800754 Mutex::Autolock _l(mLock);
755 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700756}
757
758bool AudioFlinger::masterMute() const
759{
Glenn Kasten98067102011-12-13 11:47:54 -0800760 Mutex::Autolock _l(mLock);
761 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700762}
763
John Grossman4ff14ba2012-02-08 16:37:41 -0800764float AudioFlinger::masterVolume_l() const
765{
John Grossman4ff14ba2012-02-08 16:37:41 -0800766 return mMasterVolume;
767}
768
John Grossmand8f178d2012-07-20 14:51:35 -0700769bool AudioFlinger::masterMute_l() const
770{
John Grossmanee578c02012-07-23 17:05:46 -0700771 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700772}
773
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800774status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
775 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700776{
777 // check calling permissions
778 if (!settingsAllowed()) {
779 return PERMISSION_DENIED;
780 }
781
Glenn Kasten263709e2012-01-06 08:40:01 -0800782 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000783 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700784 return BAD_VALUE;
785 }
786
787 AutoMutex lock(mLock);
788 PlaybackThread *thread = NULL;
789 if (output) {
790 thread = checkPlaybackThread_l(output);
791 if (thread == NULL) {
792 return BAD_VALUE;
793 }
794 }
795
796 mStreamTypes[stream].volume = value;
797
798 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800799 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700800 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700801 }
802 } else {
803 thread->setStreamVolume(stream, value);
804 }
805
806 return NO_ERROR;
807}
808
Glenn Kastenfff6d712012-01-12 16:38:12 -0800809status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810{
811 // check calling permissions
812 if (!settingsAllowed()) {
813 return PERMISSION_DENIED;
814 }
815
Glenn Kasten263709e2012-01-06 08:40:01 -0800816 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700817 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000818 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700819 return BAD_VALUE;
820 }
821
Eric Laurent93575202011-01-18 18:39:02 -0800822 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700823 mStreamTypes[stream].mute = muted;
824 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700825 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700826
827 return NO_ERROR;
828}
829
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800830float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700831{
Glenn Kasten263709e2012-01-06 08:40:01 -0800832 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833 return 0.0f;
834 }
835
836 AutoMutex lock(mLock);
837 float volume;
838 if (output) {
839 PlaybackThread *thread = checkPlaybackThread_l(output);
840 if (thread == NULL) {
841 return 0.0f;
842 }
843 volume = thread->streamVolume(stream);
844 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800845 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700846 }
847
848 return volume;
849}
850
Glenn Kastenfff6d712012-01-12 16:38:12 -0800851bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700852{
Glenn Kasten263709e2012-01-06 08:40:01 -0800853 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700854 return true;
855 }
856
Glenn Kasten6637baa2012-01-09 09:40:36 -0800857 AutoMutex lock(mLock);
858 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700859}
860
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800861status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700862{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800863 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700864 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
865 // check calling permissions
866 if (!settingsAllowed()) {
867 return PERMISSION_DENIED;
868 }
869
Mathias Agopian65ab4712010-07-14 17:59:35 -0700870 // ioHandle == 0 means the parameters are global to the audio hardware interface
871 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700872 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700873 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800874 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700875 AutoMutex lock(mHardwareLock);
876 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
877 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
878 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
879 status_t result = dev->set_parameters(dev, keyValuePairs.string());
880 final_result = result ?: final_result;
881 }
882 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800883 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700884 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
885 AudioParameter param = AudioParameter(keyValuePairs);
886 String8 value;
887 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700888 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
889 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700890 for (size_t i = 0; i < mRecordThreads.size(); i++) {
891 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -0700892 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -0700893 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
894 // collect all of the thread's session IDs
895 KeyedVector<int, bool> ids = thread->sessionIds();
896 // suspend effects associated with those session IDs
897 for (size_t j = 0; j < ids.size(); ++j) {
898 int sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700899 thread->setEffectSuspended(FX_IID_AEC,
900 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700901 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700902 thread->setEffectSuspended(FX_IID_NS,
903 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700904 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700905 }
906 }
Eric Laurentbee53372011-08-29 12:42:48 -0700907 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700908 }
909 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700910 String8 screenState;
911 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
912 bool isOff = screenState == "off";
913 if (isOff != (gScreenState & 1)) {
914 gScreenState = ((gScreenState & ~1) + 2) | isOff;
915 }
916 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700917 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700918 }
919
920 // hold a strong ref on thread in case closeOutput() or closeInput() is called
921 // and the thread is exited once the lock is released
922 sp<ThreadBase> thread;
923 {
924 Mutex::Autolock _l(mLock);
925 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -0700926 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700927 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800928 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700929 // indicate output device change to all input threads for pre processing
930 AudioParameter param = AudioParameter(keyValuePairs);
931 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700932 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
933 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700934 for (size_t i = 0; i < mRecordThreads.size(); i++) {
935 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
936 }
937 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700938 }
939 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800940 if (thread != 0) {
941 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700942 }
943 return BAD_VALUE;
944}
945
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800946String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700947{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800948// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700949// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
950
Eric Laurenta4c5a552012-03-29 10:12:40 -0700951 Mutex::Autolock _l(mLock);
952
Mathias Agopian65ab4712010-07-14 17:59:35 -0700953 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700954 String8 out_s8;
955
Dima Zavin799a70e2011-04-18 16:57:27 -0700956 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800957 char *s;
958 {
959 AutoMutex lock(mHardwareLock);
960 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700961 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800962 s = dev->get_parameters(dev, keys.string());
963 mHardwareStatus = AUDIO_HW_IDLE;
964 }
John Grossmanef7740b2012-02-09 11:28:36 -0800965 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700966 free(s);
967 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700968 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700969 }
970
Mathias Agopian65ab4712010-07-14 17:59:35 -0700971 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
972 if (playbackThread != NULL) {
973 return playbackThread->getParameters(keys);
974 }
975 RecordThread *recordThread = checkRecordThread_l(ioHandle);
976 if (recordThread != NULL) {
977 return recordThread->getParameters(keys);
978 }
979 return String8("");
980}
981
Glenn Kastendd8104c2012-07-02 12:42:44 -0700982size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
983 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700984{
Eric Laurenta1884f92011-08-23 08:25:03 -0700985 status_t ret = initCheck();
986 if (ret != NO_ERROR) {
987 return 0;
988 }
989
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800990 AutoMutex lock(mHardwareLock);
991 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700992 struct audio_config config = {
993 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -0700994 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700995 format: format,
996 };
John Grossmanee578c02012-07-23 17:05:46 -0700997 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Ricardo Cerqueira59199b12012-07-11 23:39:44 +0100998#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -0700999 size_t size = dev->get_input_buffer_size(dev, &config);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01001000#else
1001 size_t size = dev->get_input_buffer_size(dev, sampleRate, format, popcount(channelMask));
1002#endif
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001003 mHardwareStatus = AUDIO_HW_IDLE;
1004 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001005}
1006
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001007unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001008{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001009 Mutex::Autolock _l(mLock);
1010
1011 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1012 if (recordThread != NULL) {
1013 return recordThread->getInputFramesLost();
1014 }
1015 return 0;
1016}
1017
1018status_t AudioFlinger::setVoiceVolume(float value)
1019{
Eric Laurenta1884f92011-08-23 08:25:03 -07001020 status_t ret = initCheck();
1021 if (ret != NO_ERROR) {
1022 return ret;
1023 }
1024
Mathias Agopian65ab4712010-07-14 17:59:35 -07001025 // check calling permissions
1026 if (!settingsAllowed()) {
1027 return PERMISSION_DENIED;
1028 }
1029
1030 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001031 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001032 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001033 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001034 mHardwareStatus = AUDIO_HW_IDLE;
1035
1036 return ret;
1037}
1038
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001039status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1040 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001041{
1042 status_t status;
1043
1044 Mutex::Autolock _l(mLock);
1045
1046 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1047 if (playbackThread != NULL) {
1048 return playbackThread->getRenderPosition(halFrames, dspFrames);
1049 }
1050
1051 return BAD_VALUE;
1052}
1053
1054void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1055{
1056
1057 Mutex::Autolock _l(mLock);
1058
Glenn Kastenbb001922012-02-03 11:10:26 -08001059 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001060 if (mNotificationClients.indexOfKey(pid) < 0) {
1061 sp<NotificationClient> notificationClient = new NotificationClient(this,
1062 client,
1063 pid);
Steve Block3856b092011-10-20 11:56:00 +01001064 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001065
1066 mNotificationClients.add(pid, notificationClient);
1067
1068 sp<IBinder> binder = client->asBinder();
1069 binder->linkToDeath(notificationClient);
1070
1071 // the config change is always sent from playback or record threads to avoid deadlock
1072 // with AudioSystem::gLock
1073 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001074 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001075 }
1076
1077 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001078 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001079 }
1080 }
1081}
1082
1083void AudioFlinger::removeNotificationClient(pid_t pid)
1084{
1085 Mutex::Autolock _l(mLock);
1086
Glenn Kastena3b09252012-01-20 09:19:01 -08001087 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001088
Steve Block3856b092011-10-20 11:56:00 +01001089 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001090 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001091 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001092 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001093 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001094 ALOGV(" pid %d @ %d", ref->mPid, i);
1095 if (ref->mPid == pid) {
1096 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001097 mAudioSessionRefs.removeAt(i);
1098 delete ref;
1099 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001100 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001101 } else {
1102 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001103 }
1104 }
1105 if (removed) {
1106 purgeStaleEffects_l();
1107 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001108}
1109
1110// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001111void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001112{
1113 size_t size = mNotificationClients.size();
1114 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001115 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1116 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001117 }
1118}
1119
1120// removeClient_l() must be called with AudioFlinger::mLock held
1121void AudioFlinger::removeClient_l(pid_t pid)
1122{
Steve Block3856b092011-10-20 11:56:00 +01001123 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001124 mClients.removeItem(pid);
1125}
1126
Eric Laurent717e1282012-06-29 16:36:52 -07001127// getEffectThread_l() must be called with AudioFlinger::mLock held
1128sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1129{
1130 sp<PlaybackThread> thread;
1131
1132 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1133 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1134 ALOG_ASSERT(thread == 0);
1135 thread = mPlaybackThreads.valueAt(i);
1136 }
1137 }
1138
1139 return thread;
1140}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001141
1142// ----------------------------------------------------------------------------
1143
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001144AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurentf1c04f92012-08-28 14:26:53 -07001145 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001146 : Thread(false /*canCallJava*/),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001147 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001148 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001149 // mChannelMask
1150 mChannelCount(0),
1151 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1152 mParamStatus(NO_ERROR),
Eric Laurentf1c04f92012-08-28 14:26:53 -07001153 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
1154 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001155 // mName will be set by concrete (non-virtual) subclass
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001156 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001157{
1158}
1159
1160AudioFlinger::ThreadBase::~ThreadBase()
1161{
1162 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001163 // do not lock the mutex in destructor
1164 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001165 if (mPowerManager != 0) {
1166 sp<IBinder> binder = mPowerManager->asBinder();
1167 binder->unlinkToDeath(mDeathRecipient);
1168 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001169}
1170
1171void AudioFlinger::ThreadBase::exit()
1172{
Steve Block3856b092011-10-20 11:56:00 +01001173 ALOGV("ThreadBase::exit");
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07001174 // do any cleanup required for exit to succeed
1175 preExit();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001176 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001177 // This lock prevents the following race in thread (uniprocessor for illustration):
1178 // if (!exitPending()) {
1179 // // context switch from here to exit()
1180 // // exit() calls requestExit(), what exitPending() observes
1181 // // exit() calls signal(), which is dropped since no waiters
1182 // // context switch back from exit() to here
1183 // mWaitWorkCV.wait(...);
1184 // // now thread is hung
1185 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001186 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001187 requestExit();
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07001188 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001189 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001190 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1191 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001192 requestExitAndWait();
1193}
1194
Mathias Agopian65ab4712010-07-14 17:59:35 -07001195status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1196{
1197 status_t status;
1198
Steve Block3856b092011-10-20 11:56:00 +01001199 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001200 Mutex::Autolock _l(mLock);
1201
1202 mNewParameters.add(keyValuePairs);
1203 mWaitWorkCV.signal();
1204 // wait condition with timeout in case the thread loop has exited
1205 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001206 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001207 status = mParamStatus;
1208 mWaitWorkCV.signal();
1209 } else {
1210 status = TIMED_OUT;
1211 }
1212 return status;
1213}
1214
Eric Laurent896adcd2012-09-13 11:18:23 -07001215void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001216{
1217 Mutex::Autolock _l(mLock);
Eric Laurent896adcd2012-09-13 11:18:23 -07001218 sendIoConfigEvent_l(event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001219}
1220
Eric Laurent896adcd2012-09-13 11:18:23 -07001221// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
1222void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001223{
Eric Laurent896adcd2012-09-13 11:18:23 -07001224 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
1225 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
1226 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1227 mWaitWorkCV.signal();
1228}
1229
1230// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
1231void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
1232{
1233 PrioConfigEvent *prioEvent = new PrioConfigEvent(pid, tid, prio);
1234 mConfigEvents.add(static_cast<ConfigEvent *>(prioEvent));
1235 ALOGV("sendPrioConfigEvent_l() num events %d pid %d, tid %d prio %d",
1236 mConfigEvents.size(), pid, tid, prio);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001237 mWaitWorkCV.signal();
1238}
1239
1240void AudioFlinger::ThreadBase::processConfigEvents()
1241{
1242 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001243 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001244 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Eric Laurent896adcd2012-09-13 11:18:23 -07001245 ConfigEvent *event = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001246 mConfigEvents.removeAt(0);
1247 // release mLock before locking AudioFlinger mLock: lock order is always
1248 // AudioFlinger then ThreadBase to avoid cross deadlock
1249 mLock.unlock();
Eric Laurent896adcd2012-09-13 11:18:23 -07001250 switch(event->type()) {
1251 case CFG_EVENT_PRIO: {
1252 PrioConfigEvent *prioEvent = static_cast<PrioConfigEvent *>(event);
1253 int err = requestPriority(prioEvent->pid(), prioEvent->tid(), prioEvent->prio());
1254 if (err != 0) {
1255 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
1256 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
1257 }
1258 } break;
1259 case CFG_EVENT_IO: {
1260 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
1261 mAudioFlinger->mLock.lock();
1262 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
1263 mAudioFlinger->mLock.unlock();
1264 } break;
1265 default:
1266 ALOGE("processConfigEvents() unknown event type %d", event->type());
1267 break;
1268 }
1269 delete event;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001270 mLock.lock();
1271 }
1272 mLock.unlock();
1273}
1274
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001275void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001276{
1277 const size_t SIZE = 256;
1278 char buffer[SIZE];
1279 String8 result;
1280
1281 bool locked = tryLock(mLock);
1282 if (!locked) {
1283 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1284 write(fd, buffer, strlen(buffer));
1285 }
1286
Eric Laurent612bbb52012-03-14 15:03:26 -07001287 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1288 result.append(buffer);
1289 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1290 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001291 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1292 result.append(buffer);
1293 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1294 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001295 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1296 result.append(buffer);
1297 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001298 result.append(buffer);
1299 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1300 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001301 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1302 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001303 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1304 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001305 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001306 result.append(buffer);
1307
1308 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1309 result.append(buffer);
1310 result.append(" Index Command");
1311 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1312 snprintf(buffer, SIZE, "\n %02d ", i);
1313 result.append(buffer);
1314 result.append(mNewParameters[i]);
1315 }
1316
1317 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1318 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001319 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001320 mConfigEvents[i]->dump(buffer, SIZE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001321 result.append(buffer);
1322 }
1323 result.append("\n");
1324
1325 write(fd, result.string(), result.size());
1326
1327 if (locked) {
1328 mLock.unlock();
1329 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001330}
1331
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001332void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001333{
1334 const size_t SIZE = 256;
1335 char buffer[SIZE];
1336 String8 result;
1337
1338 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1339 write(fd, buffer, strlen(buffer));
1340
1341 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1342 sp<EffectChain> chain = mEffectChains[i];
1343 if (chain != 0) {
1344 chain->dump(fd, args);
1345 }
1346 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001347}
1348
Eric Laurentfeb0db62011-07-22 09:04:31 -07001349void AudioFlinger::ThreadBase::acquireWakeLock()
1350{
1351 Mutex::Autolock _l(mLock);
1352 acquireWakeLock_l();
1353}
1354
1355void AudioFlinger::ThreadBase::acquireWakeLock_l()
1356{
1357 if (mPowerManager == 0) {
1358 // use checkService() to avoid blocking if power service is not up yet
1359 sp<IBinder> binder =
1360 defaultServiceManager()->checkService(String16("power"));
1361 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001362 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001363 } else {
1364 mPowerManager = interface_cast<IPowerManager>(binder);
1365 binder->linkToDeath(mDeathRecipient);
1366 }
1367 }
1368 if (mPowerManager != 0) {
1369 sp<IBinder> binder = new BBinder();
1370 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1371 binder,
1372 String16(mName));
1373 if (status == NO_ERROR) {
1374 mWakeLockToken = binder;
1375 }
Steve Block3856b092011-10-20 11:56:00 +01001376 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001377 }
1378}
1379
1380void AudioFlinger::ThreadBase::releaseWakeLock()
1381{
1382 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001383 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001384}
1385
1386void AudioFlinger::ThreadBase::releaseWakeLock_l()
1387{
1388 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001389 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001390 if (mPowerManager != 0) {
1391 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1392 }
1393 mWakeLockToken.clear();
1394 }
1395}
1396
1397void AudioFlinger::ThreadBase::clearPowerManager()
1398{
1399 Mutex::Autolock _l(mLock);
1400 releaseWakeLock_l();
1401 mPowerManager.clear();
1402}
1403
1404void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1405{
1406 sp<ThreadBase> thread = mThread.promote();
1407 if (thread != 0) {
1408 thread->clearPowerManager();
1409 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001410 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001411}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001412
Eric Laurent59255e42011-07-27 19:49:51 -07001413void AudioFlinger::ThreadBase::setEffectSuspended(
1414 const effect_uuid_t *type, bool suspend, int sessionId)
1415{
1416 Mutex::Autolock _l(mLock);
1417 setEffectSuspended_l(type, suspend, sessionId);
1418}
1419
1420void AudioFlinger::ThreadBase::setEffectSuspended_l(
1421 const effect_uuid_t *type, bool suspend, int sessionId)
1422{
Glenn Kasten090f0192012-01-30 13:00:02 -08001423 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001424 if (chain != 0) {
1425 if (type != NULL) {
1426 chain->setEffectSuspended_l(type, suspend);
1427 } else {
1428 chain->setEffectSuspendedAll_l(suspend);
1429 }
1430 }
1431
1432 updateSuspendedSessions_l(type, suspend, sessionId);
1433}
1434
1435void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1436{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001437 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001438 if (index < 0) {
1439 return;
1440 }
1441
Glenn Kasten0a7af182012-07-09 16:09:19 -07001442 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1443 mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001444
1445 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001446 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001447 for (int j = 0; j < desc->mRefCount; j++) {
1448 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1449 chain->setEffectSuspendedAll_l(true);
1450 } else {
Steve Block3856b092011-10-20 11:56:00 +01001451 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001452 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001453 chain->setEffectSuspended_l(&desc->mType, true);
1454 }
1455 }
1456 }
1457}
1458
Eric Laurent59255e42011-07-27 19:49:51 -07001459void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1460 bool suspend,
1461 int sessionId)
1462{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001463 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001464
1465 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1466
1467 if (suspend) {
1468 if (index >= 0) {
Glenn Kasten0a7af182012-07-09 16:09:19 -07001469 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001470 } else {
1471 mSuspendedSessions.add(sessionId, sessionEffects);
1472 }
1473 } else {
1474 if (index < 0) {
1475 return;
1476 }
Glenn Kasten0a7af182012-07-09 16:09:19 -07001477 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001478 }
1479
1480
1481 int key = EffectChain::kKeyForSuspendAll;
1482 if (type != NULL) {
1483 key = type->timeLow;
1484 }
1485 index = sessionEffects.indexOfKey(key);
1486
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001487 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001488 if (suspend) {
1489 if (index >= 0) {
1490 desc = sessionEffects.valueAt(index);
1491 } else {
1492 desc = new SuspendedSessionDesc();
1493 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001494 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001495 }
1496 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001497 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001498 }
1499 desc->mRefCount++;
1500 } else {
1501 if (index < 0) {
1502 return;
1503 }
1504 desc = sessionEffects.valueAt(index);
1505 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001506 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001507 sessionEffects.removeItemsAt(index);
1508 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001509 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001510 sessionId);
1511 mSuspendedSessions.removeItem(sessionId);
1512 }
1513 }
1514 }
1515 if (!sessionEffects.isEmpty()) {
1516 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1517 }
1518}
1519
1520void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1521 bool enabled,
1522 int sessionId)
1523{
1524 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001525 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1526}
Eric Laurent59255e42011-07-27 19:49:51 -07001527
Eric Laurenta85a74a2011-10-19 11:44:54 -07001528void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1529 bool enabled,
1530 int sessionId)
1531{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001532 if (mType != RECORD) {
1533 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1534 // another session. This gives the priority to well behaved effect control panels
1535 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001536 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1537 // global effects
1538 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001539 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1540 }
1541 }
Eric Laurent59255e42011-07-27 19:49:51 -07001542
1543 sp<EffectChain> chain = getEffectChain_l(sessionId);
1544 if (chain != 0) {
1545 chain->checkSuspendOnEffectEnabled(effect, enabled);
1546 }
1547}
1548
Mathias Agopian65ab4712010-07-14 17:59:35 -07001549// ----------------------------------------------------------------------------
1550
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001551AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1552 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001553 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001554 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001555 type_t type)
Eric Laurentf1c04f92012-08-28 14:26:53 -07001556 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001557 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001558 // mStreamTypes[] initialized in constructor body
1559 mOutput(output),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001560 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001561 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001562 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001563 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001564 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001565 // index 0 is reserved for normal mixer's submix
1566 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001567{
Glenn Kasten480b4682012-02-28 12:30:08 -08001568 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001569
John Grossmanee578c02012-07-23 17:05:46 -07001570 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1571 // it would be safer to explicitly pass initial masterVolume/masterMute as
1572 // parameter.
1573 //
1574 // If the HAL we are using has support for master volume or master mute,
1575 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1576 // and the mute set to false).
1577 mMasterVolume = audioFlinger->masterVolume_l();
1578 mMasterMute = audioFlinger->masterMute_l();
1579 if (mOutput && mOutput->audioHwDev) {
1580 if (mOutput->audioHwDev->canSetMasterVolume()) {
1581 mMasterVolume = 1.0;
1582 }
1583
1584 if (mOutput->audioHwDev->canSetMasterMute()) {
1585 mMasterMute = false;
1586 }
1587 }
1588
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589 readOutputParameters();
1590
Glenn Kasten263709e2012-01-06 08:40:01 -08001591 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001592 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1593 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1594 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001595 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1596 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001597 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001598 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1599 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600}
1601
1602AudioFlinger::PlaybackThread::~PlaybackThread()
1603{
1604 delete [] mMixBuffer;
1605}
1606
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001607void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001608{
1609 dumpInternals(fd, args);
1610 dumpTracks(fd, args);
1611 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612}
1613
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001614void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001615{
1616 const size_t SIZE = 256;
1617 char buffer[SIZE];
1618 String8 result;
1619
Glenn Kasten58912562012-04-03 10:45:00 -07001620 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1621 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1622 const stream_type_t *st = &mStreamTypes[i];
1623 if (i > 0) {
1624 result.appendFormat(", ");
1625 }
1626 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1627 if (st->mute) {
1628 result.append("M");
1629 }
1630 }
1631 result.append("\n");
1632 write(fd, result.string(), result.length());
1633 result.clear();
1634
Mathias Agopian65ab4712010-07-14 17:59:35 -07001635 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1636 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001637 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001638 for (size_t i = 0; i < mTracks.size(); ++i) {
1639 sp<Track> track = mTracks[i];
1640 if (track != 0) {
1641 track->dump(buffer, SIZE);
1642 result.append(buffer);
1643 }
1644 }
1645
1646 snprintf(buffer, SIZE, "Output thread %p active 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 < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001650 sp<Track> track = mActiveTracks[i].promote();
1651 if (track != 0) {
1652 track->dump(buffer, SIZE);
1653 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001654 }
1655 }
1656 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001657
1658 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1659 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1660 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1661 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001662}
1663
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001664void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001665{
1666 const size_t SIZE = 256;
1667 char buffer[SIZE];
1668 String8 result;
1669
1670 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1671 result.append(buffer);
1672 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1673 result.append(buffer);
1674 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1675 result.append(buffer);
1676 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1677 result.append(buffer);
1678 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1679 result.append(buffer);
1680 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1681 result.append(buffer);
1682 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1683 result.append(buffer);
1684 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001685 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001686
1687 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001688}
1689
1690// Thread virtuals
1691status_t AudioFlinger::PlaybackThread::readyToRun()
1692{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001693 status_t status = initCheck();
1694 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001695 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001696 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001697 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001699 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001700}
1701
1702void AudioFlinger::PlaybackThread::onFirstRef()
1703{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001704 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001705}
1706
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07001707// ThreadBase virtuals
1708void AudioFlinger::PlaybackThread::preExit()
1709{
1710 ALOGV(" preExit()");
1711 // FIXME this is using hard-coded strings but in the future, this functionality will be
1712 // converted to use audio HAL extensions required to support tunneling
1713 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1714}
1715
Mathias Agopian65ab4712010-07-14 17:59:35 -07001716// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001717sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001718 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001719 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001720 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001721 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001722 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001723 int frameCount,
1724 const sp<IMemory>& sharedBuffer,
1725 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001726 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001727 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728 status_t *status)
1729{
1730 sp<Track> track;
1731 status_t lStatus;
1732
Glenn Kasten73d22752012-03-19 13:38:30 -07001733 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1734
1735 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001736 if (flags & IAudioFlinger::TRACK_FAST) {
1737 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001738 // not timed
1739 (!isTimed) &&
1740 // either of these use cases:
1741 (
1742 // use case 1: shared buffer with any frame count
1743 (
1744 (sharedBuffer != 0)
1745 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001746 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001747 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001748 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001749 ((frameCount == 0) ||
Glenn Kasten3ed29202012-08-07 15:24:44 -07001750 (frameCount >= (int) (mFrameCount * kFastTrackMultiplier)))
Glenn Kasten73d22752012-03-19 13:38:30 -07001751 )
1752 ) &&
1753 // PCM data
1754 audio_is_linear_pcm(format) &&
1755 // mono or stereo
1756 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1757 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001758#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001759 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001760 (sampleRate == mSampleRate) &&
1761#endif
1762 // normal mixer has an associated fast mixer
1763 hasFastMixer() &&
1764 // there are sufficient fast track slots available
1765 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001766 // FIXME test that MixerThread for this fast track has a capable output HAL
1767 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001768 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001769 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1770 if (frameCount == 0) {
Glenn Kasten3ed29202012-08-07 15:24:44 -07001771 frameCount = mFrameCount * kFastTrackMultiplier;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001772 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001773 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001774 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001775 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001776 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07001777 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001778 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1779 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1780 audio_is_linear_pcm(format),
1781 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001782 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001783 // For compatibility with AudioTrack calculation, buffer depth is forced
1784 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1785 // This is probably too conservative, but legacy application code may depend on it.
1786 // If you change this calculation, also review the start threshold which is related.
1787 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1788 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1789 if (minBufCount < 2) {
1790 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001791 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001792 int minFrameCount = mNormalFrameCount * minBufCount;
1793 if (frameCount < minFrameCount) {
1794 frameCount = minFrameCount;
1795 }
1796 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001797 }
1798
Mathias Agopian65ab4712010-07-14 17:59:35 -07001799 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001800 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1801 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001802 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001803 "for output %p with format %d",
1804 sampleRate, format, channelMask, mOutput, mFormat);
1805 lStatus = BAD_VALUE;
1806 goto Exit;
1807 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001808 }
1809 } else {
1810 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1811 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001812 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001813 lStatus = BAD_VALUE;
1814 goto Exit;
1815 }
1816 }
1817
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001818 lStatus = initCheck();
1819 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001820 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001821 goto Exit;
1822 }
1823
1824 { // scope for mLock
1825 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001826
1827 // all tracks in same audio session must share the same routing strategy otherwise
1828 // conflicts will happen when tracks are moved from one output to another by audio policy
1829 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001830 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001831 for (size_t i = 0; i < mTracks.size(); ++i) {
1832 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001833 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001834 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001835 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001836 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001837 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001838 lStatus = BAD_VALUE;
1839 goto Exit;
1840 }
1841 }
1842 }
1843
John Grossman4ff14ba2012-02-08 16:37:41 -08001844 if (!isTimed) {
1845 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001846 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001847 } else {
1848 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1849 channelMask, frameCount, sharedBuffer, sessionId);
1850 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001851 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001852 lStatus = NO_MEMORY;
1853 goto Exit;
1854 }
1855 mTracks.add(track);
1856
1857 sp<EffectChain> chain = getEffectChain_l(sessionId);
1858 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001859 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001860 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001861 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001862 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001864
Eric Laurent896adcd2012-09-13 11:18:23 -07001865 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1866 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1867 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1868 // so ask activity manager to do this on our behalf
1869 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001870 }
1871 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001872
Mathias Agopian65ab4712010-07-14 17:59:35 -07001873 lStatus = NO_ERROR;
1874
1875Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001876 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001877 *status = lStatus;
1878 }
1879 return track;
1880}
1881
Eric Laurente737cda2012-05-22 18:55:44 -07001882uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1883{
1884 if (mFastMixer != NULL) {
1885 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1886 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1887 }
1888 return latency;
1889}
1890
1891uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1892{
1893 return latency;
1894}
1895
Mathias Agopian65ab4712010-07-14 17:59:35 -07001896uint32_t AudioFlinger::PlaybackThread::latency() const
1897{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001898 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001899 return latency_l();
1900}
1901uint32_t AudioFlinger::PlaybackThread::latency_l() const
1902{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001903 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001904 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001905 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001906 return 0;
1907 }
1908}
1909
Glenn Kasten6637baa2012-01-09 09:40:36 -08001910void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001911{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001912 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001913 // Don't apply master volume in SW if our HAL can do it for us.
1914 if (mOutput && mOutput->audioHwDev &&
1915 mOutput->audioHwDev->canSetMasterVolume()) {
1916 mMasterVolume = 1.0;
1917 } else {
1918 mMasterVolume = value;
1919 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001920}
1921
Glenn Kasten6637baa2012-01-09 09:40:36 -08001922void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
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 mute in SW if our HAL can do it for us.
1926 if (mOutput && mOutput->audioHwDev &&
1927 mOutput->audioHwDev->canSetMasterMute()) {
1928 mMasterMute = false;
1929 } else {
1930 mMasterMute = muted;
1931 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932}
1933
Glenn Kasten6637baa2012-01-09 09:40:36 -08001934void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001935{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001936 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001937 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001938}
1939
Glenn Kasten6637baa2012-01-09 09:40:36 -08001940void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001941{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001942 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001943 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001944}
1945
Glenn Kastenfff6d712012-01-12 16:38:12 -08001946float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
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 return mStreamTypes[stream].volume;
1950}
1951
Mathias Agopian65ab4712010-07-14 17:59:35 -07001952// addTrack_l() must be called with ThreadBase::mLock held
1953status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1954{
1955 status_t status = ALREADY_EXISTS;
1956
1957 // set retry count for buffer fill
1958 track->mRetryCount = kMaxTrackStartupRetries;
1959 if (mActiveTracks.indexOf(track) < 0) {
1960 // the track is newly added, make sure it fills up all its
1961 // buffers before playing. This is to ensure the client will
1962 // effectively get the latency it requested.
1963 track->mFillingUpStatus = Track::FS_FILLING;
1964 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001965 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001966 mActiveTracks.add(track);
1967 if (track->mainBuffer() != mMixBuffer) {
1968 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1969 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001970 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001971 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972 }
1973 }
1974
1975 status = NO_ERROR;
1976 }
1977
Steve Block3856b092011-10-20 11:56:00 +01001978 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001979 mWaitWorkCV.broadcast();
1980
1981 return status;
1982}
1983
1984// destroyTrack_l() must be called with ThreadBase::mLock held
1985void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1986{
1987 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001988 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001989 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001990 removeTrack_l(track);
1991 }
1992}
1993
1994void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1995{
Eric Laurent29864602012-05-08 18:57:51 -07001996 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001997 mTracks.remove(track);
1998 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001999 // redundant as track is about to be destroyed, for dumpsys only
2000 track->mName = -1;
2001 if (track->isFastTrack()) {
2002 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07002003 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07002004 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2005 mFastTrackAvailMask |= 1 << index;
2006 // redundant as track is about to be destroyed, for dumpsys only
2007 track->mFastIndex = -1;
2008 }
Eric Laurentb469b942011-05-09 12:09:06 -07002009 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2010 if (chain != 0) {
2011 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002012 }
2013}
2014
2015String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2016{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002017 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07002018 char *s;
2019
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002020 Mutex::Autolock _l(mLock);
2021 if (initCheck() != NO_ERROR) {
2022 return out_s8;
2023 }
2024
Dima Zavin799a70e2011-04-18 16:57:27 -07002025 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07002026 out_s8 = String8(s);
2027 free(s);
2028 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002029}
2030
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002031// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
2033 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08002034 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002035
Steve Block3856b092011-10-20 11:56:00 +01002036 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037
2038 switch (event) {
2039 case AudioSystem::OUTPUT_OPENED:
2040 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002041 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002042 desc.samplingRate = mSampleRate;
2043 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07002044 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002045 desc.latency = latency();
2046 param2 = &desc;
2047 break;
2048
2049 case AudioSystem::STREAM_CONFIG_CHANGED:
2050 param2 = &param;
2051 case AudioSystem::OUTPUT_CLOSED:
2052 default:
2053 break;
2054 }
2055 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2056}
2057
2058void AudioFlinger::PlaybackThread::readOutputParameters()
2059{
Dima Zavin799a70e2011-04-18 16:57:27 -07002060 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002061 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2062 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07002063 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002064 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002065 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002066 if (mFrameCount & 15) {
2067 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2068 mFrameCount);
2069 }
2070
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002071 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002072 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002073 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002074 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002075 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2076 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2077 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2078 maxNormalFrameCount = maxNormalFrameCount & ~15;
2079 if (maxNormalFrameCount < minNormalFrameCount) {
2080 maxNormalFrameCount = minNormalFrameCount;
2081 }
2082 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2083 if (multiplier <= 1.0) {
2084 multiplier = 1.0;
2085 } else if (multiplier <= 2.0) {
2086 if (2 * mFrameCount <= maxNormalFrameCount) {
2087 multiplier = 2.0;
2088 } else {
2089 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2090 }
2091 } else {
2092 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2093 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2094 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2095 // FIXME this rounding up should not be done if no HAL SRC
2096 uint32_t truncMult = (uint32_t) multiplier;
2097 if ((truncMult & 1)) {
2098 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2099 ++truncMult;
2100 }
2101 }
2102 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002103 }
Glenn Kasten58912562012-04-03 10:45:00 -07002104 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002105 mNormalFrameCount = multiplier * mFrameCount;
2106 // round up to nearest 16 frames to satisfy AudioMixer
2107 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002108 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002109
Glenn Kastene9dd0172012-01-27 18:08:45 -08002110 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002111 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2112 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002113
Eric Laurentde070132010-07-13 04:45:46 -07002114 // force reconfiguration of effect chains and engines to take new buffer size and audio
2115 // parameters into account
2116 // Note that mLock is not held when readOutputParameters() is called from the constructor
2117 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2118 // matter.
2119 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2120 Vector< sp<EffectChain> > effectChains = mEffectChains;
2121 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002122 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002123 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002124}
2125
Eric Laurente737cda2012-05-22 18:55:44 -07002126
Mathias Agopian65ab4712010-07-14 17:59:35 -07002127status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2128{
Glenn Kastena0d68332012-01-27 16:47:15 -08002129 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002130 return BAD_VALUE;
2131 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002132 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002133 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002134 return INVALID_OPERATION;
2135 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002136 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002137
Eric Laurent1afc26d2012-09-23 15:20:50 -07002138 if (isSuspended()) {
2139 // return an estimation of rendered frames when the output is suspended
2140 int32_t frames = mBytesWritten - latency_l();
2141 if (frames < 0) {
2142 frames = 0;
2143 }
2144 *dspFrames = (uint32_t)frames;
2145 return NO_ERROR;
2146 } else {
2147 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
2148 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002149}
2150
Glenn Kasten106e8a42012-08-02 13:37:12 -07002151uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002152{
2153 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002154 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002155 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002156 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002157 }
2158
2159 for (size_t i = 0; i < mTracks.size(); ++i) {
2160 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002161 if (sessionId == track->sessionId() &&
2162 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002163 result |= TRACK_SESSION;
2164 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002165 }
2166 }
2167
Eric Laurent39e94f82010-07-28 01:32:47 -07002168 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002169}
2170
Eric Laurentde070132010-07-13 04:45:46 -07002171uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2172{
Dima Zavinfce7a472011-04-19 22:30:36 -07002173 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002174 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002175 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2176 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002177 }
2178 for (size_t i = 0; i < mTracks.size(); i++) {
2179 sp<Track> track = mTracks[i];
2180 if (sessionId == track->sessionId() &&
2181 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002182 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002183 }
2184 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002185 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002186}
2187
Mathias Agopian65ab4712010-07-14 17:59:35 -07002188
Glenn Kastenaed850d2012-01-26 09:46:34 -08002189AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002190{
2191 Mutex::Autolock _l(mLock);
2192 return mOutput;
2193}
2194
2195AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2196{
2197 Mutex::Autolock _l(mLock);
2198 AudioStreamOut *output = mOutput;
2199 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002200 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2201 // must push a NULL and wait for ack
2202 mOutputSink.clear();
2203 mPipeSink.clear();
2204 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002205 return output;
2206}
2207
2208// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002209audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002210{
2211 if (mOutput == NULL) {
2212 return NULL;
2213 }
2214 return &mOutput->stream->common;
2215}
2216
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002217uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002218{
Eric Laurentab9071b2012-06-04 13:45:29 -07002219 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002220}
2221
Eric Laurenta011e352012-03-29 15:51:43 -07002222status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2223{
2224 if (!isValidSyncEvent(event)) {
2225 return BAD_VALUE;
2226 }
2227
2228 Mutex::Autolock _l(mLock);
2229
2230 for (size_t i = 0; i < mTracks.size(); ++i) {
2231 sp<Track> track = mTracks[i];
2232 if (event->triggerSession() == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07002233 (void) track->setSyncEvent(event);
Eric Laurenta011e352012-03-29 15:51:43 -07002234 return NO_ERROR;
2235 }
2236 }
2237
2238 return NAME_NOT_FOUND;
2239}
2240
Glenn Kasten106e8a42012-08-02 13:37:12 -07002241bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07002242{
Glenn Kasten0dbb3562012-08-02 16:36:50 -07002243 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
Eric Laurenta011e352012-03-29 15:51:43 -07002244}
2245
Eric Laurent44a957f2012-05-15 15:26:05 -07002246void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2247{
2248 size_t count = tracksToRemove.size();
2249 if (CC_UNLIKELY(count)) {
2250 for (size_t i = 0 ; i < count ; i++) {
2251 const sp<Track>& track = tracksToRemove.itemAt(i);
2252 if ((track->sharedBuffer() != 0) &&
2253 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2254 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2255 }
2256 }
2257 }
2258
2259}
2260
Mathias Agopian65ab4712010-07-14 17:59:35 -07002261// ----------------------------------------------------------------------------
2262
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002263AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002264 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002265 : PlaybackThread(audioFlinger, output, id, device, type),
2266 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002267 // mFastMixer below
2268 mFastMixerFutex(0)
2269 // mOutputSink below
2270 // mPipeSink below
2271 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002272{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002273 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002274 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002275 "mFrameCount=%d, mNormalFrameCount=%d",
2276 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2277 mNormalFrameCount);
2278 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2279
Mathias Agopian65ab4712010-07-14 17:59:35 -07002280 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002281 if (mChannelCount != FCC_2) {
2282 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002283 }
Glenn Kasten58912562012-04-03 10:45:00 -07002284
2285 // create an NBAIO sink for the HAL output stream, and negotiate
2286 mOutputSink = new AudioStreamOutSink(output->stream);
2287 size_t numCounterOffers = 0;
2288 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2289 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2290 ALOG_ASSERT(index == 0);
2291
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002292 // initialize fast mixer depending on configuration
2293 bool initFastMixer;
2294 switch (kUseFastMixer) {
2295 case FastMixer_Never:
2296 initFastMixer = false;
2297 break;
2298 case FastMixer_Always:
2299 initFastMixer = true;
2300 break;
2301 case FastMixer_Static:
2302 case FastMixer_Dynamic:
2303 initFastMixer = mFrameCount < mNormalFrameCount;
2304 break;
2305 }
2306 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002307
2308 // create a MonoPipe to connect our submix to FastMixer
2309 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002310 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2311 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2312 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2313 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002314 const NBAIO_Format offers[1] = {format};
2315 size_t numCounterOffers = 0;
2316 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2317 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002318 monoPipe->setAvgFrames((mScreenState & 1) ?
2319 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002320 mPipeSink = monoPipe;
2321
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002322#ifdef TEE_SINK_FRAMES
2323 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2324 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2325 numCounterOffers = 0;
2326 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2327 ALOG_ASSERT(index == 0);
2328 mTeeSink = teeSink;
2329 PipeReader *teeSource = new PipeReader(*teeSink);
2330 numCounterOffers = 0;
2331 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2332 ALOG_ASSERT(index == 0);
2333 mTeeSource = teeSource;
2334#endif
2335
Glenn Kasten58912562012-04-03 10:45:00 -07002336 // create fast mixer and configure it initially with just one fast track for our submix
2337 mFastMixer = new FastMixer();
2338 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002339#ifdef STATE_QUEUE_DUMP
2340 sq->setObserverDump(&mStateQueueObserverDump);
2341 sq->setMutatorDump(&mStateQueueMutatorDump);
2342#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002343 FastMixerState *state = sq->begin();
2344 FastTrack *fastTrack = &state->mFastTracks[0];
2345 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2346 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2347 fastTrack->mVolumeProvider = NULL;
2348 fastTrack->mGeneration++;
2349 state->mFastTracksGen++;
2350 state->mTrackMask = 1;
2351 // fast mixer will use the HAL output sink
2352 state->mOutputSink = mOutputSink.get();
2353 state->mOutputSinkGen++;
2354 state->mFrameCount = mFrameCount;
2355 state->mCommand = FastMixerState::COLD_IDLE;
2356 // already done in constructor initialization list
2357 //mFastMixerFutex = 0;
2358 state->mColdFutexAddr = &mFastMixerFutex;
2359 state->mColdGen++;
2360 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002361 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002362 sq->end();
2363 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2364
2365 // start the fast mixer
2366 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002367 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002368 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002369 if (err != 0) {
2370 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002371 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002372 }
Glenn Kasten58912562012-04-03 10:45:00 -07002373
Glenn Kastenc15d6652012-05-30 14:52:57 -07002374#ifdef AUDIO_WATCHDOG
2375 // create and start the watchdog
2376 mAudioWatchdog = new AudioWatchdog();
2377 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2378 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2379 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002380 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002381 if (err != 0) {
2382 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002383 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002384 }
2385#endif
2386
Glenn Kasten58912562012-04-03 10:45:00 -07002387 } else {
2388 mFastMixer = NULL;
2389 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002390
2391 switch (kUseFastMixer) {
2392 case FastMixer_Never:
2393 case FastMixer_Dynamic:
2394 mNormalSink = mOutputSink;
2395 break;
2396 case FastMixer_Always:
2397 mNormalSink = mPipeSink;
2398 break;
2399 case FastMixer_Static:
2400 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2401 break;
2402 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002403}
2404
2405AudioFlinger::MixerThread::~MixerThread()
2406{
Glenn Kasten58912562012-04-03 10:45:00 -07002407 if (mFastMixer != NULL) {
2408 FastMixerStateQueue *sq = mFastMixer->sq();
2409 FastMixerState *state = sq->begin();
2410 if (state->mCommand == FastMixerState::COLD_IDLE) {
2411 int32_t old = android_atomic_inc(&mFastMixerFutex);
2412 if (old == -1) {
2413 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2414 }
2415 }
2416 state->mCommand = FastMixerState::EXIT;
2417 sq->end();
2418 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2419 mFastMixer->join();
2420 // Though the fast mixer thread has exited, it's state queue is still valid.
2421 // We'll use that extract the final state which contains one remaining fast track
2422 // corresponding to our sub-mix.
2423 state = sq->begin();
2424 ALOG_ASSERT(state->mTrackMask == 1);
2425 FastTrack *fastTrack = &state->mFastTracks[0];
2426 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2427 delete fastTrack->mBufferProvider;
2428 sq->end(false /*didModify*/);
2429 delete mFastMixer;
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002430#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002431 if (mAudioWatchdog != 0) {
2432 mAudioWatchdog->requestExit();
2433 mAudioWatchdog->requestExitAndWait();
2434 mAudioWatchdog.clear();
2435 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002436#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002437 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002438 delete mAudioMixer;
2439}
2440
Glenn Kasten83efdd02012-02-24 07:21:32 -08002441class CpuStats {
2442public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002443 CpuStats();
2444 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002445#ifdef DEBUG_CPU_USAGE
2446private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002447 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2448 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2449
2450 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2451
2452 int mCpuNum; // thread's current CPU number
2453 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002454#endif
2455};
2456
Glenn Kasten190a46f2012-03-06 11:27:10 -08002457CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002458#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002459 : mCpuNum(-1), mCpukHz(-1)
2460#endif
2461{
2462}
2463
2464void CpuStats::sample(const String8 &title) {
2465#ifdef DEBUG_CPU_USAGE
2466 // get current thread's delta CPU time in wall clock ns
2467 double wcNs;
2468 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2469
2470 // record sample for wall clock statistics
2471 if (valid) {
2472 mWcStats.sample(wcNs);
2473 }
2474
2475 // get the current CPU number
2476 int cpuNum = sched_getcpu();
2477
2478 // get the current CPU frequency in kHz
2479 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2480
2481 // check if either CPU number or frequency changed
2482 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2483 mCpuNum = cpuNum;
2484 mCpukHz = cpukHz;
2485 // ignore sample for purposes of cycles
2486 valid = false;
2487 }
2488
2489 // if no change in CPU number or frequency, then record sample for cycle statistics
2490 if (valid && mCpukHz > 0) {
2491 double cycles = wcNs * cpukHz * 0.000001;
2492 mHzStats.sample(cycles);
2493 }
2494
2495 unsigned n = mWcStats.n();
2496 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002497 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002498 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002499 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2500 double perLoop = elapsed / (double) n;
2501 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002502 double perLoop1k = perLoop * 0.001;
2503 double mean = mWcStats.mean();
2504 double stddev = mWcStats.stddev();
2505 double minimum = mWcStats.minimum();
2506 double maximum = mWcStats.maximum();
2507 double meanCycles = mHzStats.mean();
2508 double stddevCycles = mHzStats.stddev();
2509 double minCycles = mHzStats.minimum();
2510 double maxCycles = mHzStats.maximum();
2511 mCpuUsage.resetElapsed();
2512 mWcStats.reset();
2513 mHzStats.reset();
2514 ALOGD("CPU usage for %s over past %.1f secs\n"
2515 " (%u mixer loops at %.1f mean ms per loop):\n"
2516 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2517 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2518 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2519 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002520 elapsed * .000000001, n, perLoop * .000001,
2521 mean * .001,
2522 stddev * .001,
2523 minimum * .001,
2524 maximum * .001,
2525 mean / perLoop100,
2526 stddev / perLoop100,
2527 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002528 maximum / perLoop100,
2529 meanCycles / perLoop1k,
2530 stddevCycles / perLoop1k,
2531 minCycles / perLoop1k,
2532 maxCycles / perLoop1k);
2533
Glenn Kasten83efdd02012-02-24 07:21:32 -08002534 }
2535 }
2536#endif
2537};
2538
Glenn Kasten37d825e2012-02-24 07:21:48 -08002539void AudioFlinger::PlaybackThread::checkSilentMode_l()
2540{
2541 if (!mMasterMute) {
2542 char value[PROPERTY_VALUE_MAX];
2543 if (property_get("ro.audio.silent", value, "0") > 0) {
2544 char *endptr;
2545 unsigned long ul = strtoul(value, &endptr, 0);
2546 if (*endptr == '\0' && ul != 0) {
2547 ALOGD("Silence is golden");
2548 // The setprop command will not allow a property to be changed after
2549 // the first time it is set, so we don't have to worry about un-muting.
2550 setMasterMute_l(true);
2551 }
2552 }
2553 }
2554}
2555
Glenn Kasten000f0e32012-03-01 17:10:56 -08002556bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002557{
2558 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002559
Glenn Kasten000f0e32012-03-01 17:10:56 -08002560 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002561
2562 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002563 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002564
Glenn Kasten000f0e32012-03-01 17:10:56 -08002565 // DUPLICATING
2566 // FIXME could this be made local to while loop?
2567 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002568
Glenn Kasten66fcab92012-02-24 14:59:21 -08002569 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002570 sleepTime = idleSleepTime;
2571
Glenn Kasten9f34a362012-03-20 16:46:41 -07002572 if (mType == MIXER) {
2573 sleepTimeShift = 0;
2574 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002575
Glenn Kasten83efdd02012-02-24 07:21:32 -08002576 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002577 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002578
Eric Laurentfeb0db62011-07-22 09:04:31 -07002579 acquireWakeLock();
2580
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581 while (!exitPending())
2582 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002583 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002584
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002585 Vector< sp<EffectChain> > effectChains;
2586
Mathias Agopian65ab4712010-07-14 17:59:35 -07002587 processConfigEvents();
2588
Mathias Agopian65ab4712010-07-14 17:59:35 -07002589 { // scope for mLock
2590
2591 Mutex::Autolock _l(mLock);
2592
2593 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002594 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002595 }
2596
Glenn Kastenfa26a852012-03-06 11:28:04 -08002597 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002598
Mathias Agopian65ab4712010-07-14 17:59:35 -07002599 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002600 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002601 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002602 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002603
2604 threadLoop_standby();
2605
Mathias Agopian65ab4712010-07-14 17:59:35 -07002606 mStandby = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002607 }
2608
Glenn Kasten3e074702012-02-28 18:40:35 -08002609 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002610 // we're about to wait, flush the binder command buffer
2611 IPCThreadState::self()->flushCommands();
2612
Glenn Kastenfa26a852012-03-06 11:28:04 -08002613 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002614
Mathias Agopian65ab4712010-07-14 17:59:35 -07002615 if (exitPending()) break;
2616
Eric Laurentfeb0db62011-07-22 09:04:31 -07002617 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002618 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002619 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002620 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002621 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002622 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002623
Eric Laurentda747442012-04-25 18:53:13 -07002624 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002625 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Eric Laurent1afc26d2012-09-23 15:20:50 -07002626 mBytesWritten = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002627
Glenn Kasten37d825e2012-02-24 07:21:48 -08002628 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002629
Glenn Kasten000f0e32012-03-01 17:10:56 -08002630 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002631 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002632 if (mType == MIXER) {
2633 sleepTimeShift = 0;
2634 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002635
Mathias Agopian65ab4712010-07-14 17:59:35 -07002636 continue;
2637 }
2638 }
2639
Glenn Kasten81028042012-04-30 18:15:12 -07002640 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002641 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002642
2643 // prevent any changes in effect chain list and in each effect chain
2644 // during mixing and effect process as the audio buffers could be deleted
2645 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002646 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002647 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002648
Glenn Kastenfec279f2012-03-08 07:47:15 -08002649 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002650 threadLoop_mix();
2651 } else {
2652 threadLoop_sleepTime();
2653 }
2654
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002655 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002656 sleepTime = suspendSleepTimeUs();
Eric Laurent1afc26d2012-09-23 15:20:50 -07002657 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002658 }
2659
2660 // only process effects if we're going to write
2661 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002662 for (size_t i = 0; i < effectChains.size(); i ++) {
2663 effectChains[i]->process_l();
2664 }
2665 }
2666
2667 // enable changes in effect chain
2668 unlockEffectChains(effectChains);
2669
2670 // sleepTime == 0 means we must write to audio hardware
2671 if (sleepTime == 0) {
2672
2673 threadLoop_write();
2674
2675if (mType == MIXER) {
2676 // write blocked detection
2677 nsecs_t now = systemTime();
2678 nsecs_t delta = now - mLastWriteTime;
2679 if (!mStandby && delta > maxPeriod) {
2680 mNumDelayedWrites++;
2681 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002682#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002683 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002684#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002685 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2686 ns2ms(delta), mNumDelayedWrites, this);
2687 lastWarning = now;
2688 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002689 }
2690}
2691
2692 mStandby = false;
2693 } else {
2694 usleep(sleepTime);
2695 }
2696
Glenn Kasten58912562012-04-03 10:45:00 -07002697 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002698 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002699 // same lock. This will also mutate and push a new fast mixer state.
2700 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002701 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002702
Glenn Kastenfa26a852012-03-06 11:28:04 -08002703 // FIXME I don't understand the need for this here;
2704 // it was in the original code but maybe the
2705 // assignment in saveOutputTracks() makes this unnecessary?
2706 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002707
2708 // Effect chains will be actually deleted here if they were removed from
2709 // mEffectChains list during mixing or effects processing
2710 effectChains.clear();
2711
2712 // FIXME Note that the above .clear() is no longer necessary since effectChains
2713 // is now local to this block, but will keep it for now (at least until merge done).
2714 }
2715
Glenn Kasten9f34a362012-03-20 16:46:41 -07002716 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2717 if (mType == MIXER || mType == DIRECT) {
2718 // put output stream into standby mode
2719 if (!mStandby) {
2720 mOutput->stream->common.standby(&mOutput->stream->common);
2721 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002722 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002723
2724 releaseWakeLock();
2725
2726 ALOGV("Thread %p type %d exiting", this, mType);
2727 return false;
2728}
2729
Glenn Kasten58912562012-04-03 10:45:00 -07002730void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2731{
Glenn Kasten58912562012-04-03 10:45:00 -07002732 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2733}
2734
2735void AudioFlinger::MixerThread::threadLoop_write()
2736{
2737 // FIXME we should only do one push per cycle; confirm this is true
2738 // Start the fast mixer if it's not already running
2739 if (mFastMixer != NULL) {
2740 FastMixerStateQueue *sq = mFastMixer->sq();
2741 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002742 if (state->mCommand != FastMixerState::MIX_WRITE &&
2743 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002744 if (state->mCommand == FastMixerState::COLD_IDLE) {
2745 int32_t old = android_atomic_inc(&mFastMixerFutex);
2746 if (old == -1) {
2747 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2748 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002749#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002750 if (mAudioWatchdog != 0) {
2751 mAudioWatchdog->resume();
2752 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002753#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002754 }
2755 state->mCommand = FastMixerState::MIX_WRITE;
2756 sq->end();
2757 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002758 if (kUseFastMixer == FastMixer_Dynamic) {
2759 mNormalSink = mPipeSink;
2760 }
Glenn Kasten58912562012-04-03 10:45:00 -07002761 } else {
2762 sq->end(false /*didModify*/);
2763 }
2764 }
2765 PlaybackThread::threadLoop_write();
2766}
2767
Glenn Kasten000f0e32012-03-01 17:10:56 -08002768// shared by MIXER and DIRECT, overridden by DUPLICATING
2769void AudioFlinger::PlaybackThread::threadLoop_write()
2770{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002771 // FIXME rewrite to reduce number of system calls
2772 mLastWriteTime = systemTime();
2773 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002774 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002775
Eric Laurent67c0a582012-05-01 19:31:12 -07002776 // If an NBAIO sink is present, use it to write the normal mixer's submix
2777 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002778#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002779 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002780#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002781 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002782#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002783 // update the setpoint when gScreenState changes
2784 uint32_t screenState = gScreenState;
2785 if (screenState != mScreenState) {
2786 mScreenState = screenState;
2787 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2788 if (pipe != NULL) {
2789 pipe->setAvgFrames((mScreenState & 1) ?
2790 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2791 }
2792 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002793 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002794#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002795 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002796#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002797 if (framesWritten > 0) {
2798 bytesWritten = framesWritten << mBitShift;
2799 } else {
2800 bytesWritten = framesWritten;
2801 }
2802 // otherwise use the HAL / AudioStreamOut directly
2803 } else {
2804 // Direct output thread.
2805 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002806 }
2807
Eric Laurent67c0a582012-05-01 19:31:12 -07002808 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002809 mNumWrites++;
2810 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002811}
2812
Glenn Kasten58912562012-04-03 10:45:00 -07002813void AudioFlinger::MixerThread::threadLoop_standby()
2814{
2815 // Idle the fast mixer if it's currently running
2816 if (mFastMixer != NULL) {
2817 FastMixerStateQueue *sq = mFastMixer->sq();
2818 FastMixerState *state = sq->begin();
2819 if (!(state->mCommand & FastMixerState::IDLE)) {
2820 state->mCommand = FastMixerState::COLD_IDLE;
2821 state->mColdFutexAddr = &mFastMixerFutex;
2822 state->mColdGen++;
2823 mFastMixerFutex = 0;
2824 sq->end();
2825 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2826 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002827 if (kUseFastMixer == FastMixer_Dynamic) {
2828 mNormalSink = mOutputSink;
2829 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002830#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002831 if (mAudioWatchdog != 0) {
2832 mAudioWatchdog->pause();
2833 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002834#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002835 } else {
2836 sq->end(false /*didModify*/);
2837 }
2838 }
2839 PlaybackThread::threadLoop_standby();
2840}
2841
Glenn Kasten000f0e32012-03-01 17:10:56 -08002842// shared by MIXER and DIRECT, overridden by DUPLICATING
2843void AudioFlinger::PlaybackThread::threadLoop_standby()
2844{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002845 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002846 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002847}
2848
2849void AudioFlinger::MixerThread::threadLoop_mix()
2850{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002851 // obtain the presentation timestamp of the next output buffer
2852 int64_t pts;
2853 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002854
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01002855#ifndef ICS_AUDIO_BLOB
John Grossman2c3b2da2012-08-02 17:08:54 -07002856 if (mNormalSink != 0) {
2857 status = mNormalSink->getNextWriteTimestamp(&pts);
2858 } else {
2859 status = mOutputSink->getNextWriteTimestamp(&pts);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002860 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01002861#endif
John Grossman4ff14ba2012-02-08 16:37:41 -08002862
Glenn Kasten952eeb22012-03-06 11:30:57 -08002863 if (status != NO_ERROR) {
2864 pts = AudioBufferProvider::kInvalidPTS;
2865 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002866
Glenn Kasten952eeb22012-03-06 11:30:57 -08002867 // mix buffers...
2868 mAudioMixer->process(pts);
2869 // increase sleep time progressively when application underrun condition clears.
2870 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2871 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2872 // such that we would underrun the audio HAL.
2873 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2874 sleepTimeShift--;
2875 }
2876 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002877 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002878 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002879}
2880
2881void AudioFlinger::MixerThread::threadLoop_sleepTime()
2882{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002883 // If no tracks are ready, sleep once for the duration of an output
2884 // buffer size, then write 0s to the output
2885 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002886 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002887 sleepTime = activeSleepTime >> sleepTimeShift;
2888 if (sleepTime < kMinThreadSleepTimeUs) {
2889 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002890 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002891 // reduce sleep time in case of consecutive application underruns to avoid
2892 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2893 // duration we would end up writing less data than needed by the audio HAL if
2894 // the condition persists.
2895 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2896 sleepTimeShift++;
2897 }
2898 } else {
2899 sleepTime = idleSleepTime;
2900 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002901 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002902 memset (mMixBuffer, 0, mixBufferSize);
2903 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002904 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002905 }
2906 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002907}
2908
2909// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002910AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002911 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002912{
2913
Glenn Kasten29c23c32012-01-26 13:37:52 -08002914 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002915 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002916 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002917 size_t mixedTracks = 0;
2918 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002919 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002920 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002921 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002922
2923 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002924 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002925
Eric Laurent571d49c2010-08-11 05:20:11 -07002926 if (masterMute) {
2927 masterVolume = 0;
2928 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002929 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002930 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002931 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002932 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002933 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002934 masterVolume = (float)((v + (1 << 23)) >> 24);
2935 chain.clear();
2936 }
2937
Glenn Kasten288ed212012-04-25 17:52:27 -07002938 // prepare a new state to push
2939 FastMixerStateQueue *sq = NULL;
2940 FastMixerState *state = NULL;
2941 bool didModify = false;
2942 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2943 if (mFastMixer != NULL) {
2944 sq = mFastMixer->sq();
2945 state = sq->begin();
2946 }
2947
Mathias Agopian65ab4712010-07-14 17:59:35 -07002948 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002949 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002950 if (t == 0) continue;
2951
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002952 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002953 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002954
Glenn Kasten288ed212012-04-25 17:52:27 -07002955 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002956 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002957
2958 // It's theoretically possible (though unlikely) for a fast track to be created
2959 // and then removed within the same normal mix cycle. This is not a problem, as
2960 // the track never becomes active so it's fast mixer slot is never touched.
2961 // The converse, of removing an (active) track and then creating a new track
2962 // at the identical fast mixer slot within the same normal mix cycle,
2963 // is impossible because the slot isn't marked available until the end of each cycle.
2964 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002965 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2966 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002967 FastTrack *fastTrack = &state->mFastTracks[j];
2968
2969 // Determine whether the track is currently in underrun condition,
2970 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002971 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2972 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002973 uint32_t recentFull = (underruns.mBitFields.mFull -
2974 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2975 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2976 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2977 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2978 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2979 uint32_t recentUnderruns = recentPartial + recentEmpty;
2980 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002981 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002982 // or stopped which can occur when flush() is called while active
2983 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002984 track->mUnderrunCount += recentUnderruns;
2985 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002986
Glenn Kastend08f48c2012-05-01 18:14:02 -07002987 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002988 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002989 bool isActive = true;
2990 switch (track->mState) {
2991 case TrackBase::STOPPING_1:
2992 // track stays active in STOPPING_1 state until first underrun
2993 if (recentUnderruns > 0) {
2994 track->mState = TrackBase::STOPPING_2;
2995 }
2996 break;
2997 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002998 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002999 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07003000 break;
3001 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003002 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003003 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003004 break;
3005 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07003006 if (recentFull > 0 || recentPartial > 0) {
3007 // track has provided at least some frames recently: reset retry count
3008 track->mRetryCount = kMaxTrackRetries;
3009 }
3010 if (recentUnderruns == 0) {
3011 // no recent underruns: stay active
3012 break;
3013 }
3014 // there has recently been an underrun of some kind
3015 if (track->sharedBuffer() == 0) {
3016 // were any of the recent underruns "empty" (no frames available)?
3017 if (recentEmpty == 0) {
3018 // no, then ignore the partial underruns as they are allowed indefinitely
3019 break;
3020 }
3021 // there has recently been an "empty" underrun: decrement the retry counter
3022 if (--(track->mRetryCount) > 0) {
3023 break;
3024 }
3025 // indicate to client process that the track was disabled because of underrun;
3026 // it will then automatically call start() when data is available
3027 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
3028 // remove from active list, but state remains ACTIVE [confusing but true]
3029 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003030 break;
3031 }
3032 // fall through
3033 case TrackBase::STOPPING_2:
3034 case TrackBase::PAUSED:
3035 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07003036 case TrackBase::STOPPED:
3037 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07003038 // Check for presentation complete if track is inactive
3039 // We have consumed all the buffers of this track.
3040 // This would be incomplete if we auto-paused on underrun
3041 {
3042 size_t audioHALFrames =
3043 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3044 size_t framesWritten =
3045 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003046 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
Glenn Kastend08f48c2012-05-01 18:14:02 -07003047 // track stays in active list until presentation is complete
3048 break;
3049 }
3050 }
3051 if (track->isStopping_2()) {
3052 track->mState = TrackBase::STOPPED;
3053 }
3054 if (track->isStopped()) {
3055 // Can't reset directly, as fast mixer is still polling this track
3056 // track->reset();
3057 // So instead mark this track as needing to be reset after push with ack
3058 resetMask |= 1 << i;
3059 }
3060 isActive = false;
3061 break;
3062 case TrackBase::IDLE:
3063 default:
3064 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003065 }
3066
3067 if (isActive) {
3068 // was it previously inactive?
3069 if (!(state->mTrackMask & (1 << j))) {
3070 ExtendedAudioBufferProvider *eabp = track;
3071 VolumeProvider *vp = track;
3072 fastTrack->mBufferProvider = eabp;
3073 fastTrack->mVolumeProvider = vp;
3074 fastTrack->mSampleRate = track->mSampleRate;
3075 fastTrack->mChannelMask = track->mChannelMask;
3076 fastTrack->mGeneration++;
3077 state->mTrackMask |= 1 << j;
3078 didModify = true;
3079 // no acknowledgement required for newly active tracks
3080 }
3081 // cache the combined master volume and stream type volume for fast mixer; this
3082 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3083 track->mCachedVolume = track->isMuted() ?
3084 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3085 ++fastTracks;
3086 } else {
3087 // was it previously active?
3088 if (state->mTrackMask & (1 << j)) {
3089 fastTrack->mBufferProvider = NULL;
3090 fastTrack->mGeneration++;
3091 state->mTrackMask &= ~(1 << j);
3092 didModify = true;
3093 // If any fast tracks were removed, we must wait for acknowledgement
3094 // because we're about to decrement the last sp<> on those tracks.
3095 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003096 } else {
3097 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003098 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003099 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003100 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003101 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003102 }
3103 continue;
3104 }
3105
3106 { // local variable scope to avoid goto warning
3107
Mathias Agopian65ab4712010-07-14 17:59:35 -07003108 audio_track_cblk_t* cblk = track->cblk();
3109
3110 // The first time a track is added we wait
3111 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003112 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003113 // make sure that we have enough frames to mix one full buffer.
3114 // enforce this condition only once to enable draining the buffer in case the client
3115 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003116 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003117 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003118 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003119 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003120 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003121 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003122 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003123 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003124 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003125 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003126 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003127 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003128 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3129 // the minimum track buffer size is normally twice the number of frames necessary
3130 // to fill one buffer and the resampler should not leave more than one buffer worth
3131 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003132 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003133 }
3134 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003135 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003136 !track->isPaused() && !track->isTerminated())
3137 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003138 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003139
3140 mixedTracks++;
3141
3142 // track->mainBuffer() != mMixBuffer means there is an effect chain
3143 // connected to the track
3144 chain.clear();
3145 if (track->mainBuffer() != mMixBuffer) {
3146 chain = getEffectChain_l(track->sessionId());
3147 // Delegate volume control to effect in track effect chain if needed
3148 if (chain != 0) {
3149 tracksWithEffect++;
3150 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003151 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003152 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153 }
3154 }
3155
3156
3157 int param = AudioMixer::VOLUME;
3158 if (track->mFillingUpStatus == Track::FS_FILLED) {
3159 // no ramp for the first volume setting
3160 track->mFillingUpStatus = Track::FS_ACTIVE;
3161 if (track->mState == TrackBase::RESUMING) {
3162 track->mState = TrackBase::ACTIVE;
3163 param = AudioMixer::RAMP_VOLUME;
3164 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003165 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003166 } else if (cblk->server != 0) {
3167 // If the track is stopped before the first frame was mixed,
3168 // do not apply ramp
3169 param = AudioMixer::RAMP_VOLUME;
3170 }
3171
3172 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003173 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003174 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003175 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003176 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003177 if (track->isPausing()) {
3178 track->setPaused();
3179 }
3180 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003181
Mathias Agopian65ab4712010-07-14 17:59:35 -07003182 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003183 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003185 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003186 vl = vlr & 0xFFFF;
3187 vr = vlr >> 16;
3188 // track volumes come from shared memory, so can't be trusted and must be clamped
3189 if (vl > MAX_GAIN_INT) {
3190 ALOGV("Track left volume out of range: %04X", vl);
3191 vl = MAX_GAIN_INT;
3192 }
3193 if (vr > MAX_GAIN_INT) {
3194 ALOGV("Track right volume out of range: %04X", vr);
3195 vr = MAX_GAIN_INT;
3196 }
3197 // now apply the master volume and stream type volume
3198 vl = (uint32_t)(v * vl) << 12;
3199 vr = (uint32_t)(v * vr) << 12;
3200 // assuming master volume and stream type volume each go up to 1.0,
3201 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003202
Glenn Kasten05632a52012-01-03 14:22:33 -08003203 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3204 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003205 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003206 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003207 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003208 }
3209 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003210 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003211 // Delegate volume control to effect in track effect chain if needed
3212 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3213 // Do not ramp volume if volume is controlled by effect
3214 param = AudioMixer::VOLUME;
3215 track->mHasVolumeController = true;
3216 } else {
3217 // force no volume ramp when volume controller was just disabled or removed
3218 // from effect chain to avoid volume spike
3219 if (track->mHasVolumeController) {
3220 param = AudioMixer::VOLUME;
3221 }
3222 track->mHasVolumeController = false;
3223 }
3224
3225 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003226 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003227 vl = (vl + (1 << 11)) >> 12;
3228 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3229 vr = (vr + (1 << 11)) >> 12;
3230 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003231
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003232 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT; // va is uint32_t, so no need to check for -
Mathias Agopian65ab4712010-07-14 17:59:35 -07003233
Mathias Agopian65ab4712010-07-14 17:59:35 -07003234 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003235 mAudioMixer->setBufferProvider(name, track);
3236 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003237
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003238 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3239 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3240 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003241 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003242 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003243 AudioMixer::TRACK,
3244 AudioMixer::FORMAT, (void *)track->format());
3245 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003246 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003247 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003248 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003249 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003250 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003251 AudioMixer::RESAMPLE,
3252 AudioMixer::SAMPLE_RATE,
3253 (void *)(cblk->sampleRate));
3254 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003255 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003256 AudioMixer::TRACK,
3257 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3258 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003259 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003260 AudioMixer::TRACK,
3261 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3262
3263 // reset retry count
3264 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003265
Eric Laurent27741442012-01-17 19:20:12 -08003266 // If one track is ready, set the mixer ready if:
3267 // - the mixer was not ready during previous round OR
3268 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003269 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003270 mixerStatus != MIXER_TRACKS_ENABLED) {
3271 mixerStatus = MIXER_TRACKS_READY;
3272 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003273 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003274 // clear effect chain input buffer if an active track underruns to avoid sending
3275 // previous audio buffer again to effects
3276 chain = getEffectChain_l(track->sessionId());
3277 if (chain != 0) {
3278 chain->clearInputBuffer();
3279 }
3280
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003281 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Glenn Kasten842c5d92012-09-26 08:34:10 -07003282 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent83faee02012-04-27 18:24:29 -07003283 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003284 // We have consumed all the buffers of this track.
3285 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003286 // TODO: use actual buffer filling status instead of latency when available from
3287 // audio HAL
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07003288 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07003289 size_t framesWritten =
3290 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003291 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003292 if (track->isStopped()) {
3293 track->reset();
3294 }
Eric Laurenta011e352012-03-29 15:51:43 -07003295 tracksToRemove->add(track);
3296 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003297 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003298 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003299 // No buffers for this track. Give it a few chances to
3300 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07003301 if (--(track->mRetryCount) <= 0) {
3302 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003303 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003304 // indicate to client process that the track was disabled because of underrun;
3305 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003306 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003307 // If one track is not ready, mark the mixer also not ready if:
3308 // - the mixer was ready during previous round OR
3309 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003310 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003311 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003312 mixerStatus = MIXER_TRACKS_ENABLED;
3313 }
3314 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003315 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003316 }
Glenn Kasten58912562012-04-03 10:45:00 -07003317
3318 } // local variable scope to avoid goto warning
3319track_is_ready: ;
3320
Mathias Agopian65ab4712010-07-14 17:59:35 -07003321 }
3322
Glenn Kasten288ed212012-04-25 17:52:27 -07003323 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003324 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003325 if (didModify) {
3326 state->mFastTracksGen++;
3327 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3328 if (kUseFastMixer == FastMixer_Dynamic &&
3329 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3330 state->mCommand = FastMixerState::COLD_IDLE;
3331 state->mColdFutexAddr = &mFastMixerFutex;
3332 state->mColdGen++;
3333 mFastMixerFutex = 0;
3334 if (kUseFastMixer == FastMixer_Dynamic) {
3335 mNormalSink = mOutputSink;
3336 }
3337 // If we go into cold idle, need to wait for acknowledgement
3338 // so that fast mixer stops doing I/O.
3339 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003340 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003341 }
3342 sq->end();
3343 }
3344 if (sq != NULL) {
3345 sq->end(didModify);
3346 sq->push(block);
3347 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003348#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003349 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3350 mAudioWatchdog->pause();
3351 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003352#endif
Glenn Kasten288ed212012-04-25 17:52:27 -07003353
3354 // Now perform the deferred reset on fast tracks that have stopped
3355 while (resetMask != 0) {
3356 size_t i = __builtin_ctz(resetMask);
3357 ALOG_ASSERT(i < count);
3358 resetMask &= ~(1 << i);
3359 sp<Track> t = mActiveTracks[i].promote();
3360 if (t == 0) continue;
3361 Track* track = t.get();
3362 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3363 track->reset();
3364 }
Glenn Kasten58912562012-04-03 10:45:00 -07003365
Mathias Agopian65ab4712010-07-14 17:59:35 -07003366 // remove all the tracks that need to be...
3367 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003368 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003369 for (size_t i=0 ; i<count ; i++) {
3370 const sp<Track>& track = tracksToRemove->itemAt(i);
3371 mActiveTracks.remove(track);
3372 if (track->mainBuffer() != mMixBuffer) {
3373 chain = getEffectChain_l(track->sessionId());
3374 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003375 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003376 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003377 }
3378 }
3379 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003380 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003381 }
3382 }
3383 }
3384
3385 // mix buffer must be cleared if all tracks are connected to an
3386 // effect chain as in this case the mixer will not write to
3387 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003388 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3389 // FIXME as a performance optimization, should remember previous zero status
3390 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003391 }
3392
Glenn Kasten58912562012-04-03 10:45:00 -07003393 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003394 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003395 if (fastTracks > 0) {
3396 mixerStatus = MIXER_TRACKS_READY;
3397 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003398 return mixerStatus;
3399}
3400
Glenn Kasten66fcab92012-02-24 14:59:21 -08003401/*
3402The derived values that are cached:
3403 - mixBufferSize from frame count * frame size
3404 - activeSleepTime from activeSleepTimeUs()
3405 - idleSleepTime from idleSleepTimeUs()
3406 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3407 - maxPeriod from frame count and sample rate (MIXER only)
3408
3409The parameters that affect these derived values are:
3410 - frame count
3411 - frame size
3412 - sample rate
3413 - device type: A2DP or not
3414 - device latency
3415 - format: PCM or not
3416 - active sleep time
3417 - idle sleep time
3418*/
3419
3420void AudioFlinger::PlaybackThread::cacheParameters_l()
3421{
Glenn Kasten58912562012-04-03 10:45:00 -07003422 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003423 activeSleepTime = activeSleepTimeUs();
3424 idleSleepTime = idleSleepTimeUs();
3425}
3426
Eric Laurent22167852012-06-20 12:26:32 -07003427void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003428{
Steve Block3856b092011-10-20 11:56:00 +01003429 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003430 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003431 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003432
Mathias Agopian65ab4712010-07-14 17:59:35 -07003433 size_t size = mTracks.size();
3434 for (size_t i = 0; i < size; i++) {
3435 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003436 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003437 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003438 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003439 }
3440 }
3441}
3442
Mathias Agopian65ab4712010-07-14 17:59:35 -07003443// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003444int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003445{
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003446 return mAudioMixer->getTrackName(channelMask, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003447}
3448
3449// deleteTrackName_l() must be called with ThreadBase::mLock held
3450void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3451{
Steve Block3856b092011-10-20 11:56:00 +01003452 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003453 mAudioMixer->deleteTrackName(name);
3454}
3455
3456// checkForNewParameters_l() must be called with ThreadBase::mLock held
3457bool AudioFlinger::MixerThread::checkForNewParameters_l()
3458{
Glenn Kasten58912562012-04-03 10:45:00 -07003459 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3460 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003461 bool reconfig = false;
3462
3463 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003464
3465 if (mFastMixer != NULL) {
3466 FastMixerStateQueue *sq = mFastMixer->sq();
3467 FastMixerState *state = sq->begin();
3468 if (!(state->mCommand & FastMixerState::IDLE)) {
3469 previousCommand = state->mCommand;
3470 state->mCommand = FastMixerState::HOT_IDLE;
3471 sq->end();
3472 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3473 } else {
3474 sq->end(false /*didModify*/);
3475 }
3476 }
3477
Mathias Agopian65ab4712010-07-14 17:59:35 -07003478 status_t status = NO_ERROR;
3479 String8 keyValuePair = mNewParameters[0];
3480 AudioParameter param = AudioParameter(keyValuePair);
3481 int value;
3482
3483 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3484 reconfig = true;
3485 }
3486 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003487 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003488 status = BAD_VALUE;
3489 } else {
3490 reconfig = true;
3491 }
3492 }
3493 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003494 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003495 status = BAD_VALUE;
3496 } else {
3497 reconfig = true;
3498 }
3499 }
3500 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3501 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003502 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003503 // if frame count is changed after track creation
3504 if (!mTracks.isEmpty()) {
3505 status = INVALID_OPERATION;
3506 } else {
3507 reconfig = true;
3508 }
3509 }
3510 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003511#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003512 // when changing the audio output device, call addBatteryData to notify
3513 // the change
Eric Laurentf1c04f92012-08-28 14:26:53 -07003514 if (mOutDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003515 uint32_t params = 0;
3516 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003517 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003518 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3519 }
3520
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003521 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003522 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003523 // check if any other device (except speaker) is on
3524 if (value & deviceWithoutSpeaker ) {
3525 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3526 }
3527
3528 if (params != 0) {
3529 addBatteryData(params);
3530 }
3531 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003532#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003533
Mathias Agopian65ab4712010-07-14 17:59:35 -07003534 // forward device change to effects that have requested to be
3535 // aware of attached audio device.
Eric Laurentf1c04f92012-08-28 14:26:53 -07003536 mOutDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003537 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07003538 mEffectChains[i]->setDevice_l(mOutDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003539 }
3540 }
3541
3542 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003543 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003544 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003545 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003546 mOutput->stream->common.standby(&mOutput->stream->common);
3547 mStandby = true;
3548 mBytesWritten = 0;
3549 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003550 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003551 }
3552 if (status == NO_ERROR && reconfig) {
3553 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003554 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3555 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003556 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003557 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003558 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003559 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003560 if (name < 0) break;
3561 mTracks[i]->mName = name;
3562 // limit track sample rate to 2 x new output sample rate
3563 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3564 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3565 }
3566 }
Eric Laurent896adcd2012-09-13 11:18:23 -07003567 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003568 }
3569 }
3570
3571 mNewParameters.removeAt(0);
3572
3573 mParamStatus = status;
3574 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003575 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3576 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003577 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003578 }
Glenn Kasten58912562012-04-03 10:45:00 -07003579
3580 if (!(previousCommand & FastMixerState::IDLE)) {
3581 ALOG_ASSERT(mFastMixer != NULL);
3582 FastMixerStateQueue *sq = mFastMixer->sq();
3583 FastMixerState *state = sq->begin();
3584 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3585 state->mCommand = previousCommand;
3586 sq->end();
3587 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3588 }
3589
Mathias Agopian65ab4712010-07-14 17:59:35 -07003590 return reconfig;
3591}
3592
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07003593void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003594{
3595 const size_t SIZE = 256;
3596 char buffer[SIZE];
3597 String8 result;
3598
3599 PlaybackThread::dumpInternals(fd, args);
3600
3601 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3602 result.append(buffer);
3603 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003604
3605 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3606 FastMixerDumpState copy = mFastMixerDumpState;
3607 copy.dump(fd);
3608
Glenn Kasten39993082012-05-31 13:40:27 -07003609#ifdef STATE_QUEUE_DUMP
3610 // Similar for state queue
3611 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3612 observerCopy.dump(fd);
3613 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3614 mutatorCopy.dump(fd);
3615#endif
3616
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003617 // Write the tee output to a .wav file
3618 NBAIO_Source *teeSource = mTeeSource.get();
3619 if (teeSource != NULL) {
3620 char teePath[64];
3621 struct timeval tv;
3622 gettimeofday(&tv, NULL);
3623 struct tm tm;
3624 localtime_r(&tv.tv_sec, &tm);
3625 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3626 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3627 if (teeFd >= 0) {
3628 char wavHeader[44];
3629 memcpy(wavHeader,
3630 "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",
3631 sizeof(wavHeader));
3632 NBAIO_Format format = teeSource->format();
3633 unsigned channelCount = Format_channelCount(format);
3634 ALOG_ASSERT(channelCount <= FCC_2);
3635 unsigned sampleRate = Format_sampleRate(format);
3636 wavHeader[22] = channelCount; // number of channels
3637 wavHeader[24] = sampleRate; // sample rate
3638 wavHeader[25] = sampleRate >> 8;
3639 wavHeader[32] = channelCount * 2; // block alignment
3640 write(teeFd, wavHeader, sizeof(wavHeader));
3641 size_t total = 0;
3642 bool firstRead = true;
3643 for (;;) {
3644#define TEE_SINK_READ 1024
3645 short buffer[TEE_SINK_READ * FCC_2];
3646 size_t count = TEE_SINK_READ;
John Grossman2c3b2da2012-08-02 17:08:54 -07003647 ssize_t actual = teeSource->read(buffer, count,
3648 AudioBufferProvider::kInvalidPTS);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003649 bool wasFirstRead = firstRead;
3650 firstRead = false;
3651 if (actual <= 0) {
3652 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3653 continue;
3654 }
3655 break;
3656 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003657 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003658 write(teeFd, buffer, actual * channelCount * sizeof(short));
3659 total += actual;
3660 }
3661 lseek(teeFd, (off_t) 4, SEEK_SET);
3662 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3663 write(teeFd, &temp, sizeof(temp));
3664 lseek(teeFd, (off_t) 40, SEEK_SET);
3665 temp = total * channelCount * sizeof(short);
3666 write(teeFd, &temp, sizeof(temp));
3667 close(teeFd);
3668 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3669 } else {
3670 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3671 }
3672 }
3673
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003674#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003675 if (mAudioWatchdog != 0) {
3676 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3677 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3678 wdCopy.dump(fd);
3679 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003680#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003681}
3682
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003683uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003684{
Glenn Kasten58912562012-04-03 10:45:00 -07003685 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003686}
3687
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003688uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003689{
Glenn Kasten58912562012-04-03 10:45:00 -07003690 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003691}
3692
Glenn Kasten66fcab92012-02-24 14:59:21 -08003693void AudioFlinger::MixerThread::cacheParameters_l()
3694{
3695 PlaybackThread::cacheParameters_l();
3696
3697 // FIXME: Relaxed timing because of a certain device that can't meet latency
3698 // Should be reduced to 2x after the vendor fixes the driver issue
3699 // increase threshold again due to low power audio mode. The way this warning
3700 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003701 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003702}
3703
Mathias Agopian65ab4712010-07-14 17:59:35 -07003704// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003705AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003706 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003707 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003708 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003709{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003710}
3711
3712AudioFlinger::DirectOutputThread::~DirectOutputThread()
3713{
3714}
3715
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003716AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3717 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003718)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003719{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003720 sp<Track> trackToRemove;
3721
Glenn Kastenfec279f2012-03-08 07:47:15 -08003722 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003723
Glenn Kasten952eeb22012-03-06 11:30:57 -08003724 // find out which tracks need to be processed
3725 if (mActiveTracks.size() != 0) {
3726 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003727 // The track died recently
3728 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003729
Glenn Kasten952eeb22012-03-06 11:30:57 -08003730 Track* const track = t.get();
3731 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003732
Glenn Kasten952eeb22012-03-06 11:30:57 -08003733 // The first time a track is added we wait
3734 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003735 uint32_t minFrames;
3736 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3737 minFrames = mNormalFrameCount;
3738 } else {
3739 minFrames = 1;
3740 }
3741 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003742 !track->isPaused() && !track->isTerminated())
3743 {
3744 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003745
Glenn Kasten952eeb22012-03-06 11:30:57 -08003746 if (track->mFillingUpStatus == Track::FS_FILLED) {
3747 track->mFillingUpStatus = Track::FS_ACTIVE;
3748 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003749 if (track->mState == TrackBase::RESUMING) {
3750 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003751 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003752 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003753
Glenn Kasten952eeb22012-03-06 11:30:57 -08003754 // compute volume for this track
3755 float left, right;
3756 if (track->isMuted() || mMasterMute || track->isPausing() ||
3757 mStreamTypes[track->streamType()].mute) {
3758 left = right = 0;
3759 if (track->isPausing()) {
3760 track->setPaused();
3761 }
3762 } else {
3763 float typeVolume = mStreamTypes[track->streamType()].volume;
3764 float v = mMasterVolume * typeVolume;
3765 uint32_t vlr = cblk->getVolumeLR();
3766 float v_clamped = v * (vlr & 0xFFFF);
3767 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3768 left = v_clamped/MAX_GAIN;
3769 v_clamped = v * (vlr >> 16);
3770 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3771 right = v_clamped/MAX_GAIN;
3772 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003773
Glenn Kasten952eeb22012-03-06 11:30:57 -08003774 if (left != mLeftVolFloat || right != mRightVolFloat) {
3775 mLeftVolFloat = left;
3776 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003777
Glenn Kasten952eeb22012-03-06 11:30:57 -08003778 // Convert volumes from float to 8.24
3779 uint32_t vl = (uint32_t)(left * (1 << 24));
3780 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003781
Glenn Kasten952eeb22012-03-06 11:30:57 -08003782 // Delegate volume control to effect in track effect chain if needed
3783 // only one effect chain can be present on DirectOutputThread, so if
3784 // there is one, the track is connected to it
3785 if (!mEffectChains.isEmpty()) {
3786 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003787 mEffectChains[0]->setVolume_l(&vl, &vr);
3788 left = (float)vl / (1 << 24);
3789 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003790 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003791 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003792 }
3793
3794 // reset retry count
3795 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003796 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003797 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003798 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003799 // clear effect chain input buffer if an active track underruns to avoid sending
3800 // previous audio buffer again to effects
3801 if (!mEffectChains.isEmpty()) {
3802 mEffectChains[0]->clearInputBuffer();
3803 }
3804
Glenn Kasten952eeb22012-03-06 11:30:57 -08003805 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten842c5d92012-09-26 08:34:10 -07003806 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent67c0a582012-05-01 19:31:12 -07003807 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003808 // We have consumed all the buffers of this track.
3809 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003810 // TODO: implement behavior for compressed audio
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07003811 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07003812 size_t framesWritten =
3813 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003814 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003815 if (track->isStopped()) {
3816 track->reset();
3817 }
Eric Laurenta011e352012-03-29 15:51:43 -07003818 trackToRemove = track;
3819 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003820 } else {
3821 // No buffers for this track. Give it a few chances to
3822 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07003823 if (--(track->mRetryCount) <= 0) {
3824 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Glenn Kasten952eeb22012-03-06 11:30:57 -08003825 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003826 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003827 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003828 }
3829 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003830 }
3831 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003832
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003833 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003834 // remove all the tracks that need to be...
3835 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003836 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003837 mActiveTracks.remove(trackToRemove);
3838 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003839 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003840 trackToRemove->sessionId());
3841 mEffectChains[0]->decActiveTrackCnt();
3842 }
3843 if (trackToRemove->isTerminated()) {
3844 removeTrack_l(trackToRemove);
3845 }
3846 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003847
Glenn Kastenfec279f2012-03-08 07:47:15 -08003848 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003849}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003850
Glenn Kasten000f0e32012-03-01 17:10:56 -08003851void AudioFlinger::DirectOutputThread::threadLoop_mix()
3852{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003853 AudioBufferProvider::Buffer buffer;
3854 size_t frameCount = mFrameCount;
3855 int8_t *curBuf = (int8_t *)mMixBuffer;
3856 // output audio to hardware
3857 while (frameCount) {
3858 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003859 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003860 if (CC_UNLIKELY(buffer.raw == NULL)) {
3861 memset(curBuf, 0, frameCount * mFrameSize);
3862 break;
3863 }
3864 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3865 frameCount -= buffer.frameCount;
3866 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003867 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003868 }
3869 sleepTime = 0;
3870 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003871 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003872
Glenn Kasten000f0e32012-03-01 17:10:56 -08003873}
3874
3875void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3876{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003877 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003878 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003879 sleepTime = activeSleepTime;
3880 } else {
3881 sleepTime = idleSleepTime;
3882 }
3883 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003884 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003885 sleepTime = 0;
3886 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003887}
3888
3889// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003890int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3891 int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003892{
3893 return 0;
3894}
3895
3896// deleteTrackName_l() must be called with ThreadBase::mLock held
3897void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3898{
3899}
3900
3901// checkForNewParameters_l() must be called with ThreadBase::mLock held
3902bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3903{
3904 bool reconfig = false;
3905
3906 while (!mNewParameters.isEmpty()) {
3907 status_t status = NO_ERROR;
3908 String8 keyValuePair = mNewParameters[0];
3909 AudioParameter param = AudioParameter(keyValuePair);
3910 int value;
3911
3912 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3913 // do not accept frame count changes if tracks are open as the track buffer
3914 // size depends on frame count and correct behavior would not be garantied
3915 // if frame count is changed after track creation
3916 if (!mTracks.isEmpty()) {
3917 status = INVALID_OPERATION;
3918 } else {
3919 reconfig = true;
3920 }
3921 }
3922 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003923 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003924 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003925 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003926 mOutput->stream->common.standby(&mOutput->stream->common);
3927 mStandby = true;
3928 mBytesWritten = 0;
3929 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003930 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003931 }
3932 if (status == NO_ERROR && reconfig) {
3933 readOutputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07003934 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003935 }
3936 }
3937
3938 mNewParameters.removeAt(0);
3939
3940 mParamStatus = status;
3941 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003942 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3943 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003944 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003945 }
3946 return reconfig;
3947}
3948
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003949uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003950{
3951 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003952 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003953 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003954 } else {
3955 time = 10000;
3956 }
3957 return time;
3958}
3959
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003960uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003961{
3962 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003963 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003964 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003965 } else {
3966 time = 10000;
3967 }
3968 return time;
3969}
3970
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003971uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003972{
3973 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003974 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003975 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3976 } else {
3977 time = 10000;
3978 }
3979 return time;
3980}
3981
Glenn Kasten66fcab92012-02-24 14:59:21 -08003982void AudioFlinger::DirectOutputThread::cacheParameters_l()
3983{
3984 PlaybackThread::cacheParameters_l();
3985
3986 // use shorter standby delay as on normal output to release
3987 // hardware resources as soon as possible
3988 standbyDelay = microseconds(activeSleepTime*2);
3989}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003990
Mathias Agopian65ab4712010-07-14 17:59:35 -07003991// ----------------------------------------------------------------------------
3992
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003993AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003994 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Eric Laurentf1c04f92012-08-28 14:26:53 -07003995 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(), DUPLICATING),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003996 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003997{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003998 addOutputTrack(mainThread);
3999}
4000
4001AudioFlinger::DuplicatingThread::~DuplicatingThread()
4002{
4003 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4004 mOutputTracks[i]->destroy();
4005 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004006}
4007
Glenn Kasten000f0e32012-03-01 17:10:56 -08004008void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004009{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004010 // mix buffers...
4011 if (outputsReady(outputTracks)) {
4012 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4013 } else {
4014 memset(mMixBuffer, 0, mixBufferSize);
4015 }
4016 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07004017 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004018 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004019}
4020
4021void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4022{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004023 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004024 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004025 sleepTime = activeSleepTime;
4026 } else {
4027 sleepTime = idleSleepTime;
4028 }
4029 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004030 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4031 writeFrames = mNormalFrameCount;
4032 memset(mMixBuffer, 0, mixBufferSize);
4033 } else {
4034 // flush remaining overflow buffers in output tracks
4035 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004036 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004037 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004038 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08004039}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004040
Glenn Kasten000f0e32012-03-01 17:10:56 -08004041void AudioFlinger::DuplicatingThread::threadLoop_write()
4042{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004043 for (size_t i = 0; i < outputTracks.size(); i++) {
4044 outputTracks[i]->write(mMixBuffer, writeFrames);
4045 }
4046 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004047}
Glenn Kasten688a6402012-02-29 07:57:06 -08004048
Glenn Kasten000f0e32012-03-01 17:10:56 -08004049void AudioFlinger::DuplicatingThread::threadLoop_standby()
4050{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004051 // DuplicatingThread implements standby by stopping all tracks
4052 for (size_t i = 0; i < outputTracks.size(); i++) {
4053 outputTracks[i]->stop();
4054 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004055}
4056
Glenn Kastenfa26a852012-03-06 11:28:04 -08004057void AudioFlinger::DuplicatingThread::saveOutputTracks()
4058{
4059 outputTracks = mOutputTracks;
4060}
4061
4062void AudioFlinger::DuplicatingThread::clearOutputTracks()
4063{
4064 outputTracks.clear();
4065}
4066
Mathias Agopian65ab4712010-07-14 17:59:35 -07004067void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4068{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004069 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004070 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004071 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004072 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004073 this,
4074 mSampleRate,
4075 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004076 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004077 frameCount);
4078 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004079 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004080 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004081 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004082 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004083 }
4084}
4085
4086void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4087{
4088 Mutex::Autolock _l(mLock);
4089 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004090 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004091 mOutputTracks[i]->destroy();
4092 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004093 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004094 return;
4095 }
4096 }
Steve Block3856b092011-10-20 11:56:00 +01004097 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004098}
4099
Glenn Kasten438b0362012-03-06 11:24:48 -08004100// caller must hold mLock
4101void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004102{
4103 mWaitTimeMs = UINT_MAX;
4104 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4105 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004106 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004107 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4108 if (waitTimeMs < mWaitTimeMs) {
4109 mWaitTimeMs = waitTimeMs;
4110 }
4111 }
4112 }
4113}
4114
4115
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004116bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004117{
4118 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004119 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004120 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004121 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004122 return false;
4123 }
4124 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004125 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004126 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004127 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004128 return false;
4129 }
4130 }
4131 return true;
4132}
4133
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004134uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004135{
4136 return (mWaitTimeMs * 1000) / 2;
4137}
4138
Glenn Kasten66fcab92012-02-24 14:59:21 -08004139void AudioFlinger::DuplicatingThread::cacheParameters_l()
4140{
4141 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4142 updateWaitTime_l();
4143
4144 MixerThread::cacheParameters_l();
4145}
4146
Mathias Agopian65ab4712010-07-14 17:59:35 -07004147// ----------------------------------------------------------------------------
4148
4149// TrackBase constructor must be called with AudioFlinger::mLock held
4150AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004151 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004152 const sp<Client>& client,
4153 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004154 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004155 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004156 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004157 const sp<IMemory>& sharedBuffer,
4158 int sessionId)
4159 : RefBase(),
4160 mThread(thread),
4161 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004162 mCblk(NULL),
4163 // mBuffer
4164 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004165 mFrameCount(0),
4166 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004167 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004168 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004169 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004170 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004171 // mChannelCount
4172 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004173{
Steve Block3856b092011-10-20 11:56:00 +01004174 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004175
Steve Blockb8a80522011-12-20 16:23:08 +00004176 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004177 size_t size = sizeof(audio_track_cblk_t);
4178 uint8_t channelCount = popcount(channelMask);
4179 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4180 if (sharedBuffer == 0) {
4181 size += bufferSize;
4182 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004183
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004184 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004185 mCblkMemory = client->heap()->allocate(size);
4186 if (mCblkMemory != 0) {
4187 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004188 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004189 new(mCblk) audio_track_cblk_t();
4190 // clear all buffers
4191 mCblk->frameCount = frameCount;
4192 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004193// uncomment the following lines to quickly test 32-bit wraparound
4194// mCblk->user = 0xffff0000;
4195// mCblk->server = 0xffff0000;
4196// mCblk->userBase = 0xffff0000;
4197// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004198 mChannelCount = channelCount;
4199 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200 if (sharedBuffer == 0) {
4201 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4202 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4203 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004204 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004205 mCblk->flags = CBLK_UNDERRUN_ON;
4206 } else {
4207 mBuffer = sharedBuffer->pointer();
4208 }
4209 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4210 }
4211 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004212 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004213 client->heap()->dump("AudioTrack");
4214 return;
4215 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004216 } else {
4217 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004218 // construct the shared structure in-place.
4219 new(mCblk) audio_track_cblk_t();
4220 // clear all buffers
4221 mCblk->frameCount = frameCount;
4222 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004223// uncomment the following lines to quickly test 32-bit wraparound
4224// mCblk->user = 0xffff0000;
4225// mCblk->server = 0xffff0000;
4226// mCblk->userBase = 0xffff0000;
4227// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004228 mChannelCount = channelCount;
4229 mChannelMask = channelMask;
4230 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4231 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4232 // Force underrun condition to avoid false underrun callback until first data is
4233 // written to buffer (other flags are cleared)
4234 mCblk->flags = CBLK_UNDERRUN_ON;
4235 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004236 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004237}
4238
4239AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4240{
Glenn Kastena0d68332012-01-27 16:47:15 -08004241 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004242 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004243 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004244 } else {
4245 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004246 }
4247 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004248 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004249 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004250 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004251 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004252 // If the client's reference count drops to zero, the associated destructor
4253 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4254 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004255 mClient.clear();
4256 }
4257}
4258
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004259// AudioBufferProvider interface
4260// getNextBuffer() = 0;
4261// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004262void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4263{
Glenn Kastene0feee32011-12-13 11:53:26 -08004264 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004265 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004266 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004267 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004268 buffer->frameCount = 0;
4269}
4270
4271bool AudioFlinger::ThreadBase::TrackBase::step() {
4272 bool result;
4273 audio_track_cblk_t* cblk = this->cblk();
4274
4275 result = cblk->stepServer(mFrameCount);
4276 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004277 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004278 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004279 }
4280 return result;
4281}
4282
4283void AudioFlinger::ThreadBase::TrackBase::reset() {
4284 audio_track_cblk_t* cblk = this->cblk();
4285
4286 cblk->user = 0;
4287 cblk->server = 0;
4288 cblk->userBase = 0;
4289 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004290 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004291 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004292}
4293
Mathias Agopian65ab4712010-07-14 17:59:35 -07004294int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4295 return (int)mCblk->sampleRate;
4296}
4297
Mathias Agopian65ab4712010-07-14 17:59:35 -07004298void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4299 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004300 size_t frameSize = cblk->frameSize;
4301 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4302 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004303
4304 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004305 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4306 "TrackBase::getBuffer buffer out of range:\n"
4307 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4308 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004309 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004310 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004311
4312 return bufferStart;
4313}
4314
Eric Laurenta011e352012-03-29 15:51:43 -07004315status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4316{
4317 mSyncEvents.add(event);
4318 return NO_ERROR;
4319}
4320
Mathias Agopian65ab4712010-07-14 17:59:35 -07004321// ----------------------------------------------------------------------------
4322
4323// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4324AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004325 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004326 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004327 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004328 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004329 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004330 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004331 int frameCount,
4332 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004333 int sessionId,
4334 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004335 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004336 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004337 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004338 // mRetryCount initialized later when needed
4339 mSharedBuffer(sharedBuffer),
4340 mStreamType(streamType),
4341 mName(-1), // see note below
4342 mMainBuffer(thread->mixBuffer()),
4343 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004344 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004345 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004346 mFlags(flags),
4347 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004348 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004349 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004350{
4351 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004352 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4353 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004354 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004355 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07004356 mName = thread->getTrackName_l(channelMask, sessionId);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004357 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004358 if (mName < 0) {
4359 ALOGE("no more track names available");
4360 return;
4361 }
4362 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004363 if (flags & IAudioFlinger::TRACK_FAST) {
4364 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4365 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4366 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004367 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004368 // FIXME This is too eager. We allocate a fast track index before the
4369 // fast track becomes active. Since fast tracks are a scarce resource,
4370 // this means we are potentially denying other more important fast tracks from
4371 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004372 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004373 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004374 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004375 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004376 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004377 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004378 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004379 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004380}
4381
4382AudioFlinger::PlaybackThread::Track::~Track()
4383{
Steve Block3856b092011-10-20 11:56:00 +01004384 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004385}
4386
4387void AudioFlinger::PlaybackThread::Track::destroy()
4388{
4389 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4390 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004391 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004392 // we must acquire a strong reference on this Track before locking mLock
4393 // here so that the destructor is called only when exiting this function.
4394 // On the other hand, as long as Track::destroy() is only called by
4395 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4396 // this Track with its member mTrack.
4397 sp<Track> keep(this);
4398 { // scope for mLock
4399 sp<ThreadBase> thread = mThread.promote();
4400 if (thread != 0) {
4401 if (!isOutputTrack()) {
4402 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004403 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004404
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004405#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004406 // to track the speaker usage
4407 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004408#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004409 }
4410 AudioSystem::releaseOutput(thread->id());
4411 }
4412 Mutex::Autolock _l(thread->mLock);
4413 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4414 playbackThread->destroyTrack_l(this);
4415 }
4416 }
4417}
4418
Glenn Kasten288ed212012-04-25 17:52:27 -07004419/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4420{
Glenn Kastene213c862012-04-25 13:46:15 -07004421 result.append(" Name Client Type Fmt Chn mask Session mFrCnt fCount S M F SRate L dB R dB "
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07004422 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004423}
4424
Mathias Agopian65ab4712010-07-14 17:59:35 -07004425void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4426{
Glenn Kasten83d86532012-01-17 14:39:34 -08004427 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004428 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004429 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004430 } else {
4431 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4432 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004433 track_state state = mState;
4434 char stateChar;
4435 switch (state) {
4436 case IDLE:
4437 stateChar = 'I';
4438 break;
4439 case TERMINATED:
4440 stateChar = 'T';
4441 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004442 case STOPPING_1:
4443 stateChar = 's';
4444 break;
4445 case STOPPING_2:
4446 stateChar = '5';
4447 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004448 case STOPPED:
4449 stateChar = 'S';
4450 break;
4451 case RESUMING:
4452 stateChar = 'R';
4453 break;
4454 case ACTIVE:
4455 stateChar = 'A';
4456 break;
4457 case PAUSING:
4458 stateChar = 'p';
4459 break;
4460 case PAUSED:
4461 stateChar = 'P';
4462 break;
Eric Laurent29864602012-05-08 18:57:51 -07004463 case FLUSHED:
4464 stateChar = 'F';
4465 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004466 default:
4467 stateChar = '?';
4468 break;
4469 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004470 char nowInUnderrun;
4471 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4472 case UNDERRUN_FULL:
4473 nowInUnderrun = ' ';
4474 break;
4475 case UNDERRUN_PARTIAL:
4476 nowInUnderrun = '<';
4477 break;
4478 case UNDERRUN_EMPTY:
4479 nowInUnderrun = '*';
4480 break;
4481 default:
4482 nowInUnderrun = '?';
4483 break;
4484 }
Glenn Kastene213c862012-04-25 13:46:15 -07004485 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4486 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004487 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004488 mStreamType,
4489 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004490 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004491 mSessionId,
4492 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004493 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004494 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004495 mMute,
4496 mFillingUpStatus,
4497 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004498 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4499 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004500 mCblk->server,
4501 mCblk->user,
4502 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004503 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004504 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004505 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004506 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004507}
4508
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004509// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004510status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004511 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004512{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004513 audio_track_cblk_t* cblk = this->cblk();
4514 uint32_t framesReady;
4515 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004516
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004517 // Check if last stepServer failed, try to step now
4518 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004519 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4520 // Since the fast mixer is higher priority than client callback thread,
4521 // it does not result in priority inversion for client.
4522 // But a non-blocking solution would be preferable to avoid
4523 // fast mixer being unable to tryLock(), and
4524 // to avoid the extra context switches if the client wakes up,
4525 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004526 if (!step()) goto getNextBuffer_exit;
4527 ALOGV("stepServer recovered");
4528 mStepServerFailed = false;
4529 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004530
Glenn Kasten288ed212012-04-25 17:52:27 -07004531 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004532 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004533
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004534 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004535 uint32_t s = cblk->server;
4536 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4537
4538 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4539 if (framesReq > framesReady) {
4540 framesReq = framesReady;
4541 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004542 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004543 framesReq = bufferEnd - s;
4544 }
4545
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004546 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004547 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004548 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004549 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004550
4551getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004552 buffer->raw = NULL;
4553 buffer->frameCount = 0;
4554 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4555 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004556}
4557
Glenn Kasten288ed212012-04-25 17:52:27 -07004558// Note that framesReady() takes a mutex on the control block using tryLock().
4559// This could result in priority inversion if framesReady() is called by the normal mixer,
4560// as the normal mixer thread runs at lower
4561// priority than the client's callback thread: there is a short window within framesReady()
4562// during which the normal mixer could be preempted, and the client callback would block.
4563// Another problem can occur if framesReady() is called by the fast mixer:
4564// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4565// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4566size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004567 return mCblk->framesReady();
4568}
4569
Glenn Kasten288ed212012-04-25 17:52:27 -07004570// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004571bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004572 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004573
John Grossman4ff14ba2012-02-08 16:37:41 -08004574 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004575 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4576 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004577 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004578 return true;
4579 }
4580 return false;
4581}
4582
Glenn Kasten3acbd052012-02-28 10:39:56 -08004583status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004584 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004585{
4586 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004587 ALOGV("start(%d), calling pid %d session %d",
4588 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004589
Mathias Agopian65ab4712010-07-14 17:59:35 -07004590 sp<ThreadBase> thread = mThread.promote();
4591 if (thread != 0) {
4592 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004593 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004594 // here the track could be either new, or restarted
4595 // in both cases "unstop" the track
4596 if (mState == PAUSED) {
4597 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004598 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004599 } else {
4600 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004601 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004602 }
4603
4604 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4605 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004606 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004607 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004608
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004609#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004610 // to track the speaker usage
4611 if (status == NO_ERROR) {
4612 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4613 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004614#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004615 }
4616 if (status == NO_ERROR) {
4617 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4618 playbackThread->addTrack_l(this);
4619 } else {
4620 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004621 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004622 }
4623 } else {
4624 status = BAD_VALUE;
4625 }
4626 return status;
4627}
4628
4629void AudioFlinger::PlaybackThread::Track::stop()
4630{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004631 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004632 sp<ThreadBase> thread = mThread.promote();
4633 if (thread != 0) {
4634 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004635 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004636 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004637 // If the track is not active (PAUSED and buffers full), flush buffers
4638 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4639 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4640 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004641 mState = STOPPED;
4642 } else if (!isFastTrack()) {
4643 mState = STOPPED;
4644 } else {
4645 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4646 // and then to STOPPED and reset() when presentation is complete
4647 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004648 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004649 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004650 }
4651 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4652 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004653 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004654 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004655
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004656#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004657 // to track the speaker usage
4658 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004659#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004660 }
4661 }
4662}
4663
4664void AudioFlinger::PlaybackThread::Track::pause()
4665{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004666 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004667 sp<ThreadBase> thread = mThread.promote();
4668 if (thread != 0) {
4669 Mutex::Autolock _l(thread->mLock);
4670 if (mState == ACTIVE || mState == RESUMING) {
4671 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004672 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004673 if (!isOutputTrack()) {
4674 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004675 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004676 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004677
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004678#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004679 // to track the speaker usage
4680 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004681#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004682 }
4683 }
4684 }
4685}
4686
4687void AudioFlinger::PlaybackThread::Track::flush()
4688{
Steve Block3856b092011-10-20 11:56:00 +01004689 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004690 sp<ThreadBase> thread = mThread.promote();
4691 if (thread != 0) {
4692 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004693 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4694 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004695 return;
4696 }
4697 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004698 // FLUSHED state
4699 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004700 // do not reset the track if it is still in the process of being stopped or paused.
4701 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004702 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004703 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004704 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4705 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4706 reset();
4707 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004708 }
4709}
4710
4711void AudioFlinger::PlaybackThread::Track::reset()
4712{
4713 // Do not reset twice to avoid discarding data written just after a flush and before
4714 // the audioflinger thread detects the track is stopped.
4715 if (!mResetDone) {
4716 TrackBase::reset();
4717 // Force underrun condition to avoid false underrun callback until first data is
4718 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004719 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4720 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004721 mFillingUpStatus = FS_FILLING;
4722 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004723 if (mState == FLUSHED) {
4724 mState = IDLE;
4725 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004726 }
4727}
4728
4729void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4730{
4731 mMute = muted;
4732}
4733
Mathias Agopian65ab4712010-07-14 17:59:35 -07004734status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4735{
4736 status_t status = DEAD_OBJECT;
4737 sp<ThreadBase> thread = mThread.promote();
4738 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004739 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004740 sp<AudioFlinger> af = mClient->audioFlinger();
4741
4742 Mutex::Autolock _l(af->mLock);
4743
4744 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004745
Eric Laurent109347d2012-07-02 12:31:03 -07004746 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004747 Mutex::Autolock _dl(playbackThread->mLock);
4748 Mutex::Autolock _sl(srcThread->mLock);
4749 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4750 if (chain == 0) {
4751 return INVALID_OPERATION;
4752 }
4753
4754 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4755 if (effect == 0) {
4756 return INVALID_OPERATION;
4757 }
4758 srcThread->removeEffect_l(effect);
4759 playbackThread->addEffect_l(effect);
4760 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4761 if (effect->state() == EffectModule::ACTIVE ||
4762 effect->state() == EffectModule::STOPPING) {
4763 effect->start();
4764 }
4765
4766 sp<EffectChain> dstChain = effect->chain().promote();
4767 if (dstChain == 0) {
4768 srcThread->addEffect_l(effect);
4769 return INVALID_OPERATION;
4770 }
4771 AudioSystem::unregisterEffect(effect->id());
4772 AudioSystem::registerEffect(&effect->desc(),
4773 srcThread->id(),
4774 dstChain->strategy(),
4775 AUDIO_SESSION_OUTPUT_MIX,
4776 effect->id());
4777 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004778 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004779 }
4780 return status;
4781}
4782
4783void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4784{
4785 mAuxEffectId = EffectId;
4786 mAuxBuffer = buffer;
4787}
4788
Eric Laurenta011e352012-03-29 15:51:43 -07004789bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4790 size_t audioHalFrames)
4791{
4792 // a track is considered presented when the total number of frames written to audio HAL
4793 // corresponds to the number of frames written when presentationComplete() is called for the
4794 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4795 if (mPresentationCompleteFrames == 0) {
4796 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4797 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4798 mPresentationCompleteFrames, audioHalFrames);
4799 }
4800 if (framesWritten >= mPresentationCompleteFrames) {
4801 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4802 mSessionId, framesWritten);
4803 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004804 return true;
4805 }
4806 return false;
4807}
4808
4809void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4810{
4811 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4812 if (mSyncEvents[i]->type() == type) {
4813 mSyncEvents[i]->trigger();
4814 mSyncEvents.removeAt(i);
4815 i--;
4816 }
4817 }
4818}
4819
Glenn Kasten58912562012-04-03 10:45:00 -07004820// implement VolumeBufferProvider interface
4821
4822uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4823{
4824 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4825 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4826 uint32_t vlr = mCblk->getVolumeLR();
4827 uint32_t vl = vlr & 0xFFFF;
4828 uint32_t vr = vlr >> 16;
4829 // track volumes come from shared memory, so can't be trusted and must be clamped
4830 if (vl > MAX_GAIN_INT) {
4831 vl = MAX_GAIN_INT;
4832 }
4833 if (vr > MAX_GAIN_INT) {
4834 vr = MAX_GAIN_INT;
4835 }
4836 // now apply the cached master volume and stream type volume;
4837 // this is trusted but lacks any synchronization or barrier so may be stale
4838 float v = mCachedVolume;
4839 vl *= v;
4840 vr *= v;
4841 // re-combine into U4.16
4842 vlr = (vr << 16) | (vl & 0xFFFF);
4843 // FIXME look at mute, pause, and stop flags
4844 return vlr;
4845}
Eric Laurenta011e352012-03-29 15:51:43 -07004846
Eric Laurent29864602012-05-08 18:57:51 -07004847status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4848{
4849 if (mState == TERMINATED || mState == PAUSED ||
4850 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4851 (mState == STOPPED)))) {
4852 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4853 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4854 event->cancel();
4855 return INVALID_OPERATION;
4856 }
Glenn Kastend23eedc2012-08-02 13:35:47 -07004857 (void) TrackBase::setSyncEvent(event);
Eric Laurent29864602012-05-08 18:57:51 -07004858 return NO_ERROR;
4859}
4860
John Grossman4ff14ba2012-02-08 16:37:41 -08004861// timed audio tracks
4862
4863sp<AudioFlinger::PlaybackThread::TimedTrack>
4864AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004865 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004866 const sp<Client>& client,
4867 audio_stream_type_t streamType,
4868 uint32_t sampleRate,
4869 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004870 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004871 int frameCount,
4872 const sp<IMemory>& sharedBuffer,
4873 int sessionId) {
4874 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004875 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004876
Glenn Kastena0356762012-03-19 10:38:51 -07004877 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004878 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4879 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004880}
4881
4882AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004883 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004884 const sp<Client>& client,
4885 audio_stream_type_t streamType,
4886 uint32_t sampleRate,
4887 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004888 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004889 int frameCount,
4890 const sp<IMemory>& sharedBuffer,
4891 int sessionId)
4892 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004893 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004894 mQueueHeadInFlight(false),
4895 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004896 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004897 mTimedSilenceBuffer(NULL),
4898 mTimedSilenceBufferSize(0),
4899 mTimedAudioOutputOnTime(false),
4900 mMediaTimeTransformValid(false)
4901{
4902 LocalClock lc;
4903 mLocalTimeFreq = lc.getLocalFreq();
4904
4905 mLocalTimeToSampleTransform.a_zero = 0;
4906 mLocalTimeToSampleTransform.b_zero = 0;
4907 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4908 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4909 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4910 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004911
4912 mMediaTimeToSampleTransform.a_zero = 0;
4913 mMediaTimeToSampleTransform.b_zero = 0;
4914 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4915 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4916 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4917 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004918}
4919
4920AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4921 mClient->releaseTimedTrack();
4922 delete [] mTimedSilenceBuffer;
4923}
4924
4925status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4926 size_t size, sp<IMemory>* buffer) {
4927
4928 Mutex::Autolock _l(mTimedBufferQueueLock);
4929
4930 trimTimedBufferQueue_l();
4931
4932 // lazily initialize the shared memory heap for timed buffers
4933 if (mTimedMemoryDealer == NULL) {
4934 const int kTimedBufferHeapSize = 512 << 10;
4935
4936 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4937 "AudioFlingerTimed");
4938 if (mTimedMemoryDealer == NULL)
4939 return NO_MEMORY;
4940 }
4941
4942 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4943 if (newBuffer == NULL) {
4944 newBuffer = mTimedMemoryDealer->allocate(size);
4945 if (newBuffer == NULL)
4946 return NO_MEMORY;
4947 }
4948
4949 *buffer = newBuffer;
4950 return NO_ERROR;
4951}
4952
4953// caller must hold mTimedBufferQueueLock
4954void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4955 int64_t mediaTimeNow;
4956 {
4957 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4958 if (!mMediaTimeTransformValid)
4959 return;
4960
4961 int64_t targetTimeNow;
4962 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4963 ? mCCHelper.getCommonTime(&targetTimeNow)
4964 : mCCHelper.getLocalTime(&targetTimeNow);
4965
4966 if (OK != res)
4967 return;
4968
4969 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4970 &mediaTimeNow)) {
4971 return;
4972 }
4973 }
4974
John Grossman1c345192012-03-27 14:00:17 -07004975 size_t trimEnd;
4976 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004977 int64_t bufEnd;
4978
John Grossmanc95cfbb2012-04-12 11:53:11 -07004979 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4980 // We have a next buffer. Just use its PTS as the PTS of the frame
4981 // following the last frame in this buffer. If the stream is sparse
4982 // (ie, there are deliberate gaps left in the stream which should be
4983 // filled with silence by the TimedAudioTrack), then this can result
4984 // in one extra buffer being left un-trimmed when it could have
4985 // been. In general, this is not typical, and we would rather
4986 // optimized away the TS calculation below for the more common case
4987 // where PTSes are contiguous.
4988 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4989 } else {
4990 // We have no next buffer. Compute the PTS of the frame following
4991 // the last frame in this buffer by computing the duration of of
4992 // this frame in media time units and adding it to the PTS of the
4993 // buffer.
4994 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4995 / mCblk->frameSize;
4996
4997 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4998 &bufEnd)) {
4999 ALOGE("Failed to convert frame count of %lld to media time"
5000 " duration" " (scale factor %d/%u) in %s",
5001 frameCount,
5002 mMediaTimeToSampleTransform.a_to_b_numer,
5003 mMediaTimeToSampleTransform.a_to_b_denom,
5004 __PRETTY_FUNCTION__);
5005 break;
5006 }
5007 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07005008 }
John Grossman9fbdee12012-03-26 17:51:46 -07005009
5010 if (bufEnd > mediaTimeNow)
5011 break;
5012
5013 // Is the buffer we want to use in the middle of a mix operation right
5014 // now? If so, don't actually trim it. Just wait for the releaseBuffer
5015 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07005016 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07005017 mTrimQueueHeadOnRelease = true;
5018 }
John Grossman4ff14ba2012-02-08 16:37:41 -08005019 }
5020
John Grossman9fbdee12012-03-26 17:51:46 -07005021 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07005022 if (trimStart < trimEnd) {
5023 // Update the bookkeeping for framesReady()
5024 for (size_t i = trimStart; i < trimEnd; ++i) {
5025 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
5026 }
5027
5028 // Now actually remove the buffers from the queue.
5029 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08005030 }
5031}
5032
John Grossman1c345192012-03-27 14:00:17 -07005033void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
5034 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07005035 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
5036 "%s called (reason \"%s\"), but timed buffer queue has no"
5037 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005038
5039 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
5040 mTimedBufferQueue.removeAt(0);
5041}
5042
5043void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
5044 const TimedBuffer& buf,
5045 const char* logTag) {
5046 uint32_t bufBytes = buf.buffer()->size();
5047 uint32_t consumedAlready = buf.position();
5048
Eric Laurentb388e532012-04-14 13:32:48 -07005049 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07005050 "Bad bookkeeping while updating frames pending. Timed buffer is"
5051 " only %u bytes long, but claims to have consumed %u"
5052 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07005053 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005054
5055 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07005056 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5057 "Bad bookkeeping while updating frames pending. Should have at"
5058 " least %u queued frames, but we think we have only %u. (update"
5059 " reason: \"%s\")",
5060 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005061
5062 mFramesPendingInQueue -= bufFrames;
5063}
5064
John Grossman4ff14ba2012-02-08 16:37:41 -08005065status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5066 const sp<IMemory>& buffer, int64_t pts) {
5067
5068 {
5069 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5070 if (!mMediaTimeTransformValid)
5071 return INVALID_OPERATION;
5072 }
5073
5074 Mutex::Autolock _l(mTimedBufferQueueLock);
5075
John Grossman1c345192012-03-27 14:00:17 -07005076 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5077 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005078 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5079
5080 return NO_ERROR;
5081}
5082
5083status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5084 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5085
John Grossman1c345192012-03-27 14:00:17 -07005086 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5087 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5088 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005089
5090 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5091 target == TimedAudioTrack::COMMON_TIME)) {
5092 return BAD_VALUE;
5093 }
5094
5095 Mutex::Autolock lock(mMediaTimeTransformLock);
5096 mMediaTimeTransform = xform;
5097 mMediaTimeTransformTarget = target;
5098 mMediaTimeTransformValid = true;
5099
5100 return NO_ERROR;
5101}
5102
5103#define min(a, b) ((a) < (b) ? (a) : (b))
5104
5105// implementation of getNextBuffer for tracks whose buffers have timestamps
5106status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5107 AudioBufferProvider::Buffer* buffer, int64_t pts)
5108{
5109 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005110 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005111 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005112 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005113 return INVALID_OPERATION;
5114 }
5115
John Grossman4ff14ba2012-02-08 16:37:41 -08005116 Mutex::Autolock _l(mTimedBufferQueueLock);
5117
John Grossman9fbdee12012-03-26 17:51:46 -07005118 ALOG_ASSERT(!mQueueHeadInFlight,
5119 "getNextBuffer called without releaseBuffer!");
5120
John Grossman4ff14ba2012-02-08 16:37:41 -08005121 while (true) {
5122
5123 // if we have no timed buffers, then fail
5124 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005125 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005126 buffer->frameCount = 0;
5127 return NOT_ENOUGH_DATA;
5128 }
5129
5130 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5131
5132 // calculate the PTS of the head of the timed buffer queue expressed in
5133 // local time
5134 int64_t headLocalPTS;
5135 {
5136 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5137
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005138 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005139
5140 if (mMediaTimeTransform.a_to_b_denom == 0) {
5141 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005142 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005143 return NO_ERROR;
5144 }
5145
5146 int64_t transformedPTS;
5147 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5148 &transformedPTS)) {
5149 // the transform failed. this shouldn't happen, but if it does
5150 // then just drop this buffer
5151 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005152 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005153 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005154 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005155 return NO_ERROR;
5156 }
5157
5158 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5159 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5160 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005161 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005162 buffer->frameCount = 0;
5163 return INVALID_OPERATION;
5164 }
5165 } else {
5166 headLocalPTS = transformedPTS;
5167 }
5168 }
5169
5170 // adjust the head buffer's PTS to reflect the portion of the head buffer
5171 // that has already been consumed
5172 int64_t effectivePTS = headLocalPTS +
5173 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5174
5175 // Calculate the delta in samples between the head of the input buffer
5176 // queue and the start of the next output buffer that will be written.
5177 // If the transformation fails because of over or underflow, it means
5178 // that the sample's position in the output stream is so far out of
5179 // whack that it should just be dropped.
5180 int64_t sampleDelta;
5181 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5182 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005183 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5184 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005185 continue;
5186 }
5187 if (!mLocalTimeToSampleTransform.doForwardTransform(
5188 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005189 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005190 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005191 continue;
5192 }
5193
John Grossman1c345192012-03-27 14:00:17 -07005194 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5195 " sampleDelta=[%d.%08x]",
5196 head.pts(), head.position(), pts,
5197 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5198 + (sampleDelta >> 32)),
5199 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005200
5201 // if the delta between the ideal placement for the next input sample and
5202 // the current output position is within this threshold, then we will
5203 // concatenate the next input samples to the previous output
5204 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005205 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005206
5207 // if this is the first buffer of audio that we're emitting from this track
5208 // then it should be almost exactly on time.
5209 const int64_t kSampleStartupThreshold = 1LL << 32;
5210
5211 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005212 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005213 // the next input is close enough to being on time, so concatenate it
5214 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005215 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005216
John Grossman1c345192012-03-27 14:00:17 -07005217 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5218 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005219 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005220 }
5221
5222 // Looks like our output is not on time. Reset our on timed status.
5223 // Next time we mix samples from our input queue, then should be within
5224 // the StartupThreshold.
5225 mTimedAudioOutputOnTime = false;
5226 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005227 // the gap between the current output position and the proper start of
5228 // the next input sample is too big, so fill it with silence
5229 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5230
John Grossman9fbdee12012-03-26 17:51:46 -07005231 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005232 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5233 return NO_ERROR;
5234 } else {
5235 // the next input sample is late
5236 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5237 size_t onTimeSamplePosition =
5238 head.position() + lateFrames * mCblk->frameSize;
5239
5240 if (onTimeSamplePosition > head.buffer()->size()) {
5241 // all the remaining samples in the head are too late, so
5242 // drop it and move on
5243 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005244 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005245 continue;
5246 } else {
5247 // skip over the late samples
5248 head.setPosition(onTimeSamplePosition);
5249
5250 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005251 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005252
5253 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5254 return NO_ERROR;
5255 }
5256 }
5257 }
5258}
5259
5260// Yield samples from the timed buffer queue head up to the given output
5261// buffer's capacity.
5262//
5263// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005264void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005265 AudioBufferProvider::Buffer* buffer) {
5266
5267 const TimedBuffer& head = mTimedBufferQueue[0];
5268
5269 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5270 head.position());
5271
5272 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5273 mCblk->frameSize);
5274 size_t framesRequested = buffer->frameCount;
5275 buffer->frameCount = min(framesLeftInHead, framesRequested);
5276
John Grossman9fbdee12012-03-26 17:51:46 -07005277 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005278 mTimedAudioOutputOnTime = true;
5279}
5280
5281// Yield samples of silence up to the given output buffer's capacity
5282//
5283// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005284void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005285 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5286
5287 // lazily allocate a buffer filled with silence
5288 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5289 delete [] mTimedSilenceBuffer;
5290 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5291 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5292 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5293 }
5294
5295 buffer->raw = mTimedSilenceBuffer;
5296 size_t framesRequested = buffer->frameCount;
5297 buffer->frameCount = min(numFrames, framesRequested);
5298
5299 mTimedAudioOutputOnTime = false;
5300}
5301
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005302// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005303void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5304 AudioBufferProvider::Buffer* buffer) {
5305
5306 Mutex::Autolock _l(mTimedBufferQueueLock);
5307
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005308 // If the buffer which was just released is part of the buffer at the head
5309 // of the queue, be sure to update the amt of the buffer which has been
5310 // consumed. If the buffer being returned is not part of the head of the
5311 // queue, its either because the buffer is part of the silence buffer, or
5312 // because the head of the timed queue was trimmed after the mixer called
5313 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005314 if (buffer->raw == mTimedSilenceBuffer) {
5315 ALOG_ASSERT(!mQueueHeadInFlight,
5316 "Queue head in flight during release of silence buffer!");
5317 goto done;
5318 }
5319
5320 ALOG_ASSERT(mQueueHeadInFlight,
5321 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5322 " head in flight.");
5323
5324 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005325 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005326
5327 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005328 void* end = reinterpret_cast<void*>(
5329 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5330 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005331
John Grossman9fbdee12012-03-26 17:51:46 -07005332 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5333 "released buffer not within the head of the timed buffer"
5334 " queue; qHead = [%p, %p], released buffer = %p",
5335 start, end, buffer->raw);
5336
5337 head.setPosition(head.position() +
5338 (buffer->frameCount * mCblk->frameSize));
5339 mQueueHeadInFlight = false;
5340
John Grossman1c345192012-03-27 14:00:17 -07005341 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5342 "Bad bookkeeping during releaseBuffer! Should have at"
5343 " least %u queued frames, but we think we have only %u",
5344 buffer->frameCount, mFramesPendingInQueue);
5345
5346 mFramesPendingInQueue -= buffer->frameCount;
5347
John Grossman9fbdee12012-03-26 17:51:46 -07005348 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5349 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005350 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005351 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005352 }
John Grossman9fbdee12012-03-26 17:51:46 -07005353 } else {
5354 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5355 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005356 }
5357
John Grossman9fbdee12012-03-26 17:51:46 -07005358done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005359 buffer->raw = 0;
5360 buffer->frameCount = 0;
5361}
5362
Glenn Kasten288ed212012-04-25 17:52:27 -07005363size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005364 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005365 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005366}
5367
5368AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5369 : mPTS(0), mPosition(0) {}
5370
5371AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5372 const sp<IMemory>& buffer, int64_t pts)
5373 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5374
Mathias Agopian65ab4712010-07-14 17:59:35 -07005375// ----------------------------------------------------------------------------
5376
5377// RecordTrack constructor must be called with AudioFlinger::mLock held
5378AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005379 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005380 const sp<Client>& client,
5381 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005382 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005383 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005384 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005385 int sessionId)
5386 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005387 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005388 mOverflow(false)
5389{
5390 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005391 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5392 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5393 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5394 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5395 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5396 } else {
5397 mCblk->frameSize = sizeof(int8_t);
5398 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005399 }
5400}
5401
5402AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5403{
Glenn Kasten510a3d62012-07-16 14:24:34 -07005404 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005405}
5406
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005407// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005408status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005409{
5410 audio_track_cblk_t* cblk = this->cblk();
5411 uint32_t framesAvail;
5412 uint32_t framesReq = buffer->frameCount;
5413
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005414 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005415 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005416 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005417 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005418 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005419 }
5420
5421 framesAvail = cblk->framesAvailable_l();
5422
Glenn Kastenf6b16782011-12-15 09:51:17 -08005423 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005424 uint32_t s = cblk->server;
5425 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5426
5427 if (framesReq > framesAvail) {
5428 framesReq = framesAvail;
5429 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005430 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005431 framesReq = bufferEnd - s;
5432 }
5433
5434 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005435 buffer->frameCount = framesReq;
5436 return NO_ERROR;
5437 }
5438
5439getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005440 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005441 buffer->frameCount = 0;
5442 return NOT_ENOUGH_DATA;
5443}
5444
Glenn Kasten3acbd052012-02-28 10:39:56 -08005445status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005446 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005447{
5448 sp<ThreadBase> thread = mThread.promote();
5449 if (thread != 0) {
5450 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005451 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005452 } else {
5453 return BAD_VALUE;
5454 }
5455}
5456
5457void AudioFlinger::RecordThread::RecordTrack::stop()
5458{
5459 sp<ThreadBase> thread = mThread.promote();
5460 if (thread != 0) {
5461 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005462 recordThread->mLock.lock();
5463 bool doStop = recordThread->stop_l(this);
5464 if (doStop) {
5465 TrackBase::reset();
5466 // Force overrun condition to avoid false overrun callback until first data is
5467 // read from buffer
5468 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5469 }
5470 recordThread->mLock.unlock();
5471 if (doStop) {
5472 AudioSystem::stopInput(recordThread->id());
5473 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005474 }
5475}
5476
Glenn Kasten510a3d62012-07-16 14:24:34 -07005477/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
5478{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005479 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User FrameCount\n");
Glenn Kasten510a3d62012-07-16 14:24:34 -07005480}
5481
Mathias Agopian65ab4712010-07-14 17:59:35 -07005482void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5483{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005484 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x %05d\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005485 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005486 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005487 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005488 mSessionId,
5489 mFrameCount,
5490 mState,
5491 mCblk->sampleRate,
5492 mCblk->server,
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005493 mCblk->user,
5494 mCblk->frameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005495}
5496
5497
5498// ----------------------------------------------------------------------------
5499
5500AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005501 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005502 DuplicatingThread *sourceThread,
5503 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005504 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005505 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005506 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005507 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5508 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005509 mActive(false), mSourceThread(sourceThread)
5510{
5511
Mathias Agopian65ab4712010-07-14 17:59:35 -07005512 if (mCblk != NULL) {
5513 mCblk->flags |= CBLK_DIRECTION_OUT;
5514 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005515 mOutBuffer.frameCount = 0;
5516 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005517 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005518 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5519 mCblk, mBuffer, mCblk->buffers,
5520 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005521 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005522 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005523 }
5524}
5525
5526AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5527{
5528 clearBufferQueue();
5529}
5530
Glenn Kasten3acbd052012-02-28 10:39:56 -08005531status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005532 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005533{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005534 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005535 if (status != NO_ERROR) {
5536 return status;
5537 }
5538
5539 mActive = true;
5540 mRetryCount = 127;
5541 return status;
5542}
5543
5544void AudioFlinger::PlaybackThread::OutputTrack::stop()
5545{
5546 Track::stop();
5547 clearBufferQueue();
5548 mOutBuffer.frameCount = 0;
5549 mActive = false;
5550}
5551
5552bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5553{
5554 Buffer *pInBuffer;
5555 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005556 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005557 bool outputBufferFull = false;
5558 inBuffer.frameCount = frames;
5559 inBuffer.i16 = data;
5560
5561 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5562
5563 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005564 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005565 sp<ThreadBase> thread = mThread.promote();
5566 if (thread != 0) {
5567 MixerThread *mixerThread = (MixerThread *)thread.get();
5568 if (mCblk->frameCount > frames){
5569 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5570 uint32_t startFrames = (mCblk->frameCount - frames);
5571 pInBuffer = new Buffer;
5572 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5573 pInBuffer->frameCount = startFrames;
5574 pInBuffer->i16 = pInBuffer->mBuffer;
5575 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5576 mBufferQueue.add(pInBuffer);
5577 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005578 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005579 }
5580 }
5581 }
5582 }
5583
5584 while (waitTimeLeftMs) {
5585 // First write pending buffers, then new data
5586 if (mBufferQueue.size()) {
5587 pInBuffer = mBufferQueue.itemAt(0);
5588 } else {
5589 pInBuffer = &inBuffer;
5590 }
5591
5592 if (pInBuffer->frameCount == 0) {
5593 break;
5594 }
5595
5596 if (mOutBuffer.frameCount == 0) {
5597 mOutBuffer.frameCount = pInBuffer->frameCount;
5598 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005599 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005600 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005601 outputBufferFull = true;
5602 break;
5603 }
5604 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5605 if (waitTimeLeftMs >= waitTimeMs) {
5606 waitTimeLeftMs -= waitTimeMs;
5607 } else {
5608 waitTimeLeftMs = 0;
5609 }
5610 }
5611
5612 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5613 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5614 mCblk->stepUser(outFrames);
5615 pInBuffer->frameCount -= outFrames;
5616 pInBuffer->i16 += outFrames * channelCount;
5617 mOutBuffer.frameCount -= outFrames;
5618 mOutBuffer.i16 += outFrames * channelCount;
5619
5620 if (pInBuffer->frameCount == 0) {
5621 if (mBufferQueue.size()) {
5622 mBufferQueue.removeAt(0);
5623 delete [] pInBuffer->mBuffer;
5624 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005625 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005626 } else {
5627 break;
5628 }
5629 }
5630 }
5631
5632 // If we could not write all frames, allocate a buffer and queue it for next time.
5633 if (inBuffer.frameCount) {
5634 sp<ThreadBase> thread = mThread.promote();
5635 if (thread != 0 && !thread->standby()) {
5636 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5637 pInBuffer = new Buffer;
5638 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5639 pInBuffer->frameCount = inBuffer.frameCount;
5640 pInBuffer->i16 = pInBuffer->mBuffer;
5641 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5642 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005643 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005644 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005645 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005646 }
5647 }
5648 }
5649
5650 // Calling write() with a 0 length buffer, means that no more data will be written:
5651 // If no more buffers are pending, fill output track buffer to make sure it is started
5652 // by output mixer.
5653 if (frames == 0 && mBufferQueue.size() == 0) {
5654 if (mCblk->user < mCblk->frameCount) {
5655 frames = mCblk->frameCount - mCblk->user;
5656 pInBuffer = new Buffer;
5657 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5658 pInBuffer->frameCount = frames;
5659 pInBuffer->i16 = pInBuffer->mBuffer;
5660 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5661 mBufferQueue.add(pInBuffer);
5662 } else if (mActive) {
5663 stop();
5664 }
5665 }
5666
5667 return outputBufferFull;
5668}
5669
5670status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5671{
5672 int active;
5673 status_t result;
5674 audio_track_cblk_t* cblk = mCblk;
5675 uint32_t framesReq = buffer->frameCount;
5676
Steve Block3856b092011-10-20 11:56:00 +01005677// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005678 buffer->frameCount = 0;
5679
5680 uint32_t framesAvail = cblk->framesAvailable();
5681
5682
5683 if (framesAvail == 0) {
5684 Mutex::Autolock _l(cblk->lock);
5685 goto start_loop_here;
5686 while (framesAvail == 0) {
5687 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005688 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005689 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005690 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005691 }
5692 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5693 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005694 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005695 }
5696 // read the server count again
5697 start_loop_here:
5698 framesAvail = cblk->framesAvailable_l();
5699 }
5700 }
5701
5702// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005703// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704// }
5705
5706 if (framesReq > framesAvail) {
5707 framesReq = framesAvail;
5708 }
5709
5710 uint32_t u = cblk->user;
5711 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5712
Marco Nelissena1472d92012-03-30 14:36:54 -07005713 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005714 framesReq = bufferEnd - u;
5715 }
5716
5717 buffer->frameCount = framesReq;
5718 buffer->raw = (void *)cblk->buffer(u);
5719 return NO_ERROR;
5720}
5721
5722
5723void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5724{
5725 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005726
5727 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005728 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005729 delete [] pBuffer->mBuffer;
5730 delete pBuffer;
5731 }
5732 mBufferQueue.clear();
5733}
5734
5735// ----------------------------------------------------------------------------
5736
5737AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5738 : RefBase(),
5739 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005740 // 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 -07005741 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005742 mPid(pid),
5743 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005744{
5745 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5746}
5747
5748// Client destructor must be called with AudioFlinger::mLock held
5749AudioFlinger::Client::~Client()
5750{
5751 mAudioFlinger->removeClient_l(mPid);
5752}
5753
Glenn Kasten435dbe62012-01-30 10:15:48 -08005754sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005755{
5756 return mMemoryDealer;
5757}
5758
John Grossman4ff14ba2012-02-08 16:37:41 -08005759// Reserve one of the limited slots for a timed audio track associated
5760// with this client
5761bool AudioFlinger::Client::reserveTimedTrack()
5762{
5763 const int kMaxTimedTracksPerClient = 4;
5764
5765 Mutex::Autolock _l(mTimedTrackLock);
5766
5767 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5768 ALOGW("can not create timed track - pid %d has exceeded the limit",
5769 mPid);
5770 return false;
5771 }
5772
5773 mTimedTrackCount++;
5774 return true;
5775}
5776
5777// Release a slot for a timed audio track
5778void AudioFlinger::Client::releaseTimedTrack()
5779{
5780 Mutex::Autolock _l(mTimedTrackLock);
5781 mTimedTrackCount--;
5782}
5783
Mathias Agopian65ab4712010-07-14 17:59:35 -07005784// ----------------------------------------------------------------------------
5785
5786AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5787 const sp<IAudioFlingerClient>& client,
5788 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005789 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005790{
5791}
5792
5793AudioFlinger::NotificationClient::~NotificationClient()
5794{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005795}
5796
5797void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5798{
5799 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005800 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005801}
5802
5803// ----------------------------------------------------------------------------
5804
5805AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5806 : BnAudioTrack(),
5807 mTrack(track)
5808{
5809}
5810
5811AudioFlinger::TrackHandle::~TrackHandle() {
5812 // just stop the track on deletion, associated resources
5813 // will be freed from the main thread once all pending buffers have
5814 // been played. Unless it's not in the active track list, in which
5815 // case we free everything now...
5816 mTrack->destroy();
5817}
5818
Glenn Kasten90716c52012-01-26 13:40:12 -08005819sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5820 return mTrack->getCblk();
5821}
5822
Glenn Kasten3acbd052012-02-28 10:39:56 -08005823status_t AudioFlinger::TrackHandle::start() {
5824 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005825}
5826
5827void AudioFlinger::TrackHandle::stop() {
5828 mTrack->stop();
5829}
5830
5831void AudioFlinger::TrackHandle::flush() {
5832 mTrack->flush();
5833}
5834
5835void AudioFlinger::TrackHandle::mute(bool e) {
5836 mTrack->mute(e);
5837}
5838
5839void AudioFlinger::TrackHandle::pause() {
5840 mTrack->pause();
5841}
5842
Mathias Agopian65ab4712010-07-14 17:59:35 -07005843status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5844{
5845 return mTrack->attachAuxEffect(EffectId);
5846}
5847
John Grossman4ff14ba2012-02-08 16:37:41 -08005848status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5849 sp<IMemory>* buffer) {
5850 if (!mTrack->isTimedTrack())
5851 return INVALID_OPERATION;
5852
5853 PlaybackThread::TimedTrack* tt =
5854 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5855 return tt->allocateTimedBuffer(size, buffer);
5856}
5857
5858status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5859 int64_t pts) {
5860 if (!mTrack->isTimedTrack())
5861 return INVALID_OPERATION;
5862
5863 PlaybackThread::TimedTrack* tt =
5864 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5865 return tt->queueTimedBuffer(buffer, pts);
5866}
5867
5868status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5869 const LinearTransform& xform, int target) {
5870
5871 if (!mTrack->isTimedTrack())
5872 return INVALID_OPERATION;
5873
5874 PlaybackThread::TimedTrack* tt =
5875 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5876 return tt->setMediaTimeTransform(
5877 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5878}
5879
Mathias Agopian65ab4712010-07-14 17:59:35 -07005880status_t AudioFlinger::TrackHandle::onTransact(
5881 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5882{
5883 return BnAudioTrack::onTransact(code, data, reply, flags);
5884}
5885
5886// ----------------------------------------------------------------------------
5887
5888sp<IAudioRecord> AudioFlinger::openRecord(
5889 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005890 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005891 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005892 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005893 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005894 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005895 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07005896 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005897 int *sessionId,
5898 status_t *status)
5899{
5900 sp<RecordThread::RecordTrack> recordTrack;
5901 sp<RecordHandle> recordHandle;
5902 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005903 status_t lStatus;
5904 RecordThread *thread;
5905 size_t inFrameCount;
5906 int lSessionId;
5907
5908 // check calling permissions
5909 if (!recordingAllowed()) {
5910 lStatus = PERMISSION_DENIED;
5911 goto Exit;
5912 }
5913
5914 // add client to list
5915 { // scope for mLock
5916 Mutex::Autolock _l(mLock);
5917 thread = checkRecordThread_l(input);
5918 if (thread == NULL) {
5919 lStatus = BAD_VALUE;
5920 goto Exit;
5921 }
5922
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005923 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005924
5925 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005926 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005927 lSessionId = *sessionId;
5928 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005929 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005930 if (sessionId != NULL) {
5931 *sessionId = lSessionId;
5932 }
5933 }
5934 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07005935 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5936 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005937 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005938 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005939 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5940 // destructor is called by the TrackBase destructor with mLock held
5941 client.clear();
5942 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005943 goto Exit;
5944 }
5945
5946 // return to handle to client
5947 recordHandle = new RecordHandle(recordTrack);
5948 lStatus = NO_ERROR;
5949
5950Exit:
5951 if (status) {
5952 *status = lStatus;
5953 }
5954 return recordHandle;
5955}
5956
5957// ----------------------------------------------------------------------------
5958
5959AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5960 : BnAudioRecord(),
5961 mRecordTrack(recordTrack)
5962{
5963}
5964
5965AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005966 stop_nonvirtual();
Glenn Kasten510a3d62012-07-16 14:24:34 -07005967 mRecordTrack->destroy();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005968}
5969
Glenn Kasten90716c52012-01-26 13:40:12 -08005970sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5971 return mRecordTrack->getCblk();
5972}
5973
Glenn Kasten0ec23ce2012-07-10 12:56:08 -07005974status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005975 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005976 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005977}
5978
5979void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005980 stop_nonvirtual();
5981}
5982
5983void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01005984 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005985 mRecordTrack->stop();
5986}
5987
Mathias Agopian65ab4712010-07-14 17:59:35 -07005988status_t AudioFlinger::RecordHandle::onTransact(
5989 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5990{
5991 return BnAudioRecord::onTransact(code, data, reply, flags);
5992}
5993
5994// ----------------------------------------------------------------------------
5995
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005996AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5997 AudioStreamIn *input,
5998 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07005999 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006000 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006001 audio_devices_t device) :
Eric Laurentf1c04f92012-08-28 14:26:53 -07006002 ThreadBase(audioFlinger, id, AUDIO_DEVICE_NONE, device, RECORD),
Glenn Kasten510a3d62012-07-16 14:24:34 -07006003 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006004 // mRsmpInIndex and mInputBytes set by readInputParameters()
Glenn Kasten254af182012-07-03 14:59:05 -07006005 mReqChannelCount(popcount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006006 mReqSampleRate(sampleRate)
6007 // mBytesRead is only meaningful while active, and so is cleared in start()
6008 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006009{
Glenn Kasten480b4682012-02-28 12:30:08 -08006010 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07006011
Mathias Agopian65ab4712010-07-14 17:59:35 -07006012 readInputParameters();
6013}
6014
6015
6016AudioFlinger::RecordThread::~RecordThread()
6017{
6018 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08006019 delete mResampler;
6020 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006021}
6022
6023void AudioFlinger::RecordThread::onFirstRef()
6024{
Eric Laurentfeb0db62011-07-22 09:04:31 -07006025 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006026}
6027
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006028status_t AudioFlinger::RecordThread::readyToRun()
6029{
6030 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00006031 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006032 return status;
6033}
6034
Mathias Agopian65ab4712010-07-14 17:59:35 -07006035bool AudioFlinger::RecordThread::threadLoop()
6036{
6037 AudioBufferProvider::Buffer buffer;
6038 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006039 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006040
Eric Laurent44d98482010-09-30 16:12:31 -07006041 nsecs_t lastWarning = 0;
6042
Glenn Kastene4e2a372012-07-23 12:55:09 -07006043 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07006044 acquireWakeLock();
6045
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07006046 // used to verify we've read at least once before evaluating how many bytes were read
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006047 bool readOnce = false;
6048
Mathias Agopian65ab4712010-07-14 17:59:35 -07006049 // start recording
6050 while (!exitPending()) {
6051
6052 processConfigEvents();
6053
6054 { // scope for mLock
6055 Mutex::Autolock _l(mLock);
6056 checkForNewParameters_l();
6057 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006058 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006059
6060 if (exitPending()) break;
6061
Eric Laurentfeb0db62011-07-22 09:04:31 -07006062 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01006063 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006064 // go to sleep
6065 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006066 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006067 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006068 continue;
6069 }
6070 if (mActiveTrack != 0) {
6071 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006072 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006073 mActiveTrack.clear();
6074 mStartStopCond.broadcast();
6075 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6076 if (mReqChannelCount != mActiveTrack->channelCount()) {
6077 mActiveTrack.clear();
6078 mStartStopCond.broadcast();
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006079 } else if (readOnce) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006080 // record start succeeds only if first read from audio input
6081 // succeeds
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006082 if (mBytesRead >= 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006083 mActiveTrack->mState = TrackBase::ACTIVE;
6084 } else {
6085 mActiveTrack.clear();
6086 }
6087 mStartStopCond.broadcast();
6088 }
6089 mStandby = false;
Glenn Kasten510a3d62012-07-16 14:24:34 -07006090 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
6091 removeTrack_l(mActiveTrack);
6092 mActiveTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006093 }
6094 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006095 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006096 }
6097
6098 if (mActiveTrack != 0) {
6099 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6100 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006101 unlockEffectChains(effectChains);
6102 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006103 continue;
6104 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006105 for (size_t i = 0; i < effectChains.size(); i ++) {
6106 effectChains[i]->process_l();
6107 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006108
Mathias Agopian65ab4712010-07-14 17:59:35 -07006109 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006110 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006111 readOnce = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006112 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006113 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006114 // no resampling
6115 while (framesOut) {
6116 size_t framesIn = mFrameCount - mRsmpInIndex;
6117 if (framesIn) {
6118 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6119 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6120 if (framesIn > framesOut)
6121 framesIn = framesOut;
6122 mRsmpInIndex += framesIn;
6123 framesOut -= framesIn;
6124 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006125 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006126 memcpy(dst, src, framesIn * mFrameSize);
6127 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006128 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006129 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6130 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006131 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006132 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6133 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006134 }
6135 }
6136 }
6137 if (framesOut && mFrameCount == mRsmpInIndex) {
6138 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006139 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006140 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006141 framesOut = 0;
6142 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006143 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006144 mRsmpInIndex = 0;
6145 }
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006146 if (mBytesRead <= 0) {
6147 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
6148 {
6149 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006150 // Force input into standby so that it tries to
6151 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006152 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006153 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006154 }
6155 mRsmpInIndex = mFrameCount;
6156 framesOut = 0;
6157 buffer.frameCount = 0;
6158 }
6159 }
6160 }
6161 } else {
6162 // resampling
6163
6164 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6165 // alter output frame count as if we were expecting stereo samples
6166 if (mChannelCount == 1 && mReqChannelCount == 1) {
6167 framesOut >>= 1;
6168 }
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07006169 mResampler->resample(mRsmpOutBuffer, framesOut, this /* AudioBufferProvider* */);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006170 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6171 // are 32 bit aligned which should be always true.
6172 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006173 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006174 // the resampler always outputs stereo samples: do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006175 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6176 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006177 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006178 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006179 }
6180
6181 }
Eric Laurenta011e352012-03-29 15:51:43 -07006182 if (mFramestoDrop == 0) {
6183 mActiveTrack->releaseBuffer(&buffer);
6184 } else {
6185 if (mFramestoDrop > 0) {
6186 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006187 if (mFramestoDrop <= 0) {
6188 clearSyncStartEvent();
6189 }
6190 } else {
6191 mFramestoDrop += buffer.frameCount;
6192 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6193 mSyncStartEvent->isCancelled()) {
6194 ALOGW("Synced record %s, session %d, trigger session %d",
6195 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6196 mActiveTrack->sessionId(),
6197 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6198 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006199 }
6200 }
6201 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006202 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006203 }
6204 // client isn't retrieving buffers fast enough
6205 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006206 if (!mActiveTrack->setOverflow()) {
6207 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006208 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006209 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006210 lastWarning = now;
6211 }
6212 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006213 // Release the processor for a while before asking for a new buffer.
6214 // This will give the application more chance to read from the buffer and
6215 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006216 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006217 }
6218 }
Eric Laurentec437d82011-07-26 20:54:46 -07006219 // enable changes in effect chain
6220 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006221 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006222 }
6223
Glenn Kastene4e2a372012-07-23 12:55:09 -07006224 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006225
Glenn Kasten33e6e352012-07-16 15:56:57 -07006226 {
6227 Mutex::Autolock _l(mLock);
6228 mActiveTrack.clear();
6229 mStartStopCond.broadcast();
6230 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006231
Eric Laurentfeb0db62011-07-22 09:04:31 -07006232 releaseWakeLock();
6233
Steve Block3856b092011-10-20 11:56:00 +01006234 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006235 return false;
6236}
6237
Glenn Kastene4e2a372012-07-23 12:55:09 -07006238void AudioFlinger::RecordThread::standby()
6239{
6240 if (!mStandby) {
6241 inputStandBy();
6242 mStandby = true;
6243 }
6244}
6245
6246void AudioFlinger::RecordThread::inputStandBy()
6247{
6248 mInput->stream->common.standby(&mInput->stream->common);
6249}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006250
6251sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6252 const sp<AudioFlinger::Client>& client,
6253 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006254 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006255 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006256 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006257 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006258 IAudioFlinger::track_flags_t flags,
6259 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006260 status_t *status)
6261{
6262 sp<RecordTrack> track;
6263 status_t lStatus;
6264
6265 lStatus = initCheck();
6266 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006267 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006268 goto Exit;
6269 }
6270
Glenn Kasten1879fff2012-07-11 15:36:59 -07006271 // FIXME use flags and tid similar to createTrack_l()
6272
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006273 { // scope for mLock
6274 Mutex::Autolock _l(mLock);
6275
6276 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006277 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006278
Glenn Kasten7378ca52012-01-20 13:44:40 -08006279 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006280 lStatus = NO_MEMORY;
6281 goto Exit;
6282 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006283 mTracks.add(track);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006284
Eric Laurent59bd0da2011-08-01 09:52:20 -07006285 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1c04f92012-08-28 14:26:53 -07006286 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006287 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006288 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6289 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006290 }
6291 lStatus = NO_ERROR;
6292
6293Exit:
6294 if (status) {
6295 *status = lStatus;
6296 }
6297 return track;
6298}
6299
Eric Laurenta011e352012-03-29 15:51:43 -07006300status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006301 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006302 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006303{
Glenn Kasten58912562012-04-03 10:45:00 -07006304 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006305 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006306 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006307
6308 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006309 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006310 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6311 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6312 triggerSession,
6313 recordTrack->sessionId(),
6314 syncStartEventCallback,
6315 this);
Eric Laurent29864602012-05-08 18:57:51 -07006316 // Sync event can be cancelled by the trigger session if the track is not in a
6317 // compatible state in which case we start record immediately
6318 if (mSyncStartEvent->isCancelled()) {
6319 clearSyncStartEvent();
6320 } else {
6321 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6322 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6323 }
Eric Laurenta011e352012-03-29 15:51:43 -07006324 }
6325
Mathias Agopian65ab4712010-07-14 17:59:35 -07006326 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006327 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006328 if (mActiveTrack != 0) {
6329 if (recordTrack != mActiveTrack.get()) {
6330 status = -EBUSY;
6331 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6332 mActiveTrack->mState = TrackBase::ACTIVE;
6333 }
6334 return status;
6335 }
6336
6337 recordTrack->mState = TrackBase::IDLE;
6338 mActiveTrack = recordTrack;
6339 mLock.unlock();
6340 status_t status = AudioSystem::startInput(mId);
6341 mLock.lock();
6342 if (status != NO_ERROR) {
6343 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006344 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006345 return status;
6346 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006347 mRsmpInIndex = mFrameCount;
6348 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006349 if (mResampler != NULL) {
6350 mResampler->reset();
6351 }
6352 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006353 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006354 ALOGV("Signal record thread");
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07006355 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006356 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006357 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006358 mActiveTrack.clear();
6359 status = INVALID_OPERATION;
6360 goto startError;
6361 }
6362 mStartStopCond.wait(mLock);
6363 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006364 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006365 status = BAD_VALUE;
6366 goto startError;
6367 }
Steve Block3856b092011-10-20 11:56:00 +01006368 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006369 return status;
6370 }
6371startError:
6372 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006373 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006374 return status;
6375}
6376
Eric Laurenta011e352012-03-29 15:51:43 -07006377void AudioFlinger::RecordThread::clearSyncStartEvent()
6378{
6379 if (mSyncStartEvent != 0) {
6380 mSyncStartEvent->cancel();
6381 }
6382 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006383 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006384}
6385
6386void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6387{
6388 sp<SyncEvent> strongEvent = event.promote();
6389
6390 if (strongEvent != 0) {
6391 RecordThread *me = (RecordThread *)strongEvent->cookie();
6392 me->handleSyncStartEvent(strongEvent);
6393 }
6394}
6395
6396void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6397{
Eric Laurent29864602012-05-08 18:57:51 -07006398 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006399 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6400 // from audio HAL
6401 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006402 }
6403}
6404
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006405bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006406 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006407 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
6408 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006409 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006410 recordTrack->mState = TrackBase::PAUSING;
6411 // do not wait for mStartStopCond if exiting
6412 if (exitPending()) {
6413 return true;
6414 }
6415 mStartStopCond.wait(mLock);
6416 // if we have been restarted, recordTrack == mActiveTrack.get() here
6417 if (exitPending() || recordTrack != mActiveTrack.get()) {
6418 ALOGV("Record stopped OK");
6419 return true;
6420 }
6421 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006422}
6423
Glenn Kasten106e8a42012-08-02 13:37:12 -07006424bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07006425{
6426 return false;
6427}
6428
6429status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6430{
Glenn Kasten7aa25592012-08-02 16:37:07 -07006431#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 -07006432 if (!isValidSyncEvent(event)) {
6433 return BAD_VALUE;
6434 }
6435
Glenn Kasten510a3d62012-07-16 14:24:34 -07006436 int eventSession = event->triggerSession();
6437 status_t ret = NAME_NOT_FOUND;
6438
Eric Laurenta011e352012-03-29 15:51:43 -07006439 Mutex::Autolock _l(mLock);
6440
Glenn Kasten510a3d62012-07-16 14:24:34 -07006441 for (size_t i = 0; i < mTracks.size(); i++) {
6442 sp<RecordTrack> track = mTracks[i];
6443 if (eventSession == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07006444 (void) track->setSyncEvent(event);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006445 ret = NO_ERROR;
6446 }
Eric Laurenta011e352012-03-29 15:51:43 -07006447 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006448 return ret;
Glenn Kasten7aa25592012-08-02 16:37:07 -07006449#else
6450 return BAD_VALUE;
6451#endif
Glenn Kasten510a3d62012-07-16 14:24:34 -07006452}
6453
6454void AudioFlinger::RecordThread::RecordTrack::destroy()
6455{
6456 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
6457 sp<RecordTrack> keep(this);
6458 {
6459 sp<ThreadBase> thread = mThread.promote();
6460 if (thread != 0) {
6461 if (mState == ACTIVE || mState == RESUMING) {
6462 AudioSystem::stopInput(thread->id());
6463 }
6464 AudioSystem::releaseInput(thread->id());
6465 Mutex::Autolock _l(thread->mLock);
6466 RecordThread *recordThread = (RecordThread *) thread.get();
6467 recordThread->destroyTrack_l(this);
6468 }
6469 }
6470}
6471
6472// destroyTrack_l() must be called with ThreadBase::mLock held
6473void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6474{
6475 track->mState = TrackBase::TERMINATED;
6476 // active tracks are removed by threadLoop()
6477 if (mActiveTrack != track) {
6478 removeTrack_l(track);
6479 }
6480}
6481
6482void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6483{
6484 mTracks.remove(track);
6485 // need anything related to effects here?
Eric Laurenta011e352012-03-29 15:51:43 -07006486}
6487
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07006488void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006489{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006490 dumpInternals(fd, args);
6491 dumpTracks(fd, args);
6492 dumpEffectChains(fd, args);
6493}
6494
6495void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6496{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006497 const size_t SIZE = 256;
6498 char buffer[SIZE];
6499 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006500
6501 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6502 result.append(buffer);
6503
6504 if (mActiveTrack != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006505 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6506 result.append(buffer);
6507 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6508 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006509 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006510 result.append(buffer);
6511 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6512 result.append(buffer);
6513 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6514 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006515 } else {
Glenn Kasten510a3d62012-07-16 14:24:34 -07006516 result.append("No active record client\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006517 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006518
Mathias Agopian65ab4712010-07-14 17:59:35 -07006519 write(fd, result.string(), result.size());
6520
6521 dumpBase(fd, args);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006522}
6523
6524void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
6525{
6526 const size_t SIZE = 256;
6527 char buffer[SIZE];
6528 String8 result;
6529
6530 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
6531 result.append(buffer);
6532 RecordTrack::appendDumpHeader(result);
6533 for (size_t i = 0; i < mTracks.size(); ++i) {
6534 sp<RecordTrack> track = mTracks[i];
6535 if (track != 0) {
6536 track->dump(buffer, SIZE);
6537 result.append(buffer);
6538 }
6539 }
6540
6541 if (mActiveTrack != 0) {
6542 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
6543 result.append(buffer);
6544 RecordTrack::appendDumpHeader(result);
6545 mActiveTrack->dump(buffer, SIZE);
6546 result.append(buffer);
6547
6548 }
6549 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006550}
6551
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006552// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006553status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006554{
6555 size_t framesReq = buffer->frameCount;
6556 size_t framesReady = mFrameCount - mRsmpInIndex;
6557 int channelCount;
6558
6559 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006560 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07006561 if (mBytesRead <= 0) {
6562 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
6563 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006564 // Force input into standby so that it tries to
6565 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006566 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006567 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006568 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006569 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006570 buffer->frameCount = 0;
6571 return NOT_ENOUGH_DATA;
6572 }
6573 mRsmpInIndex = 0;
6574 framesReady = mFrameCount;
6575 }
6576
6577 if (framesReq > framesReady) {
6578 framesReq = framesReady;
6579 }
6580
6581 if (mChannelCount == 1 && mReqChannelCount == 2) {
6582 channelCount = 1;
6583 } else {
6584 channelCount = 2;
6585 }
6586 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6587 buffer->frameCount = framesReq;
6588 return NO_ERROR;
6589}
6590
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006591// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006592void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6593{
6594 mRsmpInIndex += buffer->frameCount;
6595 buffer->frameCount = 0;
6596}
6597
6598bool AudioFlinger::RecordThread::checkForNewParameters_l()
6599{
6600 bool reconfig = false;
6601
6602 while (!mNewParameters.isEmpty()) {
6603 status_t status = NO_ERROR;
6604 String8 keyValuePair = mNewParameters[0];
6605 AudioParameter param = AudioParameter(keyValuePair);
6606 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006607 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006608 int reqSamplingRate = mReqSampleRate;
6609 int reqChannelCount = mReqChannelCount;
6610
6611 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6612 reqSamplingRate = value;
6613 reconfig = true;
6614 }
6615 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006616 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006617 reconfig = true;
6618 }
6619 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006620 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006621 reconfig = true;
6622 }
6623 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6624 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006625 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006626 // if frame count is changed after track creation
6627 if (mActiveTrack != 0) {
6628 status = INVALID_OPERATION;
6629 } else {
6630 reconfig = true;
6631 }
6632 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006633 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6634 // forward device change to effects that have requested to be
6635 // aware of attached audio device.
6636 for (size_t i = 0; i < mEffectChains.size(); i++) {
6637 mEffectChains[i]->setDevice_l(value);
6638 }
Eric Laurentf1c04f92012-08-28 14:26:53 -07006639
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006640 // store input device and output device but do not forward output device to audio HAL.
6641 // Note that status is ignored by the caller for output device
6642 // (see AudioFlinger::setParameters()
Eric Laurentf1c04f92012-08-28 14:26:53 -07006643 if (audio_is_output_devices(value)) {
6644 mOutDevice = value;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006645 status = BAD_VALUE;
6646 } else {
Eric Laurentf1c04f92012-08-28 14:26:53 -07006647 mInDevice = value;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006648 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kasten510a3d62012-07-16 14:24:34 -07006649 if (mTracks.size() > 0) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07006650 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6651 mAudioFlinger->btNrecIsOff();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006652 for (size_t i = 0; i < mTracks.size(); i++) {
6653 sp<RecordTrack> track = mTracks[i];
6654 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6655 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6656 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07006657 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006658 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006659 }
Eric Laurent57b2dd12012-08-31 17:44:06 -07006660 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6661 mAudioSource != (audio_source_t)value) {
6662 // forward device change to effects that have requested to be
6663 // aware of attached audio device.
6664 for (size_t i = 0; i < mEffectChains.size(); i++) {
6665 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
6666 }
6667 mAudioSource = (audio_source_t)value;
6668 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006669 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006670 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006671 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006672 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006673 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6674 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006675 }
6676 if (reconfig) {
6677 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006678 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006679 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006680 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006681 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6682 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006683 status = NO_ERROR;
6684 }
6685 if (status == NO_ERROR) {
6686 readInputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07006687 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006688 }
6689 }
6690 }
6691
6692 mNewParameters.removeAt(0);
6693
6694 mParamStatus = status;
6695 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006696 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6697 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006698 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006699 }
6700 return reconfig;
6701}
6702
6703String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6704{
Dima Zavinfce7a472011-04-19 22:30:36 -07006705 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006706 String8 out_s8 = String8();
6707
6708 Mutex::Autolock _l(mLock);
6709 if (initCheck() != NO_ERROR) {
6710 return out_s8;
6711 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006712
Dima Zavin799a70e2011-04-18 16:57:27 -07006713 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006714 out_s8 = String8(s);
6715 free(s);
6716 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006717}
6718
6719void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6720 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006721 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006722
6723 switch (event) {
6724 case AudioSystem::INPUT_OPENED:
6725 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006726 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006727 desc.samplingRate = mSampleRate;
6728 desc.format = mFormat;
6729 desc.frameCount = mFrameCount;
6730 desc.latency = 0;
6731 param2 = &desc;
6732 break;
6733
6734 case AudioSystem::INPUT_CLOSED:
6735 default:
6736 break;
6737 }
6738 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6739}
6740
6741void AudioFlinger::RecordThread::readInputParameters()
6742{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006743 delete mRsmpInBuffer;
6744 // mRsmpInBuffer is always assigned a new[] below
6745 delete mRsmpOutBuffer;
6746 mRsmpOutBuffer = NULL;
6747 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006748 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006749
Dima Zavin799a70e2011-04-18 16:57:27 -07006750 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006751 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6752 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006753 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006754 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006755 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006756 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006757 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006758 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6759
Glenn Kasten53d76db2012-03-08 12:32:47 -08006760 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006761 {
6762 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006763 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6764 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006765 if (mChannelCount == 1 && mReqChannelCount == 2) {
6766 channelCount = 1;
6767 } else {
6768 channelCount = 2;
6769 }
6770 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6771 mResampler->setSampleRate(mSampleRate);
6772 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6773 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6774
6775 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6776 if (mChannelCount == 1 && mReqChannelCount == 1) {
6777 mFrameCount >>= 1;
6778 }
6779
6780 }
6781 mRsmpInIndex = mFrameCount;
6782}
6783
6784unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6785{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006786 Mutex::Autolock _l(mLock);
6787 if (initCheck() != NO_ERROR) {
6788 return 0;
6789 }
6790
Dima Zavin799a70e2011-04-18 16:57:27 -07006791 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006792}
6793
Glenn Kasten106e8a42012-08-02 13:37:12 -07006794uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006795{
6796 Mutex::Autolock _l(mLock);
6797 uint32_t result = 0;
6798 if (getEffectChain_l(sessionId) != 0) {
6799 result = EFFECT_SESSION;
6800 }
6801
Glenn Kasten510a3d62012-07-16 14:24:34 -07006802 for (size_t i = 0; i < mTracks.size(); ++i) {
6803 if (sessionId == mTracks[i]->sessionId()) {
6804 result |= TRACK_SESSION;
6805 break;
6806 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006807 }
6808
6809 return result;
6810}
6811
Glenn Kasten106e8a42012-08-02 13:37:12 -07006812KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent59bd0da2011-08-01 09:52:20 -07006813{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006814 KeyedVector<int, bool> ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006815 Mutex::Autolock _l(mLock);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006816 for (size_t j = 0; j < mTracks.size(); ++j) {
6817 sp<RecordThread::RecordTrack> track = mTracks[j];
6818 int sessionId = track->sessionId();
6819 if (ids.indexOfKey(sessionId) < 0) {
6820 ids.add(sessionId, true);
6821 }
6822 }
6823 return ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006824}
6825
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006826AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6827{
6828 Mutex::Autolock _l(mLock);
6829 AudioStreamIn *input = mInput;
6830 mInput = NULL;
6831 return input;
6832}
6833
6834// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006835audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006836{
6837 if (mInput == NULL) {
6838 return NULL;
6839 }
6840 return &mInput->stream->common;
6841}
6842
6843
Mathias Agopian65ab4712010-07-14 17:59:35 -07006844// ----------------------------------------------------------------------------
6845
Eric Laurenta4c5a552012-03-29 10:12:40 -07006846audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6847{
6848 if (!settingsAllowed()) {
6849 return 0;
6850 }
6851 Mutex::Autolock _l(mLock);
6852 return loadHwModule_l(name);
6853}
6854
6855// loadHwModule_l() must be called with AudioFlinger::mLock held
6856audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6857{
6858 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6859 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6860 ALOGW("loadHwModule() module %s already loaded", name);
6861 return mAudioHwDevs.keyAt(i);
6862 }
6863 }
6864
Eric Laurenta4c5a552012-03-29 10:12:40 -07006865 audio_hw_device_t *dev;
6866
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006867 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006868 if (rc) {
6869 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6870 return 0;
6871 }
6872
6873 mHardwareStatus = AUDIO_HW_INIT;
6874 rc = dev->init_check(dev);
6875 mHardwareStatus = AUDIO_HW_IDLE;
6876 if (rc) {
6877 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6878 return 0;
6879 }
6880
John Grossmanee578c02012-07-23 17:05:46 -07006881 // Check and cache this HAL's level of support for master mute and master
6882 // volume. If this is the first HAL opened, and it supports the get
6883 // methods, use the initial values provided by the HAL as the current
6884 // master mute and volume settings.
6885
6886 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
6887 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07006888 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07006889
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01006890#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07006891 if (0 == mAudioHwDevs.size()) {
6892 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6893 if (NULL != dev->get_master_volume) {
6894 float mv;
6895 if (OK == dev->get_master_volume(dev, &mv)) {
6896 mMasterVolume = mv;
6897 }
6898 }
6899
6900 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
6901 if (NULL != dev->get_master_mute) {
6902 bool mm;
6903 if (OK == dev->get_master_mute(dev, &mm)) {
6904 mMasterMute = mm;
6905 }
6906 }
6907 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01006908#endif
John Grossmanee578c02012-07-23 17:05:46 -07006909
Eric Laurenta4c5a552012-03-29 10:12:40 -07006910 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07006911 if ((NULL != dev->set_master_volume) &&
6912 (OK == dev->set_master_volume(dev, mMasterVolume))) {
6913 flags = static_cast<AudioHwDevice::Flags>(flags |
6914 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
6915 }
6916
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01006917#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07006918 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
6919 if ((NULL != dev->set_master_mute) &&
6920 (OK == dev->set_master_mute(dev, mMasterMute))) {
6921 flags = static_cast<AudioHwDevice::Flags>(flags |
6922 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
6923 }
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01006924#endif
John Grossmanee578c02012-07-23 17:05:46 -07006925
Eric Laurenta4c5a552012-03-29 10:12:40 -07006926 mHardwareStatus = AUDIO_HW_IDLE;
6927 }
6928
6929 audio_module_handle_t handle = nextUniqueId();
John Grossmanee578c02012-07-23 17:05:46 -07006930 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07006931
6932 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006933 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006934
6935 return handle;
6936
6937}
6938
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07006939// ----------------------------------------------------------------------------
6940
6941int32_t AudioFlinger::getPrimaryOutputSamplingRate()
6942{
6943 Mutex::Autolock _l(mLock);
6944 PlaybackThread *thread = primaryPlaybackThread_l();
6945 return thread != NULL ? thread->sampleRate() : 0;
6946}
6947
6948int32_t AudioFlinger::getPrimaryOutputFrameCount()
6949{
6950 Mutex::Autolock _l(mLock);
6951 PlaybackThread *thread = primaryPlaybackThread_l();
6952 return thread != NULL ? thread->frameCountHAL() : 0;
6953}
6954
6955// ----------------------------------------------------------------------------
6956
Eric Laurenta4c5a552012-03-29 10:12:40 -07006957audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6958 audio_devices_t *pDevices,
6959 uint32_t *pSamplingRate,
6960 audio_format_t *pFormat,
6961 audio_channel_mask_t *pChannelMask,
6962 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006963 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006964{
6965 status_t status;
6966 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006967 struct audio_config config = {
6968 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6969 channel_mask: pChannelMask ? *pChannelMask : 0,
6970 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6971 };
6972 audio_stream_out_t *outStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07006973 AudioHwDevice *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006974
Eric Laurenta4c5a552012-03-29 10:12:40 -07006975 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6976 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006977 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006978 config.sample_rate,
6979 config.format,
6980 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006981 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006982
6983 if (pDevices == NULL || *pDevices == 0) {
6984 return 0;
6985 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006986
Mathias Agopian65ab4712010-07-14 17:59:35 -07006987 Mutex::Autolock _l(mLock);
6988
Eric Laurenta4c5a552012-03-29 10:12:40 -07006989 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006990 if (outHwDev == NULL)
6991 return 0;
6992
John Grossmanee578c02012-07-23 17:05:46 -07006993 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006994 audio_io_handle_t id = nextUniqueId();
6995
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006996 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006997
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01006998#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07006999 status = hwDevHal->open_output_stream(hwDevHal,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007000 id,
7001 *pDevices,
7002 (audio_output_flags_t)flags,
7003 &config,
7004 &outStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007005#else
7006 status = hwDevHal->open_output_stream(hwDevHal,
7007 *pDevices,
7008 (int *)&config.format,
7009 &config.channel_mask,
7010 &config.sample_rate,
7011 &outStream);
7012 uint32_t newflags = flags | AUDIO_OUTPUT_FLAG_PRIMARY;
7013 flags = (audio_output_flags_t)newflags;
7014#endif
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007015
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007016 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01007017 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007018 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007019 config.sample_rate,
7020 config.format,
7021 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007022 status);
7023
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007024 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007025 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007026
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007027 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007028 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
7029 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007030 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007031 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007032 } else {
7033 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007034 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007035 }
7036 mPlaybackThreads.add(id, thread);
7037
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007038 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
7039 if (pFormat != NULL) *pFormat = config.format;
7040 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08007041 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007042
7043 // notify client processes of the new output creation
7044 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007045
7046 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007047 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07007048 ALOGI("Using module %d has the primary audio interface", module);
7049 mPrimaryHardwareDev = outHwDev;
7050
7051 AutoMutex lock(mHardwareLock);
7052 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -07007053 hwDevHal->set_mode(hwDevHal, mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007054 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007055 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007056 return id;
7057 }
7058
7059 return 0;
7060}
7061
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007062audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
7063 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007064{
7065 Mutex::Autolock _l(mLock);
7066 MixerThread *thread1 = checkMixerThread_l(output1);
7067 MixerThread *thread2 = checkMixerThread_l(output2);
7068
7069 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007070 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007071 return 0;
7072 }
7073
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007074 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007075 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
7076 thread->addOutputTrack(thread2);
7077 mPlaybackThreads.add(id, thread);
7078 // notify client processes of the new output creation
7079 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7080 return id;
7081}
7082
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007083status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007084{
Glenn Kastend96c5722012-04-25 13:44:49 -07007085 return closeOutput_nonvirtual(output);
7086}
7087
7088status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
7089{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007090 // keep strong reference on the playback thread so that
7091 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007092 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007093 {
7094 Mutex::Autolock _l(mLock);
7095 thread = checkPlaybackThread_l(output);
7096 if (thread == NULL) {
7097 return BAD_VALUE;
7098 }
7099
Steve Block3856b092011-10-20 11:56:00 +01007100 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007101
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007102 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007103 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007104 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007105 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
7106 dupThread->removeOutputTrack((MixerThread *)thread.get());
7107 }
7108 }
7109 }
Glenn Kastena1117922012-01-26 10:53:32 -08007110 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007111 mPlaybackThreads.removeItem(output);
7112 }
7113 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007114 // The thread entity (active unit of execution) is no longer running here,
7115 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007116
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007117 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007118 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007119 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007120 // from now on thread->mOutput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007121 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007122 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007123 }
7124 return NO_ERROR;
7125}
7126
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007127status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007128{
7129 Mutex::Autolock _l(mLock);
7130 PlaybackThread *thread = checkPlaybackThread_l(output);
7131
7132 if (thread == NULL) {
7133 return BAD_VALUE;
7134 }
7135
Steve Block3856b092011-10-20 11:56:00 +01007136 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007137 thread->suspend();
7138
7139 return NO_ERROR;
7140}
7141
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007142status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007143{
7144 Mutex::Autolock _l(mLock);
7145 PlaybackThread *thread = checkPlaybackThread_l(output);
7146
7147 if (thread == NULL) {
7148 return BAD_VALUE;
7149 }
7150
Steve Block3856b092011-10-20 11:56:00 +01007151 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007152
7153 thread->restore();
7154
7155 return NO_ERROR;
7156}
7157
Eric Laurenta4c5a552012-03-29 10:12:40 -07007158audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
7159 audio_devices_t *pDevices,
7160 uint32_t *pSamplingRate,
7161 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07007162 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007163{
7164 status_t status;
7165 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007166 struct audio_config config = {
7167 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7168 channel_mask: pChannelMask ? *pChannelMask : 0,
7169 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7170 };
7171 uint32_t reqSamplingRate = config.sample_rate;
7172 audio_format_t reqFormat = config.format;
7173 audio_channel_mask_t reqChannels = config.channel_mask;
7174 audio_stream_in_t *inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007175 AudioHwDevice *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007176
7177 if (pDevices == NULL || *pDevices == 0) {
7178 return 0;
7179 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007180
Mathias Agopian65ab4712010-07-14 17:59:35 -07007181 Mutex::Autolock _l(mLock);
7182
Eric Laurenta4c5a552012-03-29 10:12:40 -07007183 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007184 if (inHwDev == NULL)
7185 return 0;
7186
John Grossmanee578c02012-07-23 17:05:46 -07007187 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007188 audio_io_handle_t id = nextUniqueId();
7189
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007190#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007191 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007192 &inStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007193#else
7194 status = inHwHal->open_input_stream(inHwHal, *pDevices,
7195 (int *)&config.format,
7196 &config.channel_mask,
7197 &config.sample_rate, (audio_in_acoustics_t)0,
7198 &inStream);
7199#endif
Eric Laurenta4c5a552012-03-29 10:12:40 -07007200 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007201 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007202 config.sample_rate,
7203 config.format,
7204 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007205 status);
7206
7207 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7208 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7209 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007210 if (status == BAD_VALUE &&
7211 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7212 (config.sample_rate <= 2 * reqSamplingRate) &&
7213 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007214 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007215 inStream = NULL;
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007216#ifndef ICS_AUDIO_BLOB
John Grossmanee578c02012-07-23 17:05:46 -07007217 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
Ricardo Cerqueira59199b12012-07-11 23:39:44 +01007218#else
7219 status = inHwHal->open_input_stream(inHwHal, *pDevices,
7220 (int *)&config.format,
7221 &config.channel_mask,
7222 &config.sample_rate, (audio_in_acoustics_t)0,
7223 &inStream);
7224#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07007225 }
7226
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007227 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007228 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7229
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007230 // Start record thread
7231 // RecorThread require both input and output device indication to forward to audio
7232 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007233 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007234 thread = new RecordThread(this,
7235 input,
7236 reqSamplingRate,
7237 reqChannels,
7238 id,
7239 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007240 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007241 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007242 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007243 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007244 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007245
Mathias Agopian65ab4712010-07-14 17:59:35 -07007246 // notify client processes of the new input creation
7247 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7248 return id;
7249 }
7250
7251 return 0;
7252}
7253
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007254status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007255{
Glenn Kastend96c5722012-04-25 13:44:49 -07007256 return closeInput_nonvirtual(input);
7257}
7258
7259status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7260{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007261 // keep strong reference on the record thread so that
7262 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007263 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007264 {
7265 Mutex::Autolock _l(mLock);
7266 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007267 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007268 return BAD_VALUE;
7269 }
7270
Steve Block3856b092011-10-20 11:56:00 +01007271 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007272 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007273 mRecordThreads.removeItem(input);
7274 }
7275 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007276 // The thread entity (active unit of execution) is no longer running here,
7277 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007278
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007279 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007280 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007281 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007282 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007283 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007284
7285 return NO_ERROR;
7286}
7287
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007288status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007289{
7290 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007291 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007292
7293 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7294 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007295 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007296 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007297
7298 return NO_ERROR;
7299}
7300
7301
7302int AudioFlinger::newAudioSessionId()
7303{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007304 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007305}
7306
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007307void AudioFlinger::acquireAudioSessionId(int audioSession)
7308{
7309 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007310 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007311 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007312 size_t num = mAudioSessionRefs.size();
7313 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007314 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007315 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7316 ref->mCnt++;
7317 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007318 return;
7319 }
7320 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007321 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7322 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007323}
7324
7325void AudioFlinger::releaseAudioSessionId(int audioSession)
7326{
7327 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007328 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007329 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007330 size_t num = mAudioSessionRefs.size();
7331 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007332 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007333 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7334 ref->mCnt--;
7335 ALOGV(" decremented refcount to %d", ref->mCnt);
7336 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007337 mAudioSessionRefs.removeAt(i);
7338 delete ref;
7339 purgeStaleEffects_l();
7340 }
7341 return;
7342 }
7343 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007344 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007345}
7346
7347void AudioFlinger::purgeStaleEffects_l() {
7348
Steve Block3856b092011-10-20 11:56:00 +01007349 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007350
7351 Vector< sp<EffectChain> > chains;
7352
7353 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7354 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7355 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7356 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007357 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7358 chains.push(ec);
7359 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007360 }
7361 }
7362 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7363 sp<RecordThread> t = mRecordThreads.valueAt(i);
7364 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7365 sp<EffectChain> ec = t->mEffectChains[j];
7366 chains.push(ec);
7367 }
7368 }
7369
7370 for (size_t i = 0; i < chains.size(); i++) {
7371 sp<EffectChain> ec = chains[i];
7372 int sessionid = ec->sessionId();
7373 sp<ThreadBase> t = ec->mThread.promote();
7374 if (t == 0) {
7375 continue;
7376 }
7377 size_t numsessionrefs = mAudioSessionRefs.size();
7378 bool found = false;
7379 for (size_t k = 0; k < numsessionrefs; k++) {
7380 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007381 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007382 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007383 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007384 found = true;
7385 break;
7386 }
7387 }
7388 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007389 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007390 // remove all effects from the chain
7391 while (ec->mEffects.size()) {
7392 sp<EffectModule> effect = ec->mEffects[0];
7393 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007394 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007395 if (effect->purgeHandles()) {
7396 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007397 }
7398 AudioSystem::unregisterEffect(effect->id());
7399 }
7400 }
7401 }
7402 return;
7403}
7404
Mathias Agopian65ab4712010-07-14 17:59:35 -07007405// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007406AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007407{
Glenn Kastena1117922012-01-26 10:53:32 -08007408 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007409}
7410
7411// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007412AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007413{
7414 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007415 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007416}
7417
7418// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007419AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007420{
Glenn Kastena1117922012-01-26 10:53:32 -08007421 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007422}
7423
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007424uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007425{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007426 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007427}
7428
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007429AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007430{
7431 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7432 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007433 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07007434 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007435 return thread;
7436 }
7437 }
7438 return NULL;
7439}
7440
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007441audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007442{
7443 PlaybackThread *thread = primaryPlaybackThread_l();
7444
7445 if (thread == NULL) {
7446 return 0;
7447 }
7448
Eric Laurentf1c04f92012-08-28 14:26:53 -07007449 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007450}
7451
Eric Laurenta011e352012-03-29 15:51:43 -07007452sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7453 int triggerSession,
7454 int listenerSession,
7455 sync_event_callback_t callBack,
7456 void *cookie)
7457{
7458 Mutex::Autolock _l(mLock);
7459
7460 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7461 status_t playStatus = NAME_NOT_FOUND;
7462 status_t recStatus = NAME_NOT_FOUND;
7463 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7464 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7465 if (playStatus == NO_ERROR) {
7466 return event;
7467 }
7468 }
7469 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7470 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7471 if (recStatus == NO_ERROR) {
7472 return event;
7473 }
7474 }
7475 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7476 mPendingSyncEvents.add(event);
7477 } else {
7478 ALOGV("createSyncEvent() invalid event %d", event->type());
7479 event.clear();
7480 }
7481 return event;
7482}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007483
Mathias Agopian65ab4712010-07-14 17:59:35 -07007484// ----------------------------------------------------------------------------
7485// Effect management
7486// ----------------------------------------------------------------------------
7487
7488
Glenn Kastenf587ba52012-01-26 16:25:10 -08007489status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007490{
7491 Mutex::Autolock _l(mLock);
7492 return EffectQueryNumberEffects(numEffects);
7493}
7494
Glenn Kastenf587ba52012-01-26 16:25:10 -08007495status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007496{
7497 Mutex::Autolock _l(mLock);
7498 return EffectQueryEffect(index, descriptor);
7499}
7500
Glenn Kasten5e92a782012-01-30 07:40:52 -08007501status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007502 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007503{
7504 Mutex::Autolock _l(mLock);
7505 return EffectGetDescriptor(pUuid, descriptor);
7506}
7507
7508
Mathias Agopian65ab4712010-07-14 17:59:35 -07007509sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7510 effect_descriptor_t *pDesc,
7511 const sp<IEffectClient>& effectClient,
7512 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007513 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007514 int sessionId,
7515 status_t *status,
7516 int *id,
7517 int *enabled)
7518{
7519 status_t lStatus = NO_ERROR;
7520 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007521 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007522
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007523 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007524 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007525
7526 if (pDesc == NULL) {
7527 lStatus = BAD_VALUE;
7528 goto Exit;
7529 }
7530
Eric Laurent84e9a102010-09-23 16:10:16 -07007531 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007532 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007533 lStatus = PERMISSION_DENIED;
7534 goto Exit;
7535 }
7536
Dima Zavinfce7a472011-04-19 22:30:36 -07007537 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007538 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007539 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007540 lStatus = PERMISSION_DENIED;
7541 goto Exit;
7542 }
7543
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007544 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007545 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007546 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007547 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007548 lStatus = BAD_VALUE;
7549 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007550 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007551 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007552 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007553 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007554 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007555 }
7556 }
7557
Mathias Agopian65ab4712010-07-14 17:59:35 -07007558 {
7559 Mutex::Autolock _l(mLock);
7560
Mathias Agopian65ab4712010-07-14 17:59:35 -07007561
7562 if (!EffectIsNullUuid(&pDesc->uuid)) {
7563 // if uuid is specified, request effect descriptor
7564 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7565 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007566 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007567 goto Exit;
7568 }
7569 } else {
7570 // if uuid is not specified, look for an available implementation
7571 // of the required type in effect factory
7572 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007573 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007574 lStatus = BAD_VALUE;
7575 goto Exit;
7576 }
7577 uint32_t numEffects = 0;
7578 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007579 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007580 bool found = false;
7581
7582 lStatus = EffectQueryNumberEffects(&numEffects);
7583 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007584 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007585 goto Exit;
7586 }
7587 for (uint32_t i = 0; i < numEffects; i++) {
7588 lStatus = EffectQueryEffect(i, &desc);
7589 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007590 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007591 continue;
7592 }
7593 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7594 // If matching type found save effect descriptor. If the session is
7595 // 0 and the effect is not auxiliary, continue enumeration in case
7596 // an auxiliary version of this effect type is available
7597 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08007598 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07007599 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007600 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7601 break;
7602 }
7603 }
7604 }
7605 if (!found) {
7606 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007607 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007608 goto Exit;
7609 }
7610 // For same effect type, chose auxiliary version over insert version if
7611 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007612 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007613 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08007614 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007615 }
7616 }
7617
7618 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007619 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007620 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7621 lStatus = INVALID_OPERATION;
7622 goto Exit;
7623 }
7624
Eric Laurent59255e42011-07-27 19:49:51 -07007625 // check recording permission for visualizer
7626 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7627 !recordingAllowed()) {
7628 lStatus = PERMISSION_DENIED;
7629 goto Exit;
7630 }
7631
Mathias Agopian65ab4712010-07-14 17:59:35 -07007632 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08007633 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007634
7635 // If output is not specified try to find a matching audio session ID in one of the
7636 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007637 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7638 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007639 // Note: io is never 0 when creating an effect on an input
7640 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007641 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007642 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7643 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007644 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007645 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007646 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007647 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007648 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007649 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7650 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7651 io = mRecordThreads.keyAt(i);
7652 break;
7653 }
7654 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007655 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007656 // If no output thread contains the requested session ID, default to
7657 // first output. The effect chain will be moved to the correct output
7658 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007659 if (io == 0 && mPlaybackThreads.size()) {
7660 io = mPlaybackThreads.keyAt(0);
7661 }
Steve Block3856b092011-10-20 11:56:00 +01007662 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007663 }
7664 ThreadBase *thread = checkRecordThread_l(io);
7665 if (thread == NULL) {
7666 thread = checkPlaybackThread_l(io);
7667 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007668 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007669 lStatus = BAD_VALUE;
7670 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007671 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007672 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007673
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007674 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007675
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007676 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007677 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7678 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007679 if (handle != 0 && id != NULL) {
7680 *id = handle->id();
7681 }
7682 }
7683
7684Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007685 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007686 *status = lStatus;
7687 }
7688 return handle;
7689}
7690
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007691status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7692 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007693{
Steve Block3856b092011-10-20 11:56:00 +01007694 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007695 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007696 Mutex::Autolock _l(mLock);
7697 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007698 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007699 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007700 }
Eric Laurentde070132010-07-13 04:45:46 -07007701 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7702 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007703 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007704 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007705 }
Eric Laurentde070132010-07-13 04:45:46 -07007706 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7707 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007708 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007709 return BAD_VALUE;
7710 }
7711
7712 Mutex::Autolock _dl(dstThread->mLock);
7713 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007714 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007715
Mathias Agopian65ab4712010-07-14 17:59:35 -07007716 return NO_ERROR;
7717}
7718
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007719// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007720status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007721 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007722 AudioFlinger::PlaybackThread *dstThread,
7723 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007724{
Steve Block3856b092011-10-20 11:56:00 +01007725 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007726 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007727
Eric Laurent59255e42011-07-27 19:49:51 -07007728 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007729 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007730 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007731 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007732 return INVALID_OPERATION;
7733 }
7734
Eric Laurent39e94f82010-07-28 01:32:47 -07007735 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007736 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007737 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007738 // removed.
7739 srcThread->removeEffectChain_l(chain);
7740
7741 // transfer all effects one by one so that new effect chain is created on new thread with
7742 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007743 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007744 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007745 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007746 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7747 while (effect != 0) {
7748 srcThread->removeEffect_l(effect);
7749 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007750 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7751 if (effect->state() == EffectModule::ACTIVE ||
7752 effect->state() == EffectModule::STOPPING) {
7753 effect->start();
7754 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007755 // if the move request is not received from audio policy manager, the effect must be
7756 // re-registered with the new strategy and output
7757 if (dstChain == 0) {
7758 dstChain = effect->chain().promote();
7759 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007760 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007761 srcThread->addEffect_l(effect);
7762 return NO_INIT;
7763 }
7764 strategy = dstChain->strategy();
7765 }
7766 if (reRegister) {
7767 AudioSystem::unregisterEffect(effect->id());
7768 AudioSystem::registerEffect(&effect->desc(),
7769 dstOutput,
7770 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007771 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007772 effect->id());
7773 }
Eric Laurentde070132010-07-13 04:45:46 -07007774 effect = chain->getEffectFromId_l(0);
7775 }
7776
7777 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007778}
7779
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007780
Mathias Agopian65ab4712010-07-14 17:59:35 -07007781// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007782sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007783 const sp<AudioFlinger::Client>& client,
7784 const sp<IEffectClient>& effectClient,
7785 int32_t priority,
7786 int sessionId,
7787 effect_descriptor_t *desc,
7788 int *enabled,
7789 status_t *status
7790 )
7791{
7792 sp<EffectModule> effect;
7793 sp<EffectHandle> handle;
7794 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007795 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007796 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007797 bool effectCreated = false;
7798 bool effectRegistered = false;
7799
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007800 lStatus = initCheck();
7801 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007802 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007803 goto Exit;
7804 }
7805
7806 // Do not allow effects with session ID 0 on direct output or duplicating threads
7807 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007808 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007809 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007810 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007811 lStatus = BAD_VALUE;
7812 goto Exit;
7813 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007814 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007815 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007816 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007817 desc->name, desc->flags, mType);
7818 lStatus = BAD_VALUE;
7819 goto Exit;
7820 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007821
Steve Block3856b092011-10-20 11:56:00 +01007822 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007823
7824 { // scope for mLock
7825 Mutex::Autolock _l(mLock);
7826
7827 // check for existing effect chain with the requested audio session
7828 chain = getEffectChain_l(sessionId);
7829 if (chain == 0) {
7830 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007831 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007832 chain = new EffectChain(this, sessionId);
7833 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007834 chain->setStrategy(getStrategyForSession_l(sessionId));
7835 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007836 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007837 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007838 }
7839
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007840 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007841
7842 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007843 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007844 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007845 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007846 if (lStatus != NO_ERROR) {
7847 goto Exit;
7848 }
7849 effectRegistered = true;
7850 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007851 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007852 lStatus = effect->status();
7853 if (lStatus != NO_ERROR) {
7854 goto Exit;
7855 }
Eric Laurentcab11242010-07-15 12:50:15 -07007856 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007857 if (lStatus != NO_ERROR) {
7858 goto Exit;
7859 }
7860 effectCreated = true;
7861
Eric Laurentf1c04f92012-08-28 14:26:53 -07007862 effect->setDevice(mOutDevice);
7863 effect->setDevice(mInDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007864 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07007865 effect->setAudioSource(mAudioSource);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007866 }
7867 // create effect handle and connect it to effect module
7868 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007869 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007870 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007871 *enabled = (int)effect->isEnabled();
7872 }
7873 }
7874
7875Exit:
7876 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007877 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007878 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007879 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007880 }
7881 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007882 AudioSystem::unregisterEffect(effect->id());
7883 }
7884 if (chainCreated) {
7885 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007886 }
7887 handle.clear();
7888 }
7889
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007890 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007891 *status = lStatus;
7892 }
7893 return handle;
7894}
7895
Eric Laurent717e1282012-06-29 16:36:52 -07007896sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7897{
7898 Mutex::Autolock _l(mLock);
7899 return getEffect_l(sessionId, effectId);
7900}
7901
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007902sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7903{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007904 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007905 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007906}
7907
Eric Laurentde070132010-07-13 04:45:46 -07007908// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7909// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007910status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007911{
7912 // check for existing effect chain with the requested audio session
7913 int sessionId = effect->sessionId();
7914 sp<EffectChain> chain = getEffectChain_l(sessionId);
7915 bool chainCreated = false;
7916
7917 if (chain == 0) {
7918 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007919 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007920 chain = new EffectChain(this, sessionId);
7921 addEffectChain_l(chain);
7922 chain->setStrategy(getStrategyForSession_l(sessionId));
7923 chainCreated = true;
7924 }
Steve Block3856b092011-10-20 11:56:00 +01007925 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007926
7927 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007928 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007929 this, effect->desc().name, chain.get());
7930 return BAD_VALUE;
7931 }
7932
7933 status_t status = chain->addEffect_l(effect);
7934 if (status != NO_ERROR) {
7935 if (chainCreated) {
7936 removeEffectChain_l(chain);
7937 }
7938 return status;
7939 }
7940
Eric Laurentf1c04f92012-08-28 14:26:53 -07007941 effect->setDevice(mOutDevice);
7942 effect->setDevice(mInDevice);
Eric Laurentde070132010-07-13 04:45:46 -07007943 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07007944 effect->setAudioSource(mAudioSource);
Eric Laurentde070132010-07-13 04:45:46 -07007945 return NO_ERROR;
7946}
7947
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007948void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007949
Steve Block3856b092011-10-20 11:56:00 +01007950 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007951 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007952 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7953 detachAuxEffect_l(effect->id());
7954 }
7955
7956 sp<EffectChain> chain = effect->chain().promote();
7957 if (chain != 0) {
7958 // remove effect chain if removing last effect
7959 if (chain->removeEffect_l(effect) == 0) {
7960 removeEffectChain_l(chain);
7961 }
7962 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007963 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007964 }
7965}
7966
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007967void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007968 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007969{
7970 effectChains = mEffectChains;
7971 for (size_t i = 0; i < mEffectChains.size(); i++) {
7972 mEffectChains[i]->lock();
7973 }
7974}
7975
7976void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007977 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007978{
7979 for (size_t i = 0; i < effectChains.size(); i++) {
7980 effectChains[i]->unlock();
7981 }
7982}
7983
7984sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7985{
7986 Mutex::Autolock _l(mLock);
7987 return getEffectChain_l(sessionId);
7988}
7989
Glenn Kasten106e8a42012-08-02 13:37:12 -07007990sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007991{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007992 size_t size = mEffectChains.size();
7993 for (size_t i = 0; i < size; i++) {
7994 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007995 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007996 }
7997 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007998 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007999}
8000
Glenn Kastenf78aee72012-01-04 11:00:47 -08008001void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008002{
8003 Mutex::Autolock _l(mLock);
8004 size_t size = mEffectChains.size();
8005 for (size_t i = 0; i < size; i++) {
8006 mEffectChains[i]->setMode_l(mode);
8007 }
8008}
8009
8010void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008011 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08008012 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07008013
Mathias Agopian65ab4712010-07-14 17:59:35 -07008014 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008015 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008016 // delete the effect module if removing last handle on it
8017 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008018 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008019 removeEffect_l(effect);
8020 AudioSystem::unregisterEffect(effect->id());
8021 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008022 }
8023}
8024
8025status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
8026{
8027 int session = chain->sessionId();
8028 int16_t *buffer = mMixBuffer;
8029 bool ownsBuffer = false;
8030
Steve Block3856b092011-10-20 11:56:00 +01008031 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008032 if (session > 0) {
8033 // Only one effect chain can be present in direct output thread and it uses
8034 // the mix buffer as input
8035 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07008036 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008037 buffer = new int16_t[numSamples];
8038 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01008039 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008040 ownsBuffer = true;
8041 }
8042
8043 // Attach all tracks with same session ID to this chain.
8044 for (size_t i = 0; i < mTracks.size(); ++i) {
8045 sp<Track> track = mTracks[i];
8046 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008047 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008048 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008049 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008050 }
8051 }
8052
8053 // indicate all active tracks in the chain
8054 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8055 sp<Track> track = mActiveTracks[i].promote();
8056 if (track == 0) continue;
8057 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008058 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07008059 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008060 }
8061 }
8062 }
8063
8064 chain->setInBuffer(buffer, ownsBuffer);
8065 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07008066 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07008067 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008068 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
8069 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008070 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07008071 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
8072 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07008073 // Effect chain for other sessions are inserted at beginning of effect
8074 // chains list to be processed before output mix effects. Relative order between other
8075 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07008076 size_t size = mEffectChains.size();
8077 size_t i = 0;
8078 for (i = 0; i < size; i++) {
8079 if (mEffectChains[i]->sessionId() < session) break;
8080 }
8081 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008082 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008083
8084 return NO_ERROR;
8085}
8086
8087size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
8088{
8089 int session = chain->sessionId();
8090
Steve Block3856b092011-10-20 11:56:00 +01008091 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008092
8093 for (size_t i = 0; i < mEffectChains.size(); i++) {
8094 if (chain == mEffectChains[i]) {
8095 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07008096 // detach all active tracks from the chain
8097 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8098 sp<Track> track = mActiveTracks[i].promote();
8099 if (track == 0) continue;
8100 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008101 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07008102 chain.get(), session);
8103 chain->decActiveTrackCnt();
8104 }
8105 }
8106
Mathias Agopian65ab4712010-07-14 17:59:35 -07008107 // detach all tracks with same session ID from this chain
8108 for (size_t i = 0; i < mTracks.size(); ++i) {
8109 sp<Track> track = mTracks[i];
8110 if (session == track->sessionId()) {
8111 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008112 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008113 }
8114 }
Eric Laurentde070132010-07-13 04:45:46 -07008115 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008116 }
8117 }
8118 return mEffectChains.size();
8119}
8120
Eric Laurentde070132010-07-13 04:45:46 -07008121status_t AudioFlinger::PlaybackThread::attachAuxEffect(
8122 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008123{
8124 Mutex::Autolock _l(mLock);
8125 return attachAuxEffect_l(track, EffectId);
8126}
8127
Eric Laurentde070132010-07-13 04:45:46 -07008128status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
8129 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008130{
8131 status_t status = NO_ERROR;
8132
8133 if (EffectId == 0) {
8134 track->setAuxBuffer(0, NULL);
8135 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07008136 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
8137 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008138 if (effect != 0) {
8139 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8140 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
8141 } else {
8142 status = INVALID_OPERATION;
8143 }
8144 } else {
8145 status = BAD_VALUE;
8146 }
8147 }
8148 return status;
8149}
8150
8151void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
8152{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008153 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008154 sp<Track> track = mTracks[i];
8155 if (track->auxEffectId() == effectId) {
8156 attachAuxEffect_l(track, 0);
8157 }
8158 }
8159}
8160
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008161status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8162{
8163 // only one chain per input thread
8164 if (mEffectChains.size() != 0) {
8165 return INVALID_OPERATION;
8166 }
Steve Block3856b092011-10-20 11:56:00 +01008167 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008168
8169 chain->setInBuffer(NULL);
8170 chain->setOutBuffer(NULL);
8171
Eric Laurent59255e42011-07-27 19:49:51 -07008172 checkSuspendOnAddEffectChain_l(chain);
8173
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008174 mEffectChains.add(chain);
8175
8176 return NO_ERROR;
8177}
8178
8179size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8180{
Steve Block3856b092011-10-20 11:56:00 +01008181 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00008182 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008183 "removeEffectChain_l() %p invalid chain size %d on thread %p",
8184 chain.get(), mEffectChains.size(), this);
8185 if (mEffectChains.size() == 1) {
8186 mEffectChains.removeAt(0);
8187 }
8188 return 0;
8189}
8190
Mathias Agopian65ab4712010-07-14 17:59:35 -07008191// ----------------------------------------------------------------------------
8192// EffectModule implementation
8193// ----------------------------------------------------------------------------
8194
8195#undef LOG_TAG
8196#define LOG_TAG "AudioFlinger::EffectModule"
8197
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008198AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008199 const wp<AudioFlinger::EffectChain>& chain,
8200 effect_descriptor_t *desc,
8201 int id,
8202 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07008203 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
8204 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07008205 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07008206 // mConfig is set by configure() and not used before then
8207 mEffectInterface(NULL),
8208 mStatus(NO_INIT), mState(IDLE),
8209 // mMaxDisableWaitCnt is set by configure() and not used before then
8210 // mDisableWaitCnt is set by process() and updateState() and not used before then
8211 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008212{
Steve Block3856b092011-10-20 11:56:00 +01008213 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008214 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008215
8216 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008217 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008218
8219 if (mStatus != NO_ERROR) {
8220 return;
8221 }
8222 lStatus = init();
8223 if (lStatus < 0) {
8224 mStatus = lStatus;
8225 goto Error;
8226 }
8227
Steve Block3856b092011-10-20 11:56:00 +01008228 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008229 return;
8230Error:
8231 EffectRelease(mEffectInterface);
8232 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008233 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008234}
8235
8236AudioFlinger::EffectModule::~EffectModule()
8237{
Steve Block3856b092011-10-20 11:56:00 +01008238 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008239 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008240 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8241 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8242 sp<ThreadBase> thread = mThread.promote();
8243 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008244 audio_stream_t *stream = thread->stream();
8245 if (stream != NULL) {
8246 stream->remove_audio_effect(stream, mEffectInterface);
8247 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008248 }
8249 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008250 // release effect engine
8251 EffectRelease(mEffectInterface);
8252 }
8253}
8254
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008255status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008256{
8257 status_t status;
8258
8259 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008260 int priority = handle->priority();
8261 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008262 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008263 size_t i;
8264 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008265 EffectHandle *h = mHandles[i];
8266 if (h == NULL || h->destroyed_l()) continue;
8267 // first non destroyed handle is considered in control
8268 if (controlHandle == NULL)
8269 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008270 if (h->priority() <= priority) break;
8271 }
8272 // if inserted in first place, move effect control from previous owner to this handle
8273 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008274 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008275 if (controlHandle != NULL) {
8276 enabled = controlHandle->enabled();
8277 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008278 }
Eric Laurent59255e42011-07-27 19:49:51 -07008279 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008280 status = NO_ERROR;
8281 } else {
8282 status = ALREADY_EXISTS;
8283 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008284 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008285 mHandles.insertAt(handle, i);
8286 return status;
8287}
8288
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008289size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008290{
8291 Mutex::Autolock _l(mLock);
8292 size_t size = mHandles.size();
8293 size_t i;
8294 for (i = 0; i < size; i++) {
8295 if (mHandles[i] == handle) break;
8296 }
8297 if (i == size) {
8298 return size;
8299 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008300 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008301
Mathias Agopian65ab4712010-07-14 17:59:35 -07008302 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008303 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008304 if (i == 0) {
8305 EffectHandle *h = controlHandle_l();
8306 if (h != NULL) {
8307 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008308 }
8309 }
8310
Eric Laurentec437d82011-07-26 20:54:46 -07008311 // Prevent calls to process() and other functions on effect interface from now on.
8312 // The effect engine will be released by the destructor when the last strong reference on
8313 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008314 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008315 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008316 }
8317
Eric Laurente65c8912012-07-20 15:57:23 -07008318 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008319}
8320
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008321// must be called with EffectModule::mLock held
8322AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008323{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008324 // the first valid handle in the list has control over the module
8325 for (size_t i = 0; i < mHandles.size(); i++) {
8326 EffectHandle *h = mHandles[i];
8327 if (h != NULL && !h->destroyed_l()) {
8328 return h;
8329 }
8330 }
8331
8332 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008333}
8334
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008335size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008336{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008337 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008338 // keep a strong reference on this EffectModule to avoid calling the
8339 // destructor before we exit
8340 sp<EffectModule> keep(this);
8341 {
8342 sp<ThreadBase> thread = mThread.promote();
8343 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008344 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008345 }
8346 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008347 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008348}
8349
8350void AudioFlinger::EffectModule::updateState() {
8351 Mutex::Autolock _l(mLock);
8352
8353 switch (mState) {
8354 case RESTART:
8355 reset_l();
8356 // FALL THROUGH
8357
8358 case STARTING:
8359 // clear auxiliary effect input buffer for next accumulation
8360 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8361 memset(mConfig.inputCfg.buffer.raw,
8362 0,
8363 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8364 }
8365 start_l();
8366 mState = ACTIVE;
8367 break;
8368 case STOPPING:
8369 stop_l();
8370 mDisableWaitCnt = mMaxDisableWaitCnt;
8371 mState = STOPPED;
8372 break;
8373 case STOPPED:
8374 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8375 // turn off sequence.
8376 if (--mDisableWaitCnt == 0) {
8377 reset_l();
8378 mState = IDLE;
8379 }
8380 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008381 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008382 break;
8383 }
8384}
8385
8386void AudioFlinger::EffectModule::process()
8387{
8388 Mutex::Autolock _l(mLock);
8389
Eric Laurentec437d82011-07-26 20:54:46 -07008390 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008391 mConfig.inputCfg.buffer.raw == NULL ||
8392 mConfig.outputCfg.buffer.raw == NULL) {
8393 return;
8394 }
8395
Eric Laurent8f45bd72010-08-31 13:50:07 -07008396 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008397 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8398 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008399 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008400 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008401 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008402 }
8403
8404 // do the actual processing in the effect engine
8405 int ret = (*mEffectInterface)->process(mEffectInterface,
8406 &mConfig.inputCfg.buffer,
8407 &mConfig.outputCfg.buffer);
8408
8409 // force transition to IDLE state when engine is ready
8410 if (mState == STOPPED && ret == -ENODATA) {
8411 mDisableWaitCnt = 1;
8412 }
8413
8414 // clear auxiliary effect input buffer for next accumulation
8415 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008416 memset(mConfig.inputCfg.buffer.raw, 0,
8417 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008418 }
8419 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008420 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8421 // If an insert effect is idle and input buffer is different from output buffer,
8422 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008423 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008424 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008425 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8426 int16_t *in = mConfig.inputCfg.buffer.s16;
8427 int16_t *out = mConfig.outputCfg.buffer.s16;
8428 for (size_t i = 0; i < frameCnt; i++) {
8429 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008430 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008431 }
8432 }
8433}
8434
8435void AudioFlinger::EffectModule::reset_l()
8436{
8437 if (mEffectInterface == NULL) {
8438 return;
8439 }
8440 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8441}
8442
8443status_t AudioFlinger::EffectModule::configure()
8444{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008445 if (mEffectInterface == NULL) {
8446 return NO_INIT;
8447 }
8448
8449 sp<ThreadBase> thread = mThread.promote();
8450 if (thread == 0) {
8451 return DEAD_OBJECT;
8452 }
8453
8454 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07008455 audio_channel_mask_t channelMask = thread->channelMask();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008456
8457 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008458 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008459 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07008460 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008461 }
Glenn Kasten254af182012-07-03 14:59:05 -07008462 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07008463 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8464 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008465 mConfig.inputCfg.samplingRate = thread->sampleRate();
8466 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8467 mConfig.inputCfg.bufferProvider.cookie = NULL;
8468 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8469 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8470 mConfig.outputCfg.bufferProvider.cookie = NULL;
8471 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8472 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8473 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8474 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008475 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008476 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008477 // - in other sessions:
8478 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8479 // other effect: overwrites output buffer: input buffer == output buffer
8480 // Auxiliary effect:
8481 // accumulates in output buffer: input buffer != output buffer
8482 // Therefore: accumulate <=> input buffer != output buffer
8483 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8484 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8485 } else {
8486 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8487 }
8488 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8489 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8490 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8491 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8492
Steve Block3856b092011-10-20 11:56:00 +01008493 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008494 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8495
Mathias Agopian65ab4712010-07-14 17:59:35 -07008496 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008497 uint32_t size = sizeof(int);
8498 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008499 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008500 sizeof(effect_config_t),
8501 &mConfig,
8502 &size,
8503 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008504 if (status == 0) {
8505 status = cmdStatus;
8506 }
8507
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008508 if (status == 0 &&
8509 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8510 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8511 effect_param_t *p = (effect_param_t *)buf32;
8512
8513 p->psize = sizeof(uint32_t);
8514 p->vsize = sizeof(uint32_t);
8515 size = sizeof(int);
8516 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8517
8518 uint32_t latency = 0;
8519 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8520 if (pbt != NULL) {
8521 latency = pbt->latency_l();
8522 }
8523
8524 *((int32_t *)p->data + 1)= latency;
8525 (*mEffectInterface)->command(mEffectInterface,
8526 EFFECT_CMD_SET_PARAM,
8527 sizeof(effect_param_t) + 8,
8528 &buf32,
8529 &size,
8530 &cmdStatus);
8531 }
8532
Mathias Agopian65ab4712010-07-14 17:59:35 -07008533 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8534 (1000 * mConfig.outputCfg.buffer.frameCount);
8535
8536 return status;
8537}
8538
8539status_t AudioFlinger::EffectModule::init()
8540{
8541 Mutex::Autolock _l(mLock);
8542 if (mEffectInterface == NULL) {
8543 return NO_INIT;
8544 }
8545 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008546 uint32_t size = sizeof(status_t);
8547 status_t status = (*mEffectInterface)->command(mEffectInterface,
8548 EFFECT_CMD_INIT,
8549 0,
8550 NULL,
8551 &size,
8552 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008553 if (status == 0) {
8554 status = cmdStatus;
8555 }
8556 return status;
8557}
8558
Eric Laurentec35a142011-10-05 17:42:25 -07008559status_t AudioFlinger::EffectModule::start()
8560{
8561 Mutex::Autolock _l(mLock);
8562 return start_l();
8563}
8564
Mathias Agopian65ab4712010-07-14 17:59:35 -07008565status_t AudioFlinger::EffectModule::start_l()
8566{
8567 if (mEffectInterface == NULL) {
8568 return NO_INIT;
8569 }
8570 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008571 uint32_t size = sizeof(status_t);
8572 status_t status = (*mEffectInterface)->command(mEffectInterface,
8573 EFFECT_CMD_ENABLE,
8574 0,
8575 NULL,
8576 &size,
8577 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008578 if (status == 0) {
8579 status = cmdStatus;
8580 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008581 if (status == 0 &&
8582 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8583 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8584 sp<ThreadBase> thread = mThread.promote();
8585 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008586 audio_stream_t *stream = thread->stream();
8587 if (stream != NULL) {
8588 stream->add_audio_effect(stream, mEffectInterface);
8589 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008590 }
8591 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008592 return status;
8593}
8594
Eric Laurentec437d82011-07-26 20:54:46 -07008595status_t AudioFlinger::EffectModule::stop()
8596{
8597 Mutex::Autolock _l(mLock);
8598 return stop_l();
8599}
8600
Mathias Agopian65ab4712010-07-14 17:59:35 -07008601status_t AudioFlinger::EffectModule::stop_l()
8602{
8603 if (mEffectInterface == NULL) {
8604 return NO_INIT;
8605 }
8606 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008607 uint32_t size = sizeof(status_t);
8608 status_t status = (*mEffectInterface)->command(mEffectInterface,
8609 EFFECT_CMD_DISABLE,
8610 0,
8611 NULL,
8612 &size,
8613 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008614 if (status == 0) {
8615 status = cmdStatus;
8616 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008617 if (status == 0 &&
8618 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8619 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8620 sp<ThreadBase> thread = mThread.promote();
8621 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008622 audio_stream_t *stream = thread->stream();
8623 if (stream != NULL) {
8624 stream->remove_audio_effect(stream, mEffectInterface);
8625 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008626 }
8627 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008628 return status;
8629}
8630
Eric Laurent25f43952010-07-28 05:40:18 -07008631status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8632 uint32_t cmdSize,
8633 void *pCmdData,
8634 uint32_t *replySize,
8635 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008636{
8637 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008638// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008639
Eric Laurentec437d82011-07-26 20:54:46 -07008640 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008641 return NO_INIT;
8642 }
Eric Laurent25f43952010-07-28 05:40:18 -07008643 status_t status = (*mEffectInterface)->command(mEffectInterface,
8644 cmdCode,
8645 cmdSize,
8646 pCmdData,
8647 replySize,
8648 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008649 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008650 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008651 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008652 EffectHandle *h = mHandles[i];
8653 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008654 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8655 }
8656 }
8657 }
8658 return status;
8659}
8660
8661status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8662{
8663 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008664 return setEnabled_l(enabled);
8665}
8666
8667// must be called with EffectModule::mLock held
8668status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8669{
8670
Steve Block3856b092011-10-20 11:56:00 +01008671 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008672
8673 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008674 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8675 if (enabled && status != NO_ERROR) {
8676 return status;
8677 }
8678
Mathias Agopian65ab4712010-07-14 17:59:35 -07008679 switch (mState) {
8680 // going from disabled to enabled
8681 case IDLE:
8682 mState = STARTING;
8683 break;
8684 case STOPPED:
8685 mState = RESTART;
8686 break;
8687 case STOPPING:
8688 mState = ACTIVE;
8689 break;
8690
8691 // going from enabled to disabled
8692 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008693 mState = STOPPED;
8694 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008695 case STARTING:
8696 mState = IDLE;
8697 break;
8698 case ACTIVE:
8699 mState = STOPPING;
8700 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008701 case DESTROYED:
8702 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008703 }
8704 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008705 EffectHandle *h = mHandles[i];
8706 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008707 h->setEnabled(enabled);
8708 }
8709 }
8710 }
8711 return NO_ERROR;
8712}
8713
Glenn Kastenc59c0042012-02-02 14:06:11 -08008714bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008715{
8716 switch (mState) {
8717 case RESTART:
8718 case STARTING:
8719 case ACTIVE:
8720 return true;
8721 case IDLE:
8722 case STOPPING:
8723 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008724 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008725 default:
8726 return false;
8727 }
8728}
8729
Glenn Kastenc59c0042012-02-02 14:06:11 -08008730bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008731{
8732 switch (mState) {
8733 case RESTART:
8734 case ACTIVE:
8735 case STOPPING:
8736 case STOPPED:
8737 return true;
8738 case IDLE:
8739 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008740 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008741 default:
8742 return false;
8743 }
8744}
8745
Mathias Agopian65ab4712010-07-14 17:59:35 -07008746status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8747{
8748 Mutex::Autolock _l(mLock);
8749 status_t status = NO_ERROR;
8750
8751 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8752 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008753 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008754 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8755 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008756 status_t cmdStatus;
8757 uint32_t volume[2];
8758 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008759 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008760 volume[0] = *left;
8761 volume[1] = *right;
8762 if (controller) {
8763 pVolume = volume;
8764 }
Eric Laurent25f43952010-07-28 05:40:18 -07008765 status = (*mEffectInterface)->command(mEffectInterface,
8766 EFFECT_CMD_SET_VOLUME,
8767 size,
8768 volume,
8769 &size,
8770 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008771 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8772 *left = volume[0];
8773 *right = volume[1];
8774 }
8775 }
8776 return status;
8777}
8778
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008779status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008780{
Eric Laurentf1c04f92012-08-28 14:26:53 -07008781 if (device == AUDIO_DEVICE_NONE) {
8782 return NO_ERROR;
8783 }
8784
Mathias Agopian65ab4712010-07-14 17:59:35 -07008785 Mutex::Autolock _l(mLock);
8786 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008787 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07008788 status_t cmdStatus;
8789 uint32_t size = sizeof(status_t);
8790 uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE :
8791 EFFECT_CMD_SET_INPUT_DEVICE;
8792 status = (*mEffectInterface)->command(mEffectInterface,
8793 cmd,
8794 sizeof(uint32_t),
8795 &device,
8796 &size,
8797 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008798 }
8799 return status;
8800}
8801
Glenn Kastenf78aee72012-01-04 11:00:47 -08008802status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008803{
8804 Mutex::Autolock _l(mLock);
8805 status_t status = NO_ERROR;
8806 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008807 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008808 uint32_t size = sizeof(status_t);
8809 status = (*mEffectInterface)->command(mEffectInterface,
8810 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008811 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008812 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008813 &size,
8814 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008815 if (status == NO_ERROR) {
8816 status = cmdStatus;
8817 }
8818 }
8819 return status;
8820}
8821
Eric Laurent57b2dd12012-08-31 17:44:06 -07008822status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
8823{
8824 Mutex::Autolock _l(mLock);
8825 status_t status = NO_ERROR;
8826 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
8827 uint32_t size = 0;
8828 status = (*mEffectInterface)->command(mEffectInterface,
8829 EFFECT_CMD_SET_AUDIO_SOURCE,
8830 sizeof(audio_source_t),
8831 &source,
8832 &size,
8833 NULL);
8834 }
8835 return status;
8836}
8837
Eric Laurent59255e42011-07-27 19:49:51 -07008838void AudioFlinger::EffectModule::setSuspended(bool suspended)
8839{
8840 Mutex::Autolock _l(mLock);
8841 mSuspended = suspended;
8842}
Glenn Kastena3a85482012-01-04 11:01:11 -08008843
8844bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008845{
8846 Mutex::Autolock _l(mLock);
8847 return mSuspended;
8848}
8849
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008850bool AudioFlinger::EffectModule::purgeHandles()
8851{
8852 bool enabled = false;
8853 Mutex::Autolock _l(mLock);
8854 for (size_t i = 0; i < mHandles.size(); i++) {
8855 EffectHandle *handle = mHandles[i];
8856 if (handle != NULL && !handle->destroyed_l()) {
8857 handle->effect().clear();
8858 if (handle->hasControl()) {
8859 enabled = handle->enabled();
8860 }
8861 }
8862 }
8863 return enabled;
8864}
8865
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07008866void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008867{
8868 const size_t SIZE = 256;
8869 char buffer[SIZE];
8870 String8 result;
8871
8872 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8873 result.append(buffer);
8874
8875 bool locked = tryLock(mLock);
8876 // failed to lock - AudioFlinger is probably deadlocked
8877 if (!locked) {
8878 result.append("\t\tCould not lock Fx mutex:\n");
8879 }
8880
8881 result.append("\t\tSession Status State Engine:\n");
8882 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8883 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8884 result.append(buffer);
8885
8886 result.append("\t\tDescriptor:\n");
8887 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8888 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8889 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8890 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8891 result.append(buffer);
8892 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8893 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8894 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8895 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8896 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008897 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008898 mDescriptor.apiVersion,
8899 mDescriptor.flags);
8900 result.append(buffer);
8901 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8902 mDescriptor.name);
8903 result.append(buffer);
8904 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8905 mDescriptor.implementor);
8906 result.append(buffer);
8907
8908 result.append("\t\t- Input configuration:\n");
8909 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8910 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8911 (uint32_t)mConfig.inputCfg.buffer.raw,
8912 mConfig.inputCfg.buffer.frameCount,
8913 mConfig.inputCfg.samplingRate,
8914 mConfig.inputCfg.channels,
8915 mConfig.inputCfg.format);
8916 result.append(buffer);
8917
8918 result.append("\t\t- Output configuration:\n");
8919 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8920 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8921 (uint32_t)mConfig.outputCfg.buffer.raw,
8922 mConfig.outputCfg.buffer.frameCount,
8923 mConfig.outputCfg.samplingRate,
8924 mConfig.outputCfg.channels,
8925 mConfig.outputCfg.format);
8926 result.append(buffer);
8927
8928 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8929 result.append(buffer);
8930 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8931 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008932 EffectHandle *handle = mHandles[i];
8933 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008934 handle->dump(buffer, SIZE);
8935 result.append(buffer);
8936 }
8937 }
8938
8939 result.append("\n");
8940
8941 write(fd, result.string(), result.length());
8942
8943 if (locked) {
8944 mLock.unlock();
8945 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008946}
8947
8948// ----------------------------------------------------------------------------
8949// EffectHandle implementation
8950// ----------------------------------------------------------------------------
8951
8952#undef LOG_TAG
8953#define LOG_TAG "AudioFlinger::EffectHandle"
8954
8955AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8956 const sp<AudioFlinger::Client>& client,
8957 const sp<IEffectClient>& effectClient,
8958 int32_t priority)
8959 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008960 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008961 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008962{
Steve Block3856b092011-10-20 11:56:00 +01008963 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008964
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008965 if (client == 0) {
8966 return;
8967 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008968 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8969 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8970 if (mCblkMemory != 0) {
8971 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8972
Glenn Kastena0d68332012-01-27 16:47:15 -08008973 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008974 new(mCblk) effect_param_cblk_t();
8975 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008976 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008977 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008978 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008979 return;
8980 }
8981}
8982
8983AudioFlinger::EffectHandle::~EffectHandle()
8984{
Steve Block3856b092011-10-20 11:56:00 +01008985 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008986
8987 if (mEffect == 0) {
8988 mDestroyed = true;
8989 return;
8990 }
8991 mEffect->lock();
8992 mDestroyed = true;
8993 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008994 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008995}
8996
8997status_t AudioFlinger::EffectHandle::enable()
8998{
Steve Block3856b092011-10-20 11:56:00 +01008999 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009000 if (!mHasControl) return INVALID_OPERATION;
9001 if (mEffect == 0) return DEAD_OBJECT;
9002
Eric Laurentdb7c0792011-08-10 10:37:50 -07009003 if (mEnabled) {
9004 return NO_ERROR;
9005 }
9006
Eric Laurent59255e42011-07-27 19:49:51 -07009007 mEnabled = true;
9008
9009 sp<ThreadBase> thread = mEffect->thread().promote();
9010 if (thread != 0) {
9011 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
9012 }
9013
9014 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
9015 if (mEffect->suspended()) {
9016 return NO_ERROR;
9017 }
9018
Eric Laurentdb7c0792011-08-10 10:37:50 -07009019 status_t status = mEffect->setEnabled(true);
9020 if (status != NO_ERROR) {
9021 if (thread != 0) {
9022 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9023 }
9024 mEnabled = false;
9025 }
9026 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009027}
9028
9029status_t AudioFlinger::EffectHandle::disable()
9030{
Steve Block3856b092011-10-20 11:56:00 +01009031 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009032 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07009033 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009034
Eric Laurentdb7c0792011-08-10 10:37:50 -07009035 if (!mEnabled) {
9036 return NO_ERROR;
9037 }
Eric Laurent59255e42011-07-27 19:49:51 -07009038 mEnabled = false;
9039
9040 if (mEffect->suspended()) {
9041 return NO_ERROR;
9042 }
9043
9044 status_t status = mEffect->setEnabled(false);
9045
9046 sp<ThreadBase> thread = mEffect->thread().promote();
9047 if (thread != 0) {
9048 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9049 }
9050
9051 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009052}
9053
9054void AudioFlinger::EffectHandle::disconnect()
9055{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009056 disconnect(true);
9057}
9058
Glenn Kasten58123c32012-02-03 10:32:24 -08009059void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009060{
Glenn Kasten58123c32012-02-03 10:32:24 -08009061 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009062 if (mEffect == 0) {
9063 return;
9064 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009065 // restore suspended effects if the disconnected handle was enabled and the last one.
9066 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009067 sp<ThreadBase> thread = mEffect->thread().promote();
9068 if (thread != 0) {
9069 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9070 }
Eric Laurent59255e42011-07-27 19:49:51 -07009071 }
9072
Mathias Agopian65ab4712010-07-14 17:59:35 -07009073 // release sp on module => module destructor can be called now
9074 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009075 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08009076 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08009077 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009078 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
9079 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08009080 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08009081 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07009082 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
9083 mClient.clear();
9084 }
9085}
9086
Eric Laurent25f43952010-07-28 05:40:18 -07009087status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
9088 uint32_t cmdSize,
9089 void *pCmdData,
9090 uint32_t *replySize,
9091 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009092{
Steve Block3856b092011-10-20 11:56:00 +01009093// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07009094// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07009095
9096 // only get parameter command is permitted for applications not controlling the effect
9097 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
9098 return INVALID_OPERATION;
9099 }
9100 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009101 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009102
9103 // handle commands that are not forwarded transparently to effect engine
9104 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
9105 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
9106 // no risk to block the whole media server process or mixer threads is we are stuck here
9107 Mutex::Autolock _l(mCblk->lock);
9108 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
9109 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
9110 mCblk->serverIndex = 0;
9111 mCblk->clientIndex = 0;
9112 return BAD_VALUE;
9113 }
9114 status_t status = NO_ERROR;
9115 while (mCblk->serverIndex < mCblk->clientIndex) {
9116 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07009117 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009118 int *p = (int *)(mBuffer + mCblk->serverIndex);
9119 int size = *p++;
9120 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009121 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009122 break;
9123 }
9124 effect_param_t *param = (effect_param_t *)p;
9125 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009126 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009127 mCblk->serverIndex += size;
9128 continue;
9129 }
Eric Laurent25f43952010-07-28 05:40:18 -07009130 uint32_t psize = sizeof(effect_param_t) +
9131 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
9132 param->vsize;
9133 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
9134 psize,
9135 p,
9136 &rsize,
9137 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07009138 // stop at first error encountered
9139 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009140 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07009141 *(int *)pReplyData = reply;
9142 break;
9143 } else if (reply != NO_ERROR) {
9144 *(int *)pReplyData = reply;
9145 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009146 }
9147 mCblk->serverIndex += size;
9148 }
9149 mCblk->serverIndex = 0;
9150 mCblk->clientIndex = 0;
9151 return status;
9152 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009153 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009154 return enable();
9155 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009156 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009157 return disable();
9158 }
9159
9160 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9161}
9162
Eric Laurent59255e42011-07-27 19:49:51 -07009163void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009164{
Steve Block3856b092011-10-20 11:56:00 +01009165 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009166
9167 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07009168 mEnabled = enabled;
9169
Mathias Agopian65ab4712010-07-14 17:59:35 -07009170 if (signal && mEffectClient != 0) {
9171 mEffectClient->controlStatusChanged(hasControl);
9172 }
9173}
9174
Eric Laurent25f43952010-07-28 05:40:18 -07009175void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
9176 uint32_t cmdSize,
9177 void *pCmdData,
9178 uint32_t replySize,
9179 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009180{
9181 if (mEffectClient != 0) {
9182 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9183 }
9184}
9185
9186
9187
9188void AudioFlinger::EffectHandle::setEnabled(bool enabled)
9189{
9190 if (mEffectClient != 0) {
9191 mEffectClient->enableStatusChanged(enabled);
9192 }
9193}
9194
9195status_t AudioFlinger::EffectHandle::onTransact(
9196 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9197{
9198 return BnEffect::onTransact(code, data, reply, flags);
9199}
9200
9201
9202void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
9203{
Glenn Kastena0d68332012-01-27 16:47:15 -08009204 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009205
9206 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08009207 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07009208 mPriority,
9209 mHasControl,
9210 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009211 mCblk ? mCblk->clientIndex : 0,
9212 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07009213 );
9214
9215 if (locked) {
9216 mCblk->lock.unlock();
9217 }
9218}
9219
9220#undef LOG_TAG
9221#define LOG_TAG "AudioFlinger::EffectChain"
9222
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009223AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009224 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009225 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07009226 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9227 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009228{
Dima Zavinfce7a472011-04-19 22:30:36 -07009229 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009230 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009231 return;
9232 }
9233 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9234 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009235}
9236
9237AudioFlinger::EffectChain::~EffectChain()
9238{
9239 if (mOwnInBuffer) {
9240 delete mInBuffer;
9241 }
9242
9243}
9244
Eric Laurent59255e42011-07-27 19:49:51 -07009245// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009246sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009247{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009248 size_t size = mEffects.size();
9249
9250 for (size_t i = 0; i < size; i++) {
9251 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009252 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009253 }
9254 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009255 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009256}
9257
Eric Laurent59255e42011-07-27 19:49:51 -07009258// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009259sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009260{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009261 size_t size = mEffects.size();
9262
9263 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009264 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9265 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009266 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009267 }
9268 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009269 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009270}
9271
Eric Laurent59255e42011-07-27 19:49:51 -07009272// getEffectFromType_l() must be called with ThreadBase::mLock held
9273sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9274 const effect_uuid_t *type)
9275{
Eric Laurent59255e42011-07-27 19:49:51 -07009276 size_t size = mEffects.size();
9277
9278 for (size_t i = 0; i < size; i++) {
9279 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009280 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009281 }
9282 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009283 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009284}
9285
Eric Laurent91b14c42012-05-30 12:30:29 -07009286void AudioFlinger::EffectChain::clearInputBuffer()
9287{
9288 Mutex::Autolock _l(mLock);
9289 sp<ThreadBase> thread = mThread.promote();
9290 if (thread == 0) {
9291 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9292 return;
9293 }
9294 clearInputBuffer_l(thread);
9295}
9296
9297// Must be called with EffectChain::mLock locked
9298void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9299{
9300 size_t numSamples = thread->frameCount() * thread->channelCount();
9301 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9302
9303}
9304
Mathias Agopian65ab4712010-07-14 17:59:35 -07009305// Must be called with EffectChain::mLock locked
9306void AudioFlinger::EffectChain::process_l()
9307{
Eric Laurentdac69112010-09-28 14:09:57 -07009308 sp<ThreadBase> thread = mThread.promote();
9309 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009310 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009311 return;
9312 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009313 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9314 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009315 // always process effects unless no more tracks are on the session and the effect tail
9316 // has been rendered
9317 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009318 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009319 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009320
Eric Laurent544fe9b2011-11-11 15:42:52 -08009321 if (!tracksOnSession && mTailBufferCount == 0) {
9322 doProcess = false;
9323 }
9324
9325 if (activeTrackCnt() == 0) {
9326 // if no track is active and the effect tail has not been rendered,
9327 // the input buffer must be cleared here as the mixer process will not do it
9328 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009329 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009330 if (mTailBufferCount > 0) {
9331 mTailBufferCount--;
9332 }
9333 }
9334 }
Eric Laurentdac69112010-09-28 14:09:57 -07009335 }
9336
Mathias Agopian65ab4712010-07-14 17:59:35 -07009337 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009338 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009339 for (size_t i = 0; i < size; i++) {
9340 mEffects[i]->process();
9341 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009342 }
9343 for (size_t i = 0; i < size; i++) {
9344 mEffects[i]->updateState();
9345 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009346}
9347
Eric Laurentcab11242010-07-15 12:50:15 -07009348// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009349status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009350{
9351 effect_descriptor_t desc = effect->desc();
9352 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9353
9354 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009355 effect->setChain(this);
9356 sp<ThreadBase> thread = mThread.promote();
9357 if (thread == 0) {
9358 return NO_INIT;
9359 }
9360 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009361
9362 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9363 // Auxiliary effects are inserted at the beginning of mEffects vector as
9364 // they are processed first and accumulated in chain input buffer
9365 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009366
Mathias Agopian65ab4712010-07-14 17:59:35 -07009367 // the input buffer for auxiliary effect contains mono samples in
9368 // 32 bit format. This is to avoid saturation in AudoMixer
9369 // accumulation stage. Saturation is done in EffectModule::process() before
9370 // calling the process in effect engine
9371 size_t numSamples = thread->frameCount();
9372 int32_t *buffer = new int32_t[numSamples];
9373 memset(buffer, 0, numSamples * sizeof(int32_t));
9374 effect->setInBuffer((int16_t *)buffer);
9375 // auxiliary effects output samples to chain input buffer for further processing
9376 // by insert effects
9377 effect->setOutBuffer(mInBuffer);
9378 } else {
9379 // Insert effects are inserted at the end of mEffects vector as they are processed
9380 // after track and auxiliary effects.
9381 // Insert effect order as a function of indicated preference:
9382 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9383 // another effect is present
9384 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9385 // last effect claiming first position
9386 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9387 // first effect claiming last position
9388 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9389 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9390 // already present
9391
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009392 size_t size = mEffects.size();
9393 size_t idx_insert = size;
9394 ssize_t idx_insert_first = -1;
9395 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009396
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009397 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009398 effect_descriptor_t d = mEffects[i]->desc();
9399 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9400 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9401 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9402 // check invalid effect chaining combinations
9403 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9404 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009405 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009406 return INVALID_OPERATION;
9407 }
9408 // remember position of first insert effect and by default
9409 // select this as insert position for new effect
9410 if (idx_insert == size) {
9411 idx_insert = i;
9412 }
9413 // remember position of last insert effect claiming
9414 // first position
9415 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9416 idx_insert_first = i;
9417 }
9418 // remember position of first insert effect claiming
9419 // last position
9420 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9421 idx_insert_last == -1) {
9422 idx_insert_last = i;
9423 }
9424 }
9425 }
9426
9427 // modify idx_insert from first position if needed
9428 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9429 if (idx_insert_last != -1) {
9430 idx_insert = idx_insert_last;
9431 } else {
9432 idx_insert = size;
9433 }
9434 } else {
9435 if (idx_insert_first != -1) {
9436 idx_insert = idx_insert_first + 1;
9437 }
9438 }
9439
9440 // always read samples from chain input buffer
9441 effect->setInBuffer(mInBuffer);
9442
9443 // if last effect in the chain, output samples to chain
9444 // output buffer, otherwise to chain input buffer
9445 if (idx_insert == size) {
9446 if (idx_insert != 0) {
9447 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9448 mEffects[idx_insert-1]->configure();
9449 }
9450 effect->setOutBuffer(mOutBuffer);
9451 } else {
9452 effect->setOutBuffer(mInBuffer);
9453 }
9454 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009455
Steve Block3856b092011-10-20 11:56:00 +01009456 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009457 }
9458 effect->configure();
9459 return NO_ERROR;
9460}
9461
Eric Laurentcab11242010-07-15 12:50:15 -07009462// removeEffect_l() must be called with PlaybackThread::mLock held
9463size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009464{
9465 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009466 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009467 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9468
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009469 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009470 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009471 // calling stop here will remove pre-processing effect from the audio HAL.
9472 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9473 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009474 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9475 mEffects[i]->state() == EffectModule::STOPPING) {
9476 mEffects[i]->stop();
9477 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009478 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9479 delete[] effect->inBuffer();
9480 } else {
9481 if (i == size - 1 && i != 0) {
9482 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9483 mEffects[i - 1]->configure();
9484 }
9485 }
9486 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009487 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009488 break;
9489 }
9490 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009491
9492 return mEffects.size();
9493}
9494
Eric Laurentcab11242010-07-15 12:50:15 -07009495// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009496void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009497{
9498 size_t size = mEffects.size();
9499 for (size_t i = 0; i < size; i++) {
9500 mEffects[i]->setDevice(device);
9501 }
9502}
9503
Eric Laurentcab11242010-07-15 12:50:15 -07009504// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009505void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009506{
9507 size_t size = mEffects.size();
9508 for (size_t i = 0; i < size; i++) {
9509 mEffects[i]->setMode(mode);
9510 }
9511}
9512
Eric Laurent57b2dd12012-08-31 17:44:06 -07009513// setAudioSource_l() must be called with PlaybackThread::mLock held
9514void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
9515{
9516 size_t size = mEffects.size();
9517 for (size_t i = 0; i < size; i++) {
9518 mEffects[i]->setAudioSource(source);
9519 }
9520}
9521
Eric Laurentcab11242010-07-15 12:50:15 -07009522// setVolume_l() must be called with PlaybackThread::mLock held
9523bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009524{
9525 uint32_t newLeft = *left;
9526 uint32_t newRight = *right;
9527 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009528 int ctrlIdx = -1;
9529 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009530
Eric Laurentcab11242010-07-15 12:50:15 -07009531 // first update volume controller
9532 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009533 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009534 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9535 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009536 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009537 break;
9538 }
9539 }
9540
9541 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009542 if (hasControl) {
9543 *left = mNewLeftVolume;
9544 *right = mNewRightVolume;
9545 }
9546 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009547 }
9548
9549 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009550 mLeftVolume = newLeft;
9551 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009552
9553 // second get volume update from volume controller
9554 if (ctrlIdx >= 0) {
9555 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009556 mNewLeftVolume = newLeft;
9557 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009558 }
9559 // then indicate volume to all other effects in chain.
9560 // Pass altered volume to effects before volume controller
9561 // and requested volume to effects after controller
9562 uint32_t lVol = newLeft;
9563 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009564
Mathias Agopian65ab4712010-07-14 17:59:35 -07009565 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009566 if ((int)i == ctrlIdx) continue;
9567 // this also works for ctrlIdx == -1 when there is no volume controller
9568 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009569 lVol = *left;
9570 rVol = *right;
9571 }
9572 mEffects[i]->setVolume(&lVol, &rVol, false);
9573 }
9574 *left = newLeft;
9575 *right = newRight;
9576
9577 return hasControl;
9578}
9579
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009580void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009581{
9582 const size_t SIZE = 256;
9583 char buffer[SIZE];
9584 String8 result;
9585
9586 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9587 result.append(buffer);
9588
9589 bool locked = tryLock(mLock);
9590 // failed to lock - AudioFlinger is probably deadlocked
9591 if (!locked) {
9592 result.append("\tCould not lock mutex:\n");
9593 }
9594
Eric Laurentcab11242010-07-15 12:50:15 -07009595 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9596 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009597 mEffects.size(),
9598 (uint32_t)mInBuffer,
9599 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009600 mActiveTrackCnt);
9601 result.append(buffer);
9602 write(fd, result.string(), result.size());
9603
9604 for (size_t i = 0; i < mEffects.size(); ++i) {
9605 sp<EffectModule> effect = mEffects[i];
9606 if (effect != 0) {
9607 effect->dump(fd, args);
9608 }
9609 }
9610
9611 if (locked) {
9612 mLock.unlock();
9613 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009614}
9615
Eric Laurent59255e42011-07-27 19:49:51 -07009616// must be called with ThreadBase::mLock held
9617void AudioFlinger::EffectChain::setEffectSuspended_l(
9618 const effect_uuid_t *type, bool suspend)
9619{
9620 sp<SuspendedEffectDesc> desc;
9621 // use effect type UUID timelow as key as there is no real risk of identical
9622 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009623 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009624 if (suspend) {
9625 if (index >= 0) {
9626 desc = mSuspendedEffects.valueAt(index);
9627 } else {
9628 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -08009629 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07009630 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009631 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009632 }
9633 if (desc->mRefCount++ == 0) {
9634 sp<EffectModule> effect = getEffectIfEnabled(type);
9635 if (effect != 0) {
9636 desc->mEffect = effect;
9637 effect->setSuspended(true);
9638 effect->setEnabled(false);
9639 }
9640 }
9641 } else {
9642 if (index < 0) {
9643 return;
9644 }
9645 desc = mSuspendedEffects.valueAt(index);
9646 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009647 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009648 desc->mRefCount = 1;
9649 }
9650 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009651 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009652 if (desc->mEffect != 0) {
9653 sp<EffectModule> effect = desc->mEffect.promote();
9654 if (effect != 0) {
9655 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009656 effect->lock();
9657 EffectHandle *handle = effect->controlHandle_l();
9658 if (handle != NULL && !handle->destroyed_l()) {
9659 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009660 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009661 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009662 }
9663 desc->mEffect.clear();
9664 }
9665 mSuspendedEffects.removeItemsAt(index);
9666 }
9667 }
9668}
9669
9670// must be called with ThreadBase::mLock held
9671void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9672{
9673 sp<SuspendedEffectDesc> desc;
9674
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009675 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009676 if (suspend) {
9677 if (index >= 0) {
9678 desc = mSuspendedEffects.valueAt(index);
9679 } else {
9680 desc = new SuspendedEffectDesc();
9681 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009682 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009683 }
9684 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009685 Vector< sp<EffectModule> > effects;
9686 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009687 for (size_t i = 0; i < effects.size(); i++) {
9688 setEffectSuspended_l(&effects[i]->desc().type, true);
9689 }
9690 }
9691 } else {
9692 if (index < 0) {
9693 return;
9694 }
9695 desc = mSuspendedEffects.valueAt(index);
9696 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009697 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009698 desc->mRefCount = 1;
9699 }
9700 if (--desc->mRefCount == 0) {
9701 Vector<const effect_uuid_t *> types;
9702 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9703 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9704 continue;
9705 }
9706 types.add(&mSuspendedEffects.valueAt(i)->mType);
9707 }
9708 for (size_t i = 0; i < types.size(); i++) {
9709 setEffectSuspended_l(types[i], false);
9710 }
Steve Block3856b092011-10-20 11:56:00 +01009711 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009712 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9713 }
9714 }
9715}
9716
Eric Laurent6bffdb82011-09-23 08:40:41 -07009717
9718// The volume effect is used for automated tests only
9719#ifndef OPENSL_ES_H_
9720static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9721 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9722const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9723#endif //OPENSL_ES_H_
9724
Eric Laurentdb7c0792011-08-10 10:37:50 -07009725bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9726{
9727 // auxiliary effects and visualizer are never suspended on output mix
9728 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9729 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009730 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9731 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009732 return false;
9733 }
9734 return true;
9735}
9736
Glenn Kastend0539712012-01-30 12:56:03 -08009737void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009738{
Glenn Kastend0539712012-01-30 12:56:03 -08009739 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009740 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009741 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9742 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009743 }
Eric Laurent59255e42011-07-27 19:49:51 -07009744 }
Eric Laurent59255e42011-07-27 19:49:51 -07009745}
9746
9747sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9748 const effect_uuid_t *type)
9749{
Glenn Kasten090f0192012-01-30 13:00:02 -08009750 sp<EffectModule> effect = getEffectFromType_l(type);
9751 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009752}
9753
9754void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9755 bool enabled)
9756{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009757 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009758 if (enabled) {
9759 if (index < 0) {
9760 // if the effect is not suspend check if all effects are suspended
9761 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9762 if (index < 0) {
9763 return;
9764 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009765 if (!isEffectEligibleForSuspend(effect->desc())) {
9766 return;
9767 }
Eric Laurent59255e42011-07-27 19:49:51 -07009768 setEffectSuspended_l(&effect->desc().type, enabled);
9769 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009770 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009771 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009772 return;
9773 }
Eric Laurent59255e42011-07-27 19:49:51 -07009774 }
Steve Block3856b092011-10-20 11:56:00 +01009775 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009776 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009777 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9778 // if effect is requested to suspended but was not yet enabled, supend it now.
9779 if (desc->mEffect == 0) {
9780 desc->mEffect = effect;
9781 effect->setEnabled(false);
9782 effect->setSuspended(true);
9783 }
9784 } else {
9785 if (index < 0) {
9786 return;
9787 }
Steve Block3856b092011-10-20 11:56:00 +01009788 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009789 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009790 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9791 desc->mEffect.clear();
9792 effect->setSuspended(false);
9793 }
9794}
9795
Mathias Agopian65ab4712010-07-14 17:59:35 -07009796#undef LOG_TAG
9797#define LOG_TAG "AudioFlinger"
9798
9799// ----------------------------------------------------------------------------
9800
9801status_t AudioFlinger::onTransact(
9802 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9803{
9804 return BnAudioFlinger::onTransact(code, data, reply, flags);
9805}
9806
Mathias Agopian65ab4712010-07-14 17:59:35 -07009807}; // namespace android