blob: 35bd431820d23a10eccef61b4ec2af469d3051dc [file] [log] [blame]
Glenn Kasten99e53b82012-01-19 08:59:58 -08001/*
Mathias Agopian65ab4712010-07-14 17:59:35 -07002**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070030#include <utils/Trace.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070031#include <binder/Parcel.h>
32#include <binder/IPCThreadState.h>
33#include <utils/String16.h>
34#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070035#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070036
Dima Zavinfce7a472011-04-19 22:30:36 -070037#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080039#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040
Glenn Kastend3cee2f2012-03-13 17:55:35 -070041#undef ADD_BATTERY_DATA
42
43#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -080044#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080045#include <media/IMediaDeathNotifier.h>
Glenn Kastend3cee2f2012-03-13 17:55:35 -070046#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070047
48#include <private/media/AudioTrackShared.h>
49#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070050
Dima Zavin64760242011-05-11 14:15:23 -070051#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070052#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070053
54#include "AudioMixer.h"
55#include "AudioFlinger.h"
Glenn Kasten44deb052012-02-05 18:09:08 -080056#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070059#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070060#include <audio_effects/effect_ns.h>
61#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Glenn Kasten3b21c502011-12-15 09:52:39 -080063#include <audio_utils/primitives.h>
64
Eric Laurentfeb0db62011-07-22 09:04:31 -070065#include <powermanager/PowerManager.h>
Glenn Kasten190a46f2012-03-06 11:27:10 -080066
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070067// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
Glenn Kasten190a46f2012-03-06 11:27:10 -080068#ifdef DEBUG_CPU_USAGE
69#include <cpustats/CentralTendencyStatistics.h>
70#include <cpustats/ThreadCpuUsage.h>
71#endif
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070072
John Grossman4ff14ba2012-02-08 16:37:41 -080073#include <common_time/cc_helper.h>
74#include <common_time/local_clock.h>
75
Glenn Kasten58912562012-04-03 10:45:00 -070076#include "FastMixer.h"
77
78// NBAIO implementations
Glenn Kasten2dd4bdd2012-08-29 11:10:32 -070079#include <media/nbaio/AudioStreamOutSink.h>
80#include <media/nbaio/MonoPipe.h>
81#include <media/nbaio/MonoPipeReader.h>
82#include <media/nbaio/Pipe.h>
83#include <media/nbaio/PipeReader.h>
84#include <media/nbaio/SourceAudioBufferProvider.h>
Glenn Kasten58912562012-04-03 10:45:00 -070085
Glenn Kasten1dc28b72012-04-24 10:01:03 -070086#include "SchedulingPolicyService.h"
Glenn Kasten58912562012-04-03 10:45:00 -070087
Mathias Agopian65ab4712010-07-14 17:59:35 -070088// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
John Grossman1c345192012-03-27 14:00:17 -070090// Note: the following macro is used for extremely verbose logging message. In
91// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
92// 0; but one side effect of this is to turn all LOGV's as well. Some messages
93// are so verbose that we want to suppress them even when we have ALOG_ASSERT
94// turned on. Do not uncomment the #def below unless you really know what you
95// are doing and want to see all of the extremely verbose messages.
96//#define VERY_VERY_VERBOSE_LOGGING
97#ifdef VERY_VERY_VERBOSE_LOGGING
98#define ALOGVV ALOGV
99#else
100#define ALOGVV(a...) do { } while(0)
101#endif
Eric Laurentde070132010-07-13 04:45:46 -0700102
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103namespace android {
104
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800105static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
106static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -0700107
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800109static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110
111// retry counts for buffer fill timeout
112// 50 * ~20msecs = 1 second
113static const int8_t kMaxTrackRetries = 50;
114static const int8_t kMaxTrackStartupRetries = 50;
115// allow less retry attempts on direct output thread.
116// direct outputs can be a scarce resource in audio hardware and should
117// be released as quickly as possible.
118static const int8_t kMaxTrackRetriesDirect = 2;
119
120static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -0800121static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700122
Glenn Kasten7dede872011-12-13 11:04:14 -0800123// don't warn about blocked writes or record buffer overflows more often than this
124static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700125
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700126// RecordThread loop sleep time upon application overrun or audio HAL read error
127static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128
Glenn Kasten7dede872011-12-13 11:04:14 -0800129// maximum time to wait for setParameters to complete
130static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -0700131
Eric Laurent7cafbb32011-11-22 18:50:29 -0800132// minimum sleep time for the mixer thread loop when tracks are active but in underrun
133static const uint32_t kMinThreadSleepTimeUs = 5000;
134// maximum divider applied to the active sleep time in the mixer thread loop
135static const uint32_t kMaxThreadSleepTimeShift = 2;
136
Glenn Kasten58912562012-04-03 10:45:00 -0700137// minimum normal mix buffer size, expressed in milliseconds rather than frames
138static const uint32_t kMinNormalMixBufferSizeMs = 20;
Glenn Kasten4adcede2012-05-14 12:26:02 -0700139// maximum normal mix buffer size
140static const uint32_t kMaxNormalMixBufferSizeMs = 24;
Glenn Kasten58912562012-04-03 10:45:00 -0700141
John Grossman4ff14ba2012-02-08 16:37:41 -0800142nsecs_t AudioFlinger::mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
Eric Laurent7cafbb32011-11-22 18:50:29 -0800143
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700144// Whether to use fast mixer
145static const enum {
146 FastMixer_Never, // never initialize or use: for debugging only
147 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
148 // normal mixer multiplier is 1
149 FastMixer_Static, // initialize if needed, then use all the time if initialized,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700150 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700151 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
Glenn Kasten4adcede2012-05-14 12:26:02 -0700152 // multiplier is calculated based on min & max normal mixer buffer size
Glenn Kasten300a2ee2012-04-25 13:47:36 -0700153 // FIXME for FastMixer_Dynamic:
154 // Supporting this option will require fixing HALs that can't handle large writes.
155 // For example, one HAL implementation returns an error from a large write,
156 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
157 // We could either fix the HAL implementations, or provide a wrapper that breaks
158 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
159} kUseFastMixer = FastMixer_Static;
160
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700161static uint32_t gScreenState; // incremented by 2 when screen state changes, bit 0 == 1 means "off"
162 // AudioFlinger::setParameters() updates, other threads read w/o lock
163
Glenn Kastenfd4e20c2012-06-04 11:51:12 -0700164// Priorities for requestPriority
165static const int kPriorityAudioApp = 2;
166static const int kPriorityFastMixer = 3;
167
Glenn Kasten3ed29202012-08-07 15:24:44 -0700168// IAudioFlinger::createTrack() reports back to client the total size of shared memory area
169// for the track. The client then sub-divides this into smaller buffers for its use.
170// Currently the client uses double-buffering by default, but doesn't tell us about that.
171// So for now we just assume that client is double-buffered.
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700172// FIXME It would be better for client to tell AudioFlinger whether it wants double-buffering or
173// N-buffering, so AudioFlinger could allocate the right amount of memory.
Glenn Kasten3ed29202012-08-07 15:24:44 -0700174// See the client's minBufCount and mNotificationFramesAct calculations for details.
175static const int kFastTrackMultiplier = 2;
176
Mathias Agopian65ab4712010-07-14 17:59:35 -0700177// ----------------------------------------------------------------------------
178
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700179#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -0800180// To collect the amplifier usage
181static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800182 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
183 if (service == NULL) {
184 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800185 return;
186 }
187
188 service->addBatteryData(params);
189}
Glenn Kastend3cee2f2012-03-13 17:55:35 -0700190#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -0800191
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700192static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
Dima Zavin799a70e2011-04-18 16:57:27 -0700193{
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700194 const hw_module_t *mod;
Dima Zavin799a70e2011-04-18 16:57:27 -0700195 int rc;
196
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700197 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);
198 ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,
199 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
200 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700201 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700202 }
203 rc = audio_hw_device_open(mod, dev);
204 ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,
205 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
206 if (rc) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700207 goto out;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700208 }
209 if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {
210 ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);
211 rc = BAD_VALUE;
212 goto out;
213 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700214 return 0;
215
216out:
Dima Zavin799a70e2011-04-18 16:57:27 -0700217 *dev = NULL;
218 return rc;
219}
220
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221// ----------------------------------------------------------------------------
222
223AudioFlinger::AudioFlinger()
224 : BnAudioFlinger(),
John Grossman4ff14ba2012-02-08 16:37:41 -0800225 mPrimaryHardwareDev(NULL),
Glenn Kasten7d6c35b2012-07-02 12:45:10 -0700226 mHardwareStatus(AUDIO_HW_IDLE),
John Grossman4ff14ba2012-02-08 16:37:41 -0800227 mMasterVolume(1.0f),
John Grossman4ff14ba2012-02-08 16:37:41 -0800228 mMasterMute(false),
229 mNextUniqueId(1),
230 mMode(AUDIO_MODE_INVALID),
231 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700232{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700233}
234
235void AudioFlinger::onFirstRef()
236{
Dima Zavin799a70e2011-04-18 16:57:27 -0700237 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700238
Eric Laurent93575202011-01-18 18:39:02 -0800239 Mutex::Autolock _l(mLock);
240
Dima Zavin799a70e2011-04-18 16:57:27 -0700241 /* TODO: move all this work into an Init() function */
John Grossman4ff14ba2012-02-08 16:37:41 -0800242 char val_str[PROPERTY_VALUE_MAX] = { 0 };
243 if (property_get("ro.audio.flinger_standbytime_ms", val_str, NULL) >= 0) {
244 uint32_t int_val;
245 if (1 == sscanf(val_str, "%u", &int_val)) {
246 mStandbyTimeInNsecs = milliseconds(int_val);
247 ALOGI("Using %u mSec as standby time.", int_val);
248 } else {
249 mStandbyTimeInNsecs = kDefaultStandbyTimeInNsecs;
250 ALOGI("Using default %u mSec as standby time.",
251 (uint32_t)(mStandbyTimeInNsecs / 1000000));
252 }
253 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700254
Eric Laurenta4c5a552012-03-29 10:12:40 -0700255 mMode = AUDIO_MODE_NORMAL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700256}
257
258AudioFlinger::~AudioFlinger()
259{
260 while (!mRecordThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700261 // closeInput_nonvirtual() will remove specified entry from mRecordThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700262 closeInput_nonvirtual(mRecordThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700263 }
264 while (!mPlaybackThreads.isEmpty()) {
Glenn Kastenc3ae93f2012-07-30 10:59:30 -0700265 // closeOutput_nonvirtual() will remove specified entry from mPlaybackThreads
Glenn Kastend96c5722012-04-25 13:44:49 -0700266 closeOutput_nonvirtual(mPlaybackThreads.keyAt(0));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700267 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700268
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800269 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
270 // no mHardwareLock needed, as there are no other references to this
Eric Laurenta4c5a552012-03-29 10:12:40 -0700271 audio_hw_device_close(mAudioHwDevs.valueAt(i)->hwDevice());
272 delete mAudioHwDevs.valueAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700273 }
274}
275
Eric Laurenta4c5a552012-03-29 10:12:40 -0700276static const char * const audio_interfaces[] = {
277 AUDIO_HARDWARE_MODULE_ID_PRIMARY,
278 AUDIO_HARDWARE_MODULE_ID_A2DP,
279 AUDIO_HARDWARE_MODULE_ID_USB,
280};
281#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
282
John Grossmanee578c02012-07-23 17:05:46 -0700283AudioFlinger::AudioHwDevice* AudioFlinger::findSuitableHwDev_l(
284 audio_module_handle_t module,
285 audio_devices_t devices)
Dima Zavin799a70e2011-04-18 16:57:27 -0700286{
Eric Laurenta4c5a552012-03-29 10:12:40 -0700287 // if module is 0, the request comes from an old policy manager and we should load
288 // well known modules
289 if (module == 0) {
290 ALOGW("findSuitableHwDev_l() loading well know audio hw modules");
291 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
292 loadHwModule_l(audio_interfaces[i]);
293 }
Eric Laurentf1c04f92012-08-28 14:26:53 -0700294 // then try to find a module supporting the requested device.
295 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
296 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
297 audio_hw_device_t *dev = audioHwDevice->hwDevice();
298 if ((dev->get_supported_devices != NULL) &&
299 (dev->get_supported_devices(dev) & devices) == devices)
300 return audioHwDevice;
301 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700302 } else {
303 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700304 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
305 if (audioHwDevice != NULL) {
306 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700307 }
308 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700309
Dima Zavin799a70e2011-04-18 16:57:27 -0700310 return NULL;
311}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700312
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700313void AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700314{
315 const size_t SIZE = 256;
316 char buffer[SIZE];
317 String8 result;
318
319 result.append("Clients:\n");
320 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800321 sp<Client> client = mClients.valueAt(i).promote();
322 if (client != 0) {
323 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
324 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700325 }
326 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700327
328 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800329 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700330 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
331 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800332 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700333 result.append(buffer);
334 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700336}
337
338
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700339void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700340{
341 const size_t SIZE = 256;
342 char buffer[SIZE];
343 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800344 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700345
John Grossman4ff14ba2012-02-08 16:37:41 -0800346 snprintf(buffer, SIZE, "Hardware status: %d\n"
347 "Standby Time mSec: %u\n",
348 hardwareStatus,
349 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700350 result.append(buffer);
351 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700352}
353
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700354void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700355{
356 const size_t SIZE = 256;
357 char buffer[SIZE];
358 String8 result;
359 snprintf(buffer, SIZE, "Permission Denial: "
360 "can't dump AudioFlinger from pid=%d, uid=%d\n",
361 IPCThreadState::self()->getCallingPid(),
362 IPCThreadState::self()->getCallingUid());
363 result.append(buffer);
364 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700365}
366
367static bool tryLock(Mutex& mutex)
368{
369 bool locked = false;
370 for (int i = 0; i < kDumpLockRetries; ++i) {
371 if (mutex.tryLock() == NO_ERROR) {
372 locked = true;
373 break;
374 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800375 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700376 }
377 return locked;
378}
379
380status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
381{
Glenn Kasten44deb052012-02-05 18:09:08 -0800382 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700383 dumpPermissionDenial(fd, args);
384 } else {
385 // get state of hardware lock
386 bool hardwareLocked = tryLock(mHardwareLock);
387 if (!hardwareLocked) {
388 String8 result(kHardwareLockedString);
389 write(fd, result.string(), result.size());
390 } else {
391 mHardwareLock.unlock();
392 }
393
394 bool locked = tryLock(mLock);
395
396 // failed to lock - AudioFlinger is probably deadlocked
397 if (!locked) {
398 String8 result(kDeadlockedString);
399 write(fd, result.string(), result.size());
400 }
401
402 dumpClients(fd, args);
403 dumpInternals(fd, args);
404
405 // dump playback threads
406 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
407 mPlaybackThreads.valueAt(i)->dump(fd, args);
408 }
409
410 // dump record threads
411 for (size_t i = 0; i < mRecordThreads.size(); i++) {
412 mRecordThreads.valueAt(i)->dump(fd, args);
413 }
414
Dima Zavin799a70e2011-04-18 16:57:27 -0700415 // dump all hardware devs
416 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700417 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700418 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700419 }
Glenn Kastend06785b2012-09-30 12:29:28 -0700420
421 // dump the serially shared record tee sink
422 if (mRecordTeeSource != 0) {
423 dumpTee(fd, mRecordTeeSource);
424 }
425
Mathias Agopian65ab4712010-07-14 17:59:35 -0700426 if (locked) mLock.unlock();
427 }
428 return NO_ERROR;
429}
430
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800431sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
432{
433 // If pid is already in the mClients wp<> map, then use that entry
434 // (for which promote() is always != 0), otherwise create a new entry and Client.
435 sp<Client> client = mClients.valueFor(pid).promote();
436 if (client == 0) {
437 client = new Client(this, pid);
438 mClients.add(pid, client);
439 }
440
441 return client;
442}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700443
444// IAudioFlinger interface
445
446
447sp<IAudioTrack> AudioFlinger::createTrack(
448 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800449 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700450 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800451 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700452 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700453 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800454 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700455 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800456 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800457 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700458 int *sessionId,
459 status_t *status)
460{
461 sp<PlaybackThread::Track> track;
462 sp<TrackHandle> trackHandle;
463 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700464 status_t lStatus;
465 int lSessionId;
466
Glenn Kasten263709e2012-01-06 08:40:01 -0800467 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
468 // but if someone uses binder directly they could bypass that and cause us to crash
469 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000470 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700471 lStatus = BAD_VALUE;
472 goto Exit;
473 }
474
475 {
476 Mutex::Autolock _l(mLock);
477 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700478 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700479 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000480 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700481 lStatus = BAD_VALUE;
482 goto Exit;
483 }
484
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800485 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700486
Steve Block3856b092011-10-20 11:56:00 +0100487 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700488 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700489 // check if an effect chain with the same session ID is present on another
490 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700491 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700492 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
493 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700494 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700495 if (sessions & PlaybackThread::EFFECT_SESSION) {
496 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700497 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700498 }
Eric Laurentde070132010-07-13 04:45:46 -0700499 }
500 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700501 lSessionId = *sessionId;
502 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700503 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700504 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700505 if (sessionId != NULL) {
506 *sessionId = lSessionId;
507 }
508 }
Steve Block3856b092011-10-20 11:56:00 +0100509 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700510
511 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800512 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700513
514 // move effect chain to this output thread if an effect on same session was waiting
515 // for a track to be created
516 if (lStatus == NO_ERROR && effectThread != NULL) {
517 Mutex::Autolock _dl(thread->mLock);
518 Mutex::Autolock _sl(effectThread->mLock);
519 moveEffectChain_l(lSessionId, effectThread, thread, true);
520 }
Eric Laurenta011e352012-03-29 15:51:43 -0700521
522 // Look for sync events awaiting for a session to be used.
523 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
524 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
525 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700526 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700527 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700528 } else {
529 mPendingSyncEvents[i]->cancel();
530 }
Eric Laurenta011e352012-03-29 15:51:43 -0700531 mPendingSyncEvents.removeAt(i);
532 i--;
533 }
534 }
535 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700536 }
537 if (lStatus == NO_ERROR) {
538 trackHandle = new TrackHandle(track);
539 } else {
540 // remove local strong reference to Client before deleting the Track so that the Client
541 // destructor is called by the TrackBase destructor with mLock held
542 client.clear();
543 track.clear();
544 }
545
546Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700547 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700548 *status = lStatus;
549 }
550 return trackHandle;
551}
552
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800553uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700554{
555 Mutex::Autolock _l(mLock);
556 PlaybackThread *thread = checkPlaybackThread_l(output);
557 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000558 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700559 return 0;
560 }
561 return thread->sampleRate();
562}
563
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800564int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700565{
566 Mutex::Autolock _l(mLock);
567 PlaybackThread *thread = checkPlaybackThread_l(output);
568 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000569 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700570 return 0;
571 }
572 return thread->channelCount();
573}
574
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800575audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700576{
577 Mutex::Autolock _l(mLock);
578 PlaybackThread *thread = checkPlaybackThread_l(output);
579 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000580 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800581 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700582 }
583 return thread->format();
584}
585
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800586size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700587{
588 Mutex::Autolock _l(mLock);
589 PlaybackThread *thread = checkPlaybackThread_l(output);
590 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000591 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700592 return 0;
593 }
Glenn Kasten58912562012-04-03 10:45:00 -0700594 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
595 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700596 return thread->frameCount();
597}
598
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800599uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700600{
601 Mutex::Autolock _l(mLock);
602 PlaybackThread *thread = checkPlaybackThread_l(output);
603 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000604 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700605 return 0;
606 }
607 return thread->latency();
608}
609
610status_t AudioFlinger::setMasterVolume(float value)
611{
Eric Laurenta1884f92011-08-23 08:25:03 -0700612 status_t ret = initCheck();
613 if (ret != NO_ERROR) {
614 return ret;
615 }
616
Mathias Agopian65ab4712010-07-14 17:59:35 -0700617 // check calling permissions
618 if (!settingsAllowed()) {
619 return PERMISSION_DENIED;
620 }
621
Eric Laurenta4c5a552012-03-29 10:12:40 -0700622 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700623 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700624
John Grossmanee578c02012-07-23 17:05:46 -0700625 // Set master volume in the HALs which support it.
626 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
627 AutoMutex lock(mHardwareLock);
628 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800629
John Grossmanee578c02012-07-23 17:05:46 -0700630 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
631 if (dev->canSetMasterVolume()) {
632 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800633 }
John Grossmanee578c02012-07-23 17:05:46 -0700634 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700635 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700636
John Grossmanee578c02012-07-23 17:05:46 -0700637 // Now set the master volume in each playback thread. Playback threads
638 // assigned to HALs which do not have master volume support will apply
639 // master volume during the mix operation. Threads with HALs which do
640 // support master volume will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800641 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700642 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700643
644 return NO_ERROR;
645}
646
Glenn Kastenf78aee72012-01-04 11:00:47 -0800647status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700648{
Eric Laurenta1884f92011-08-23 08:25:03 -0700649 status_t ret = initCheck();
650 if (ret != NO_ERROR) {
651 return ret;
652 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700653
654 // check calling permissions
655 if (!settingsAllowed()) {
656 return PERMISSION_DENIED;
657 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800658 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000659 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700660 return BAD_VALUE;
661 }
662
663 { // scope for the lock
664 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700665 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700666 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700667 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700668 mHardwareStatus = AUDIO_HW_IDLE;
669 }
670
671 if (NO_ERROR == ret) {
672 Mutex::Autolock _l(mLock);
673 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800674 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700675 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700676 }
677
678 return ret;
679}
680
681status_t AudioFlinger::setMicMute(bool state)
682{
Eric Laurenta1884f92011-08-23 08:25:03 -0700683 status_t ret = initCheck();
684 if (ret != NO_ERROR) {
685 return ret;
686 }
687
Mathias Agopian65ab4712010-07-14 17:59:35 -0700688 // check calling permissions
689 if (!settingsAllowed()) {
690 return PERMISSION_DENIED;
691 }
692
693 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700694 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700695 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700696 ret = dev->set_mic_mute(dev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700697 mHardwareStatus = AUDIO_HW_IDLE;
698 return ret;
699}
700
701bool AudioFlinger::getMicMute() const
702{
Eric Laurenta1884f92011-08-23 08:25:03 -0700703 status_t ret = initCheck();
704 if (ret != NO_ERROR) {
705 return false;
706 }
707
Dima Zavinfce7a472011-04-19 22:30:36 -0700708 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800709 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700710 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700711 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700712 dev->get_mic_mute(dev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700713 mHardwareStatus = AUDIO_HW_IDLE;
714 return state;
715}
716
717status_t AudioFlinger::setMasterMute(bool muted)
718{
John Grossmand8f178d2012-07-20 14:51:35 -0700719 status_t ret = initCheck();
720 if (ret != NO_ERROR) {
721 return ret;
722 }
723
Mathias Agopian65ab4712010-07-14 17:59:35 -0700724 // check calling permissions
725 if (!settingsAllowed()) {
726 return PERMISSION_DENIED;
727 }
728
John Grossmanee578c02012-07-23 17:05:46 -0700729 Mutex::Autolock _l(mLock);
730 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700731
John Grossmanee578c02012-07-23 17:05:46 -0700732 // Set master mute in the HALs which support it.
733 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
734 AutoMutex lock(mHardwareLock);
735 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700736
John Grossmanee578c02012-07-23 17:05:46 -0700737 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
738 if (dev->canSetMasterMute()) {
739 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700740 }
John Grossmanee578c02012-07-23 17:05:46 -0700741 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700742 }
743
John Grossmanee578c02012-07-23 17:05:46 -0700744 // Now set the master mute in each playback thread. Playback threads
745 // assigned to HALs which do not have master mute support will apply master
746 // mute during the mix operation. Threads with HALs which do support master
747 // mute will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800748 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700749 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700750
751 return NO_ERROR;
752}
753
754float AudioFlinger::masterVolume() const
755{
Glenn Kasten98067102011-12-13 11:47:54 -0800756 Mutex::Autolock _l(mLock);
757 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700758}
759
760bool AudioFlinger::masterMute() const
761{
Glenn Kasten98067102011-12-13 11:47:54 -0800762 Mutex::Autolock _l(mLock);
763 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700764}
765
John Grossman4ff14ba2012-02-08 16:37:41 -0800766float AudioFlinger::masterVolume_l() const
767{
John Grossman4ff14ba2012-02-08 16:37:41 -0800768 return mMasterVolume;
769}
770
John Grossmand8f178d2012-07-20 14:51:35 -0700771bool AudioFlinger::masterMute_l() const
772{
John Grossmanee578c02012-07-23 17:05:46 -0700773 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700774}
775
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800776status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
777 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700778{
779 // check calling permissions
780 if (!settingsAllowed()) {
781 return PERMISSION_DENIED;
782 }
783
Glenn Kasten263709e2012-01-06 08:40:01 -0800784 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000785 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700786 return BAD_VALUE;
787 }
788
789 AutoMutex lock(mLock);
790 PlaybackThread *thread = NULL;
791 if (output) {
792 thread = checkPlaybackThread_l(output);
793 if (thread == NULL) {
794 return BAD_VALUE;
795 }
796 }
797
798 mStreamTypes[stream].volume = value;
799
800 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800801 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700802 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700803 }
804 } else {
805 thread->setStreamVolume(stream, value);
806 }
807
808 return NO_ERROR;
809}
810
Glenn Kastenfff6d712012-01-12 16:38:12 -0800811status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700812{
813 // check calling permissions
814 if (!settingsAllowed()) {
815 return PERMISSION_DENIED;
816 }
817
Glenn Kasten263709e2012-01-06 08:40:01 -0800818 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700819 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000820 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821 return BAD_VALUE;
822 }
823
Eric Laurent93575202011-01-18 18:39:02 -0800824 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825 mStreamTypes[stream].mute = muted;
826 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700827 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828
829 return NO_ERROR;
830}
831
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800832float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833{
Glenn Kasten263709e2012-01-06 08:40:01 -0800834 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835 return 0.0f;
836 }
837
838 AutoMutex lock(mLock);
839 float volume;
840 if (output) {
841 PlaybackThread *thread = checkPlaybackThread_l(output);
842 if (thread == NULL) {
843 return 0.0f;
844 }
845 volume = thread->streamVolume(stream);
846 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800847 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700848 }
849
850 return volume;
851}
852
Glenn Kastenfff6d712012-01-12 16:38:12 -0800853bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700854{
Glenn Kasten263709e2012-01-06 08:40:01 -0800855 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700856 return true;
857 }
858
Glenn Kasten6637baa2012-01-09 09:40:36 -0800859 AutoMutex lock(mLock);
860 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700861}
862
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800863status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700864{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800865 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700866 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
867 // check calling permissions
868 if (!settingsAllowed()) {
869 return PERMISSION_DENIED;
870 }
871
Mathias Agopian65ab4712010-07-14 17:59:35 -0700872 // ioHandle == 0 means the parameters are global to the audio hardware interface
873 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700874 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700875 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800876 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700877 AutoMutex lock(mHardwareLock);
878 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
879 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
880 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
881 status_t result = dev->set_parameters(dev, keyValuePairs.string());
882 final_result = result ?: final_result;
883 }
884 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800885 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700886 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
887 AudioParameter param = AudioParameter(keyValuePairs);
888 String8 value;
889 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700890 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
891 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700892 for (size_t i = 0; i < mRecordThreads.size(); i++) {
893 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Eric Laurentf1c04f92012-08-28 14:26:53 -0700894 audio_devices_t device = thread->inDevice();
Glenn Kasten510a3d62012-07-16 14:24:34 -0700895 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
896 // collect all of the thread's session IDs
897 KeyedVector<int, bool> ids = thread->sessionIds();
898 // suspend effects associated with those session IDs
899 for (size_t j = 0; j < ids.size(); ++j) {
900 int sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700901 thread->setEffectSuspended(FX_IID_AEC,
902 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700903 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700904 thread->setEffectSuspended(FX_IID_NS,
905 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700906 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700907 }
908 }
Eric Laurentbee53372011-08-29 12:42:48 -0700909 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700910 }
911 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700912 String8 screenState;
913 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
914 bool isOff = screenState == "off";
915 if (isOff != (gScreenState & 1)) {
916 gScreenState = ((gScreenState & ~1) + 2) | isOff;
917 }
918 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700919 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700920 }
921
922 // hold a strong ref on thread in case closeOutput() or closeInput() is called
923 // and the thread is exited once the lock is released
924 sp<ThreadBase> thread;
925 {
926 Mutex::Autolock _l(mLock);
927 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -0700928 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700929 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800930 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700931 // indicate output device change to all input threads for pre processing
932 AudioParameter param = AudioParameter(keyValuePairs);
933 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700934 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
935 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700936 for (size_t i = 0; i < mRecordThreads.size(); i++) {
937 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
938 }
939 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700940 }
941 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800942 if (thread != 0) {
943 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700944 }
945 return BAD_VALUE;
946}
947
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800948String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700949{
Glenn Kasten26dd66e2012-10-18 15:51:03 -0700950 ALOGVV("getParameters() io %d, keys %s, tid %d, calling pid %d",
951 ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700952
Eric Laurenta4c5a552012-03-29 10:12:40 -0700953 Mutex::Autolock _l(mLock);
954
Mathias Agopian65ab4712010-07-14 17:59:35 -0700955 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700956 String8 out_s8;
957
Dima Zavin799a70e2011-04-18 16:57:27 -0700958 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800959 char *s;
960 {
961 AutoMutex lock(mHardwareLock);
962 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700963 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800964 s = dev->get_parameters(dev, keys.string());
965 mHardwareStatus = AUDIO_HW_IDLE;
966 }
John Grossmanef7740b2012-02-09 11:28:36 -0800967 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700968 free(s);
969 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700970 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700971 }
972
Mathias Agopian65ab4712010-07-14 17:59:35 -0700973 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
974 if (playbackThread != NULL) {
975 return playbackThread->getParameters(keys);
976 }
977 RecordThread *recordThread = checkRecordThread_l(ioHandle);
978 if (recordThread != NULL) {
979 return recordThread->getParameters(keys);
980 }
981 return String8("");
982}
983
Glenn Kastendd8104c2012-07-02 12:42:44 -0700984size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
985 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700986{
Eric Laurenta1884f92011-08-23 08:25:03 -0700987 status_t ret = initCheck();
988 if (ret != NO_ERROR) {
989 return 0;
990 }
991
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800992 AutoMutex lock(mHardwareLock);
993 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700994 struct audio_config config = {
995 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -0700996 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700997 format: format,
998 };
John Grossmanee578c02012-07-23 17:05:46 -0700999 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
1000 size_t size = dev->get_input_buffer_size(dev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -08001001 mHardwareStatus = AUDIO_HW_IDLE;
1002 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001003}
1004
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001005unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001006{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001007 Mutex::Autolock _l(mLock);
1008
1009 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1010 if (recordThread != NULL) {
1011 return recordThread->getInputFramesLost();
1012 }
1013 return 0;
1014}
1015
1016status_t AudioFlinger::setVoiceVolume(float value)
1017{
Eric Laurenta1884f92011-08-23 08:25:03 -07001018 status_t ret = initCheck();
1019 if (ret != NO_ERROR) {
1020 return ret;
1021 }
1022
Mathias Agopian65ab4712010-07-14 17:59:35 -07001023 // check calling permissions
1024 if (!settingsAllowed()) {
1025 return PERMISSION_DENIED;
1026 }
1027
1028 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001029 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001030 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001031 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001032 mHardwareStatus = AUDIO_HW_IDLE;
1033
1034 return ret;
1035}
1036
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001037status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1038 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001039{
1040 status_t status;
1041
1042 Mutex::Autolock _l(mLock);
1043
1044 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1045 if (playbackThread != NULL) {
1046 return playbackThread->getRenderPosition(halFrames, dspFrames);
1047 }
1048
1049 return BAD_VALUE;
1050}
1051
1052void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1053{
1054
1055 Mutex::Autolock _l(mLock);
1056
Glenn Kastenbb001922012-02-03 11:10:26 -08001057 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058 if (mNotificationClients.indexOfKey(pid) < 0) {
1059 sp<NotificationClient> notificationClient = new NotificationClient(this,
1060 client,
1061 pid);
Steve Block3856b092011-10-20 11:56:00 +01001062 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001063
1064 mNotificationClients.add(pid, notificationClient);
1065
1066 sp<IBinder> binder = client->asBinder();
1067 binder->linkToDeath(notificationClient);
1068
1069 // the config change is always sent from playback or record threads to avoid deadlock
1070 // with AudioSystem::gLock
1071 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001072 mPlaybackThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::OUTPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001073 }
1074
1075 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001076 mRecordThreads.valueAt(i)->sendIoConfigEvent(AudioSystem::INPUT_OPENED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001077 }
1078 }
1079}
1080
1081void AudioFlinger::removeNotificationClient(pid_t pid)
1082{
1083 Mutex::Autolock _l(mLock);
1084
Glenn Kastena3b09252012-01-20 09:19:01 -08001085 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001086
Steve Block3856b092011-10-20 11:56:00 +01001087 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001088 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001089 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001090 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001091 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001092 ALOGV(" pid %d @ %d", ref->mPid, i);
1093 if (ref->mPid == pid) {
1094 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001095 mAudioSessionRefs.removeAt(i);
1096 delete ref;
1097 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001098 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001099 } else {
1100 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001101 }
1102 }
1103 if (removed) {
1104 purgeStaleEffects_l();
1105 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001106}
1107
1108// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001109void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001110{
1111 size_t size = mNotificationClients.size();
1112 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001113 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1114 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001115 }
1116}
1117
1118// removeClient_l() must be called with AudioFlinger::mLock held
1119void AudioFlinger::removeClient_l(pid_t pid)
1120{
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001121 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(),
1122 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001123 mClients.removeItem(pid);
1124}
1125
Eric Laurent717e1282012-06-29 16:36:52 -07001126// getEffectThread_l() must be called with AudioFlinger::mLock held
1127sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1128{
1129 sp<PlaybackThread> thread;
1130
1131 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1132 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1133 ALOG_ASSERT(thread == 0);
1134 thread = mPlaybackThreads.valueAt(i);
1135 }
1136 }
1137
1138 return thread;
1139}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001140
1141// ----------------------------------------------------------------------------
1142
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001143AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurentf1c04f92012-08-28 14:26:53 -07001144 audio_devices_t outDevice, audio_devices_t inDevice, type_t type)
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001145 : Thread(false /*canCallJava*/),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001146 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001147 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001148 // mChannelMask
1149 mChannelCount(0),
1150 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1151 mParamStatus(NO_ERROR),
Eric Laurentf1c04f92012-08-28 14:26:53 -07001152 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
1153 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Glenn Kastenc3ae93f2012-07-30 10:59:30 -07001154 // mName will be set by concrete (non-virtual) subclass
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001155 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001156{
1157}
1158
1159AudioFlinger::ThreadBase::~ThreadBase()
1160{
1161 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001162 // do not lock the mutex in destructor
1163 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001164 if (mPowerManager != 0) {
1165 sp<IBinder> binder = mPowerManager->asBinder();
1166 binder->unlinkToDeath(mDeathRecipient);
1167 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001168}
1169
1170void AudioFlinger::ThreadBase::exit()
1171{
Steve Block3856b092011-10-20 11:56:00 +01001172 ALOGV("ThreadBase::exit");
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07001173 // do any cleanup required for exit to succeed
1174 preExit();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001175 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001176 // This lock prevents the following race in thread (uniprocessor for illustration):
1177 // if (!exitPending()) {
1178 // // context switch from here to exit()
1179 // // exit() calls requestExit(), what exitPending() observes
1180 // // exit() calls signal(), which is dropped since no waiters
1181 // // context switch back from exit() to here
1182 // mWaitWorkCV.wait(...);
1183 // // now thread is hung
1184 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001185 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001186 requestExit();
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07001187 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001188 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001189 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1190 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001191 requestExitAndWait();
1192}
1193
Mathias Agopian65ab4712010-07-14 17:59:35 -07001194status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1195{
1196 status_t status;
1197
Steve Block3856b092011-10-20 11:56:00 +01001198 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001199 Mutex::Autolock _l(mLock);
1200
1201 mNewParameters.add(keyValuePairs);
1202 mWaitWorkCV.signal();
1203 // wait condition with timeout in case the thread loop has exited
1204 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001205 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001206 status = mParamStatus;
1207 mWaitWorkCV.signal();
1208 } else {
1209 status = TIMED_OUT;
1210 }
1211 return status;
1212}
1213
Eric Laurent896adcd2012-09-13 11:18:23 -07001214void AudioFlinger::ThreadBase::sendIoConfigEvent(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001215{
1216 Mutex::Autolock _l(mLock);
Eric Laurent896adcd2012-09-13 11:18:23 -07001217 sendIoConfigEvent_l(event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001218}
1219
Eric Laurent896adcd2012-09-13 11:18:23 -07001220// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
1221void AudioFlinger::ThreadBase::sendIoConfigEvent_l(int event, int param)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001222{
Eric Laurent896adcd2012-09-13 11:18:23 -07001223 IoConfigEvent *ioEvent = new IoConfigEvent(event, param);
1224 mConfigEvents.add(static_cast<ConfigEvent *>(ioEvent));
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001225 ALOGV("sendIoConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event,
1226 param);
Eric Laurent896adcd2012-09-13 11:18:23 -07001227 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) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001255 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; "
1256 "error %d",
Eric Laurent896adcd2012-09-13 11:18:23 -07001257 prioEvent->prio(), prioEvent->pid(), prioEvent->tid(), err);
1258 }
1259 } break;
1260 case CFG_EVENT_IO: {
1261 IoConfigEvent *ioEvent = static_cast<IoConfigEvent *>(event);
1262 mAudioFlinger->mLock.lock();
1263 audioConfigChanged_l(ioEvent->event(), ioEvent->param());
1264 mAudioFlinger->mLock.unlock();
1265 } break;
1266 default:
1267 ALOGE("processConfigEvents() unknown event type %d", event->type());
1268 break;
1269 }
1270 delete event;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001271 mLock.lock();
1272 }
1273 mLock.unlock();
1274}
1275
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001276void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001277{
1278 const size_t SIZE = 256;
1279 char buffer[SIZE];
1280 String8 result;
1281
1282 bool locked = tryLock(mLock);
1283 if (!locked) {
1284 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1285 write(fd, buffer, strlen(buffer));
1286 }
1287
Eric Laurent612bbb52012-03-14 15:03:26 -07001288 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1289 result.append(buffer);
1290 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1291 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001292 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1293 result.append(buffer);
1294 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1295 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001296 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1297 result.append(buffer);
1298 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001299 result.append(buffer);
1300 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1301 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001302 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1303 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001304 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1305 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001306 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001307 result.append(buffer);
1308
1309 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1310 result.append(buffer);
1311 result.append(" Index Command");
1312 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1313 snprintf(buffer, SIZE, "\n %02d ", i);
1314 result.append(buffer);
1315 result.append(mNewParameters[i]);
1316 }
1317
1318 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1319 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001320 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Eric Laurent896adcd2012-09-13 11:18:23 -07001321 mConfigEvents[i]->dump(buffer, SIZE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001322 result.append(buffer);
1323 }
1324 result.append("\n");
1325
1326 write(fd, result.string(), result.size());
1327
1328 if (locked) {
1329 mLock.unlock();
1330 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001331}
1332
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001333void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001334{
1335 const size_t SIZE = 256;
1336 char buffer[SIZE];
1337 String8 result;
1338
1339 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1340 write(fd, buffer, strlen(buffer));
1341
1342 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1343 sp<EffectChain> chain = mEffectChains[i];
1344 if (chain != 0) {
1345 chain->dump(fd, args);
1346 }
1347 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001348}
1349
Eric Laurentfeb0db62011-07-22 09:04:31 -07001350void AudioFlinger::ThreadBase::acquireWakeLock()
1351{
1352 Mutex::Autolock _l(mLock);
1353 acquireWakeLock_l();
1354}
1355
1356void AudioFlinger::ThreadBase::acquireWakeLock_l()
1357{
1358 if (mPowerManager == 0) {
1359 // use checkService() to avoid blocking if power service is not up yet
1360 sp<IBinder> binder =
1361 defaultServiceManager()->checkService(String16("power"));
1362 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001363 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001364 } else {
1365 mPowerManager = interface_cast<IPowerManager>(binder);
1366 binder->linkToDeath(mDeathRecipient);
1367 }
1368 }
1369 if (mPowerManager != 0) {
1370 sp<IBinder> binder = new BBinder();
1371 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1372 binder,
1373 String16(mName));
1374 if (status == NO_ERROR) {
1375 mWakeLockToken = binder;
1376 }
Steve Block3856b092011-10-20 11:56:00 +01001377 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001378 }
1379}
1380
1381void AudioFlinger::ThreadBase::releaseWakeLock()
1382{
1383 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001384 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001385}
1386
1387void AudioFlinger::ThreadBase::releaseWakeLock_l()
1388{
1389 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001390 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001391 if (mPowerManager != 0) {
1392 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1393 }
1394 mWakeLockToken.clear();
1395 }
1396}
1397
1398void AudioFlinger::ThreadBase::clearPowerManager()
1399{
1400 Mutex::Autolock _l(mLock);
1401 releaseWakeLock_l();
1402 mPowerManager.clear();
1403}
1404
1405void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1406{
1407 sp<ThreadBase> thread = mThread.promote();
1408 if (thread != 0) {
1409 thread->clearPowerManager();
1410 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001411 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001412}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001413
Eric Laurent59255e42011-07-27 19:49:51 -07001414void AudioFlinger::ThreadBase::setEffectSuspended(
1415 const effect_uuid_t *type, bool suspend, int sessionId)
1416{
1417 Mutex::Autolock _l(mLock);
1418 setEffectSuspended_l(type, suspend, sessionId);
1419}
1420
1421void AudioFlinger::ThreadBase::setEffectSuspended_l(
1422 const effect_uuid_t *type, bool suspend, int sessionId)
1423{
Glenn Kasten090f0192012-01-30 13:00:02 -08001424 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001425 if (chain != 0) {
1426 if (type != NULL) {
1427 chain->setEffectSuspended_l(type, suspend);
1428 } else {
1429 chain->setEffectSuspendedAll_l(suspend);
1430 }
1431 }
1432
1433 updateSuspendedSessions_l(type, suspend, sessionId);
1434}
1435
1436void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1437{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001438 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001439 if (index < 0) {
1440 return;
1441 }
1442
Glenn Kasten0a7af182012-07-09 16:09:19 -07001443 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1444 mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001445
1446 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001447 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001448 for (int j = 0; j < desc->mRefCount; j++) {
1449 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1450 chain->setEffectSuspendedAll_l(true);
1451 } else {
Steve Block3856b092011-10-20 11:56:00 +01001452 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001453 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001454 chain->setEffectSuspended_l(&desc->mType, true);
1455 }
1456 }
1457 }
1458}
1459
Eric Laurent59255e42011-07-27 19:49:51 -07001460void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1461 bool suspend,
1462 int sessionId)
1463{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001464 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001465
1466 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1467
1468 if (suspend) {
1469 if (index >= 0) {
Glenn Kasten0a7af182012-07-09 16:09:19 -07001470 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001471 } else {
1472 mSuspendedSessions.add(sessionId, sessionEffects);
1473 }
1474 } else {
1475 if (index < 0) {
1476 return;
1477 }
Glenn Kasten0a7af182012-07-09 16:09:19 -07001478 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001479 }
1480
1481
1482 int key = EffectChain::kKeyForSuspendAll;
1483 if (type != NULL) {
1484 key = type->timeLow;
1485 }
1486 index = sessionEffects.indexOfKey(key);
1487
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001488 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001489 if (suspend) {
1490 if (index >= 0) {
1491 desc = sessionEffects.valueAt(index);
1492 } else {
1493 desc = new SuspendedSessionDesc();
1494 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001495 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001496 }
1497 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001498 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001499 }
1500 desc->mRefCount++;
1501 } else {
1502 if (index < 0) {
1503 return;
1504 }
1505 desc = sessionEffects.valueAt(index);
1506 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001507 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001508 sessionEffects.removeItemsAt(index);
1509 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001510 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001511 sessionId);
1512 mSuspendedSessions.removeItem(sessionId);
1513 }
1514 }
1515 }
1516 if (!sessionEffects.isEmpty()) {
1517 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1518 }
1519}
1520
1521void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1522 bool enabled,
1523 int sessionId)
1524{
1525 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001526 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1527}
Eric Laurent59255e42011-07-27 19:49:51 -07001528
Eric Laurenta85a74a2011-10-19 11:44:54 -07001529void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1530 bool enabled,
1531 int sessionId)
1532{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001533 if (mType != RECORD) {
1534 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1535 // another session. This gives the priority to well behaved effect control panels
1536 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001537 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1538 // global effects
1539 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001540 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1541 }
1542 }
Eric Laurent59255e42011-07-27 19:49:51 -07001543
1544 sp<EffectChain> chain = getEffectChain_l(sessionId);
1545 if (chain != 0) {
1546 chain->checkSuspendOnEffectEnabled(effect, enabled);
1547 }
1548}
1549
Mathias Agopian65ab4712010-07-14 17:59:35 -07001550// ----------------------------------------------------------------------------
1551
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001552AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1553 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001554 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001555 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001556 type_t type)
Eric Laurentf1c04f92012-08-28 14:26:53 -07001557 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001558 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001559 // mStreamTypes[] initialized in constructor body
1560 mOutput(output),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001561 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001562 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001563 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001564 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001565 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001566 // index 0 is reserved for normal mixer's submix
1567 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568{
Glenn Kasten480b4682012-02-28 12:30:08 -08001569 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001570
John Grossmanee578c02012-07-23 17:05:46 -07001571 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1572 // it would be safer to explicitly pass initial masterVolume/masterMute as
1573 // parameter.
1574 //
1575 // If the HAL we are using has support for master volume or master mute,
1576 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1577 // and the mute set to false).
1578 mMasterVolume = audioFlinger->masterVolume_l();
1579 mMasterMute = audioFlinger->masterMute_l();
1580 if (mOutput && mOutput->audioHwDev) {
1581 if (mOutput->audioHwDev->canSetMasterVolume()) {
1582 mMasterVolume = 1.0;
1583 }
1584
1585 if (mOutput->audioHwDev->canSetMasterMute()) {
1586 mMasterMute = false;
1587 }
1588 }
1589
Mathias Agopian65ab4712010-07-14 17:59:35 -07001590 readOutputParameters();
1591
Glenn Kasten263709e2012-01-06 08:40:01 -08001592 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001593 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1594 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1595 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001596 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1597 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001599 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1600 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001601}
1602
1603AudioFlinger::PlaybackThread::~PlaybackThread()
1604{
1605 delete [] mMixBuffer;
1606}
1607
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001608void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609{
1610 dumpInternals(fd, args);
1611 dumpTracks(fd, args);
1612 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001613}
1614
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001615void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001616{
1617 const size_t SIZE = 256;
1618 char buffer[SIZE];
1619 String8 result;
1620
Glenn Kasten58912562012-04-03 10:45:00 -07001621 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1622 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1623 const stream_type_t *st = &mStreamTypes[i];
1624 if (i > 0) {
1625 result.appendFormat(", ");
1626 }
1627 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1628 if (st->mute) {
1629 result.append("M");
1630 }
1631 }
1632 result.append("\n");
1633 write(fd, result.string(), result.length());
1634 result.clear();
1635
Mathias Agopian65ab4712010-07-14 17:59:35 -07001636 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1637 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001638 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001639 for (size_t i = 0; i < mTracks.size(); ++i) {
1640 sp<Track> track = mTracks[i];
1641 if (track != 0) {
1642 track->dump(buffer, SIZE);
1643 result.append(buffer);
1644 }
1645 }
1646
1647 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1648 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001649 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001650 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001651 sp<Track> track = mActiveTracks[i].promote();
1652 if (track != 0) {
1653 track->dump(buffer, SIZE);
1654 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001655 }
1656 }
1657 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001658
1659 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1660 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1661 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1662 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001663}
1664
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001665void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001666{
1667 const size_t SIZE = 256;
1668 char buffer[SIZE];
1669 String8 result;
1670
1671 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1672 result.append(buffer);
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001673 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n",
1674 ns2ms(systemTime() - mLastWriteTime));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001675 result.append(buffer);
1676 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1677 result.append(buffer);
1678 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1679 result.append(buffer);
1680 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1681 result.append(buffer);
1682 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1683 result.append(buffer);
1684 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1685 result.append(buffer);
1686 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001687 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001688
1689 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001690}
1691
1692// Thread virtuals
1693status_t AudioFlinger::PlaybackThread::readyToRun()
1694{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001695 status_t status = initCheck();
1696 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001697 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001698 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001699 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001700 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001701 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001702}
1703
1704void AudioFlinger::PlaybackThread::onFirstRef()
1705{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001706 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001707}
1708
Jean-Michel Trivi2bfc6b42012-09-28 14:49:39 -07001709// ThreadBase virtuals
1710void AudioFlinger::PlaybackThread::preExit()
1711{
1712 ALOGV(" preExit()");
1713 // FIXME this is using hard-coded strings but in the future, this functionality will be
1714 // converted to use audio HAL extensions required to support tunneling
1715 mOutput->stream->common.set_parameters(&mOutput->stream->common, "exiting=1");
1716}
1717
Mathias Agopian65ab4712010-07-14 17:59:35 -07001718// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001719sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001720 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001721 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001722 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001723 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001724 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001725 int frameCount,
1726 const sp<IMemory>& sharedBuffer,
1727 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001728 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001729 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001730 status_t *status)
1731{
1732 sp<Track> track;
1733 status_t lStatus;
1734
Glenn Kasten73d22752012-03-19 13:38:30 -07001735 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1736
1737 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001738 if (flags & IAudioFlinger::TRACK_FAST) {
1739 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001740 // not timed
1741 (!isTimed) &&
1742 // either of these use cases:
1743 (
1744 // use case 1: shared buffer with any frame count
1745 (
1746 (sharedBuffer != 0)
1747 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001748 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001749 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001750 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001751 ((frameCount == 0) ||
Glenn Kasten3ed29202012-08-07 15:24:44 -07001752 (frameCount >= (int) (mFrameCount * kFastTrackMultiplier)))
Glenn Kasten73d22752012-03-19 13:38:30 -07001753 )
1754 ) &&
1755 // PCM data
1756 audio_is_linear_pcm(format) &&
1757 // mono or stereo
1758 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1759 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001760#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001761 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001762 (sampleRate == mSampleRate) &&
1763#endif
1764 // normal mixer has an associated fast mixer
1765 hasFastMixer() &&
1766 // there are sufficient fast track slots available
1767 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001768 // FIXME test that MixerThread for this fast track has a capable output HAL
1769 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001770 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001771 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1772 if (frameCount == 0) {
Glenn Kasten3ed29202012-08-07 15:24:44 -07001773 frameCount = mFrameCount * kFastTrackMultiplier;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001774 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001775 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001776 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001777 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001778 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07001779 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001780 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1781 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1782 audio_is_linear_pcm(format),
1783 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001784 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001785 // For compatibility with AudioTrack calculation, buffer depth is forced
1786 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1787 // This is probably too conservative, but legacy application code may depend on it.
1788 // If you change this calculation, also review the start threshold which is related.
1789 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1790 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1791 if (minBufCount < 2) {
1792 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001793 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001794 int minFrameCount = mNormalFrameCount * minBufCount;
1795 if (frameCount < minFrameCount) {
1796 frameCount = minFrameCount;
1797 }
1798 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001799 }
1800
Mathias Agopian65ab4712010-07-14 17:59:35 -07001801 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001802 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1803 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001804 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x "
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001805 "for output %p with format %d",
1806 sampleRate, format, channelMask, mOutput, mFormat);
1807 lStatus = BAD_VALUE;
1808 goto Exit;
1809 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001810 }
1811 } else {
1812 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1813 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001814 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001815 lStatus = BAD_VALUE;
1816 goto Exit;
1817 }
1818 }
1819
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001820 lStatus = initCheck();
1821 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001822 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001823 goto Exit;
1824 }
1825
1826 { // scope for mLock
1827 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001828
1829 // all tracks in same audio session must share the same routing strategy otherwise
1830 // conflicts will happen when tracks are moved from one output to another by audio policy
1831 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001832 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001833 for (size_t i = 0; i < mTracks.size(); ++i) {
1834 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001835 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001836 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001837 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001838 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001839 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001840 lStatus = BAD_VALUE;
1841 goto Exit;
1842 }
1843 }
1844 }
1845
John Grossman4ff14ba2012-02-08 16:37:41 -08001846 if (!isTimed) {
1847 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001848 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001849 } else {
1850 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1851 channelMask, frameCount, sharedBuffer, sessionId);
1852 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001853 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001854 lStatus = NO_MEMORY;
1855 goto Exit;
1856 }
1857 mTracks.add(track);
1858
1859 sp<EffectChain> chain = getEffectChain_l(sessionId);
1860 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001861 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001862 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001863 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001864 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001865 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001866
Eric Laurent896adcd2012-09-13 11:18:23 -07001867 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1868 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1869 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1870 // so ask activity manager to do this on our behalf
1871 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001872 }
1873 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001874
Mathias Agopian65ab4712010-07-14 17:59:35 -07001875 lStatus = NO_ERROR;
1876
1877Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001878 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001879 *status = lStatus;
1880 }
1881 return track;
1882}
1883
Eric Laurente737cda2012-05-22 18:55:44 -07001884uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1885{
1886 if (mFastMixer != NULL) {
1887 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1888 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1889 }
1890 return latency;
1891}
1892
1893uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1894{
1895 return latency;
1896}
1897
Mathias Agopian65ab4712010-07-14 17:59:35 -07001898uint32_t AudioFlinger::PlaybackThread::latency() const
1899{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001900 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001901 return latency_l();
1902}
1903uint32_t AudioFlinger::PlaybackThread::latency_l() const
1904{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001905 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001906 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001907 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001908 return 0;
1909 }
1910}
1911
Glenn Kasten6637baa2012-01-09 09:40:36 -08001912void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001913{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001914 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001915 // Don't apply master volume in SW if our HAL can do it for us.
1916 if (mOutput && mOutput->audioHwDev &&
1917 mOutput->audioHwDev->canSetMasterVolume()) {
1918 mMasterVolume = 1.0;
1919 } else {
1920 mMasterVolume = value;
1921 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001922}
1923
Glenn Kasten6637baa2012-01-09 09:40:36 -08001924void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001925{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001926 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001927 // Don't apply master mute in SW if our HAL can do it for us.
1928 if (mOutput && mOutput->audioHwDev &&
1929 mOutput->audioHwDev->canSetMasterMute()) {
1930 mMasterMute = false;
1931 } else {
1932 mMasterMute = muted;
1933 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001934}
1935
Glenn Kasten6637baa2012-01-09 09:40:36 -08001936void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001937{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001938 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001940}
1941
Glenn Kasten6637baa2012-01-09 09:40:36 -08001942void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001943{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001944 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001945 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001946}
1947
Glenn Kastenfff6d712012-01-12 16:38:12 -08001948float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001950 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951 return mStreamTypes[stream].volume;
1952}
1953
Mathias Agopian65ab4712010-07-14 17:59:35 -07001954// addTrack_l() must be called with ThreadBase::mLock held
1955status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1956{
1957 status_t status = ALREADY_EXISTS;
1958
1959 // set retry count for buffer fill
1960 track->mRetryCount = kMaxTrackStartupRetries;
1961 if (mActiveTracks.indexOf(track) < 0) {
1962 // the track is newly added, make sure it fills up all its
1963 // buffers before playing. This is to ensure the client will
1964 // effectively get the latency it requested.
1965 track->mFillingUpStatus = Track::FS_FILLING;
1966 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001967 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001968 mActiveTracks.add(track);
1969 if (track->mainBuffer() != mMixBuffer) {
1970 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1971 if (chain != 0) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07001972 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
1973 track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001974 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001975 }
1976 }
1977
1978 status = NO_ERROR;
1979 }
1980
Steve Block3856b092011-10-20 11:56:00 +01001981 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001982 mWaitWorkCV.broadcast();
1983
1984 return status;
1985}
1986
1987// destroyTrack_l() must be called with ThreadBase::mLock held
1988void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1989{
1990 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001991 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001993 removeTrack_l(track);
1994 }
1995}
1996
1997void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1998{
Eric Laurent29864602012-05-08 18:57:51 -07001999 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07002000 mTracks.remove(track);
2001 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07002002 // redundant as track is about to be destroyed, for dumpsys only
2003 track->mName = -1;
2004 if (track->isFastTrack()) {
2005 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07002006 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07002007 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2008 mFastTrackAvailMask |= 1 << index;
2009 // redundant as track is about to be destroyed, for dumpsys only
2010 track->mFastIndex = -1;
2011 }
Eric Laurentb469b942011-05-09 12:09:06 -07002012 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2013 if (chain != 0) {
2014 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002015 }
2016}
2017
2018String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2019{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002020 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07002021 char *s;
2022
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002023 Mutex::Autolock _l(mLock);
2024 if (initCheck() != NO_ERROR) {
2025 return out_s8;
2026 }
2027
Dima Zavin799a70e2011-04-18 16:57:27 -07002028 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07002029 out_s8 = String8(s);
2030 free(s);
2031 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032}
2033
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002034// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07002035void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
2036 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08002037 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002038
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002039 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event,
2040 param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002041
2042 switch (event) {
2043 case AudioSystem::OUTPUT_OPENED:
2044 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002045 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002046 desc.samplingRate = mSampleRate;
2047 desc.format = mFormat;
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002048 desc.frameCount = mNormalFrameCount; // FIXME see
2049 // AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002050 desc.latency = latency();
2051 param2 = &desc;
2052 break;
2053
2054 case AudioSystem::STREAM_CONFIG_CHANGED:
2055 param2 = &param;
2056 case AudioSystem::OUTPUT_CLOSED:
2057 default:
2058 break;
2059 }
2060 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2061}
2062
2063void AudioFlinger::PlaybackThread::readOutputParameters()
2064{
Dima Zavin799a70e2011-04-18 16:57:27 -07002065 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002066 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2067 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07002068 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002069 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002070 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002071 if (mFrameCount & 15) {
2072 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2073 mFrameCount);
2074 }
2075
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002076 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002077 double multiplier = 1.0;
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002078 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2079 kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002080 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002081 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2082 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2083 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2084 maxNormalFrameCount = maxNormalFrameCount & ~15;
2085 if (maxNormalFrameCount < minNormalFrameCount) {
2086 maxNormalFrameCount = minNormalFrameCount;
2087 }
2088 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2089 if (multiplier <= 1.0) {
2090 multiplier = 1.0;
2091 } else if (multiplier <= 2.0) {
2092 if (2 * mFrameCount <= maxNormalFrameCount) {
2093 multiplier = 2.0;
2094 } else {
2095 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2096 }
2097 } else {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002098 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL
2099 // SRC (it would be unusual for the normal mix buffer size to not be a multiple of fast
2100 // track, but we sometimes have to do this to satisfy the maximum frame count
2101 // constraint)
Glenn Kasten4adcede2012-05-14 12:26:02 -07002102 // FIXME this rounding up should not be done if no HAL SRC
2103 uint32_t truncMult = (uint32_t) multiplier;
2104 if ((truncMult & 1)) {
2105 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2106 ++truncMult;
2107 }
2108 }
2109 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002110 }
Glenn Kasten58912562012-04-03 10:45:00 -07002111 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002112 mNormalFrameCount = multiplier * mFrameCount;
2113 // round up to nearest 16 frames to satisfy AudioMixer
2114 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002115 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount,
2116 mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002117
Glenn Kastene9dd0172012-01-27 18:08:45 -08002118 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002119 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2120 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002121
Eric Laurentde070132010-07-13 04:45:46 -07002122 // force reconfiguration of effect chains and engines to take new buffer size and audio
2123 // parameters into account
2124 // Note that mLock is not held when readOutputParameters() is called from the constructor
2125 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2126 // matter.
2127 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2128 Vector< sp<EffectChain> > effectChains = mEffectChains;
2129 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002130 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002131 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002132}
2133
Eric Laurente737cda2012-05-22 18:55:44 -07002134
Mathias Agopian65ab4712010-07-14 17:59:35 -07002135status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2136{
Glenn Kastena0d68332012-01-27 16:47:15 -08002137 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002138 return BAD_VALUE;
2139 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002140 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002141 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002142 return INVALID_OPERATION;
2143 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002144 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002145
Eric Laurent1afc26d2012-09-23 15:20:50 -07002146 if (isSuspended()) {
2147 // return an estimation of rendered frames when the output is suspended
2148 int32_t frames = mBytesWritten - latency_l();
2149 if (frames < 0) {
2150 frames = 0;
2151 }
2152 *dspFrames = (uint32_t)frames;
2153 return NO_ERROR;
2154 } else {
2155 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
2156 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002157}
2158
Glenn Kasten106e8a42012-08-02 13:37:12 -07002159uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002160{
2161 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002162 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002163 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002164 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002165 }
2166
2167 for (size_t i = 0; i < mTracks.size(); ++i) {
2168 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002169 if (sessionId == track->sessionId() &&
2170 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002171 result |= TRACK_SESSION;
2172 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002173 }
2174 }
2175
Eric Laurent39e94f82010-07-28 01:32:47 -07002176 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002177}
2178
Eric Laurentde070132010-07-13 04:45:46 -07002179uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2180{
Dima Zavinfce7a472011-04-19 22:30:36 -07002181 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002182 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002183 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2184 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002185 }
2186 for (size_t i = 0; i < mTracks.size(); i++) {
2187 sp<Track> track = mTracks[i];
2188 if (sessionId == track->sessionId() &&
2189 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002190 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002191 }
2192 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002193 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002194}
2195
Mathias Agopian65ab4712010-07-14 17:59:35 -07002196
Glenn Kastenaed850d2012-01-26 09:46:34 -08002197AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002198{
2199 Mutex::Autolock _l(mLock);
2200 return mOutput;
2201}
2202
2203AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2204{
2205 Mutex::Autolock _l(mLock);
2206 AudioStreamOut *output = mOutput;
2207 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002208 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2209 // must push a NULL and wait for ack
2210 mOutputSink.clear();
2211 mPipeSink.clear();
2212 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002213 return output;
2214}
2215
2216// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002217audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002218{
2219 if (mOutput == NULL) {
2220 return NULL;
2221 }
2222 return &mOutput->stream->common;
2223}
2224
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002225uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002226{
Eric Laurentab9071b2012-06-04 13:45:29 -07002227 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002228}
2229
Eric Laurenta011e352012-03-29 15:51:43 -07002230status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2231{
2232 if (!isValidSyncEvent(event)) {
2233 return BAD_VALUE;
2234 }
2235
2236 Mutex::Autolock _l(mLock);
2237
2238 for (size_t i = 0; i < mTracks.size(); ++i) {
2239 sp<Track> track = mTracks[i];
2240 if (event->triggerSession() == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07002241 (void) track->setSyncEvent(event);
Eric Laurenta011e352012-03-29 15:51:43 -07002242 return NO_ERROR;
2243 }
2244 }
2245
2246 return NAME_NOT_FOUND;
2247}
2248
Glenn Kasten106e8a42012-08-02 13:37:12 -07002249bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07002250{
Glenn Kasten0dbb3562012-08-02 16:36:50 -07002251 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
Eric Laurenta011e352012-03-29 15:51:43 -07002252}
2253
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002254void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2255 const Vector< sp<Track> >& tracksToRemove)
Eric Laurent44a957f2012-05-15 15:26:05 -07002256{
2257 size_t count = tracksToRemove.size();
2258 if (CC_UNLIKELY(count)) {
2259 for (size_t i = 0 ; i < count ; i++) {
2260 const sp<Track>& track = tracksToRemove.itemAt(i);
2261 if ((track->sharedBuffer() != 0) &&
2262 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2263 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2264 }
2265 }
2266 }
2267
2268}
2269
Mathias Agopian65ab4712010-07-14 17:59:35 -07002270// ----------------------------------------------------------------------------
2271
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002272AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002273 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002274 : PlaybackThread(audioFlinger, output, id, device, type),
2275 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002276 // mFastMixer below
2277 mFastMixerFutex(0)
2278 // mOutputSink below
2279 // mPipeSink below
2280 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002281{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002282 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002283 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002284 "mFrameCount=%d, mNormalFrameCount=%d",
2285 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2286 mNormalFrameCount);
2287 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2288
Mathias Agopian65ab4712010-07-14 17:59:35 -07002289 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002290 if (mChannelCount != FCC_2) {
2291 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002292 }
Glenn Kasten58912562012-04-03 10:45:00 -07002293
2294 // create an NBAIO sink for the HAL output stream, and negotiate
2295 mOutputSink = new AudioStreamOutSink(output->stream);
2296 size_t numCounterOffers = 0;
2297 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2298 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2299 ALOG_ASSERT(index == 0);
2300
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002301 // initialize fast mixer depending on configuration
2302 bool initFastMixer;
2303 switch (kUseFastMixer) {
2304 case FastMixer_Never:
2305 initFastMixer = false;
2306 break;
2307 case FastMixer_Always:
2308 initFastMixer = true;
2309 break;
2310 case FastMixer_Static:
2311 case FastMixer_Dynamic:
2312 initFastMixer = mFrameCount < mNormalFrameCount;
2313 break;
2314 }
2315 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002316
2317 // create a MonoPipe to connect our submix to FastMixer
2318 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002319 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2320 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2321 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2322 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002323 const NBAIO_Format offers[1] = {format};
2324 size_t numCounterOffers = 0;
2325 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2326 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002327 monoPipe->setAvgFrames((mScreenState & 1) ?
2328 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002329 mPipeSink = monoPipe;
2330
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002331#ifdef TEE_SINK_FRAMES
2332 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2333 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2334 numCounterOffers = 0;
2335 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2336 ALOG_ASSERT(index == 0);
2337 mTeeSink = teeSink;
2338 PipeReader *teeSource = new PipeReader(*teeSink);
2339 numCounterOffers = 0;
2340 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2341 ALOG_ASSERT(index == 0);
2342 mTeeSource = teeSource;
2343#endif
2344
Glenn Kasten58912562012-04-03 10:45:00 -07002345 // create fast mixer and configure it initially with just one fast track for our submix
2346 mFastMixer = new FastMixer();
2347 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002348#ifdef STATE_QUEUE_DUMP
2349 sq->setObserverDump(&mStateQueueObserverDump);
2350 sq->setMutatorDump(&mStateQueueMutatorDump);
2351#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002352 FastMixerState *state = sq->begin();
2353 FastTrack *fastTrack = &state->mFastTracks[0];
2354 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2355 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2356 fastTrack->mVolumeProvider = NULL;
2357 fastTrack->mGeneration++;
2358 state->mFastTracksGen++;
2359 state->mTrackMask = 1;
2360 // fast mixer will use the HAL output sink
2361 state->mOutputSink = mOutputSink.get();
2362 state->mOutputSinkGen++;
2363 state->mFrameCount = mFrameCount;
2364 state->mCommand = FastMixerState::COLD_IDLE;
2365 // already done in constructor initialization list
2366 //mFastMixerFutex = 0;
2367 state->mColdFutexAddr = &mFastMixerFutex;
2368 state->mColdGen++;
2369 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002370 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002371 sq->end();
2372 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2373
2374 // start the fast mixer
2375 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002376 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002377 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002378 if (err != 0) {
2379 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002380 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002381 }
Glenn Kasten58912562012-04-03 10:45:00 -07002382
Glenn Kastenc15d6652012-05-30 14:52:57 -07002383#ifdef AUDIO_WATCHDOG
2384 // create and start the watchdog
2385 mAudioWatchdog = new AudioWatchdog();
2386 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2387 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2388 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002389 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002390 if (err != 0) {
2391 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002392 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002393 }
2394#endif
2395
Glenn Kasten58912562012-04-03 10:45:00 -07002396 } else {
2397 mFastMixer = NULL;
2398 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002399
2400 switch (kUseFastMixer) {
2401 case FastMixer_Never:
2402 case FastMixer_Dynamic:
2403 mNormalSink = mOutputSink;
2404 break;
2405 case FastMixer_Always:
2406 mNormalSink = mPipeSink;
2407 break;
2408 case FastMixer_Static:
2409 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2410 break;
2411 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002412}
2413
2414AudioFlinger::MixerThread::~MixerThread()
2415{
Glenn Kasten58912562012-04-03 10:45:00 -07002416 if (mFastMixer != NULL) {
2417 FastMixerStateQueue *sq = mFastMixer->sq();
2418 FastMixerState *state = sq->begin();
2419 if (state->mCommand == FastMixerState::COLD_IDLE) {
2420 int32_t old = android_atomic_inc(&mFastMixerFutex);
2421 if (old == -1) {
2422 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2423 }
2424 }
2425 state->mCommand = FastMixerState::EXIT;
2426 sq->end();
2427 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2428 mFastMixer->join();
2429 // Though the fast mixer thread has exited, it's state queue is still valid.
2430 // We'll use that extract the final state which contains one remaining fast track
2431 // corresponding to our sub-mix.
2432 state = sq->begin();
2433 ALOG_ASSERT(state->mTrackMask == 1);
2434 FastTrack *fastTrack = &state->mFastTracks[0];
2435 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2436 delete fastTrack->mBufferProvider;
2437 sq->end(false /*didModify*/);
2438 delete mFastMixer;
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002439#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002440 if (mAudioWatchdog != 0) {
2441 mAudioWatchdog->requestExit();
2442 mAudioWatchdog->requestExitAndWait();
2443 mAudioWatchdog.clear();
2444 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002445#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002446 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002447 delete mAudioMixer;
2448}
2449
Glenn Kasten83efdd02012-02-24 07:21:32 -08002450class CpuStats {
2451public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002452 CpuStats();
2453 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002454#ifdef DEBUG_CPU_USAGE
2455private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002456 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2457 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2458
2459 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2460
2461 int mCpuNum; // thread's current CPU number
2462 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002463#endif
2464};
2465
Glenn Kasten190a46f2012-03-06 11:27:10 -08002466CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002467#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002468 : mCpuNum(-1), mCpukHz(-1)
2469#endif
2470{
2471}
2472
2473void CpuStats::sample(const String8 &title) {
2474#ifdef DEBUG_CPU_USAGE
2475 // get current thread's delta CPU time in wall clock ns
2476 double wcNs;
2477 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2478
2479 // record sample for wall clock statistics
2480 if (valid) {
2481 mWcStats.sample(wcNs);
2482 }
2483
2484 // get the current CPU number
2485 int cpuNum = sched_getcpu();
2486
2487 // get the current CPU frequency in kHz
2488 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2489
2490 // check if either CPU number or frequency changed
2491 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2492 mCpuNum = cpuNum;
2493 mCpukHz = cpukHz;
2494 // ignore sample for purposes of cycles
2495 valid = false;
2496 }
2497
2498 // if no change in CPU number or frequency, then record sample for cycle statistics
2499 if (valid && mCpukHz > 0) {
2500 double cycles = wcNs * cpukHz * 0.000001;
2501 mHzStats.sample(cycles);
2502 }
2503
2504 unsigned n = mWcStats.n();
2505 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002506 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002507 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002508 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2509 double perLoop = elapsed / (double) n;
2510 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002511 double perLoop1k = perLoop * 0.001;
2512 double mean = mWcStats.mean();
2513 double stddev = mWcStats.stddev();
2514 double minimum = mWcStats.minimum();
2515 double maximum = mWcStats.maximum();
2516 double meanCycles = mHzStats.mean();
2517 double stddevCycles = mHzStats.stddev();
2518 double minCycles = mHzStats.minimum();
2519 double maxCycles = mHzStats.maximum();
2520 mCpuUsage.resetElapsed();
2521 mWcStats.reset();
2522 mHzStats.reset();
2523 ALOGD("CPU usage for %s over past %.1f secs\n"
2524 " (%u mixer loops at %.1f mean ms per loop):\n"
2525 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2526 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2527 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2528 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002529 elapsed * .000000001, n, perLoop * .000001,
2530 mean * .001,
2531 stddev * .001,
2532 minimum * .001,
2533 maximum * .001,
2534 mean / perLoop100,
2535 stddev / perLoop100,
2536 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002537 maximum / perLoop100,
2538 meanCycles / perLoop1k,
2539 stddevCycles / perLoop1k,
2540 minCycles / perLoop1k,
2541 maxCycles / perLoop1k);
2542
Glenn Kasten83efdd02012-02-24 07:21:32 -08002543 }
2544 }
2545#endif
2546};
2547
Glenn Kasten37d825e2012-02-24 07:21:48 -08002548void AudioFlinger::PlaybackThread::checkSilentMode_l()
2549{
2550 if (!mMasterMute) {
2551 char value[PROPERTY_VALUE_MAX];
2552 if (property_get("ro.audio.silent", value, "0") > 0) {
2553 char *endptr;
2554 unsigned long ul = strtoul(value, &endptr, 0);
2555 if (*endptr == '\0' && ul != 0) {
2556 ALOGD("Silence is golden");
2557 // The setprop command will not allow a property to be changed after
2558 // the first time it is set, so we don't have to worry about un-muting.
2559 setMasterMute_l(true);
2560 }
2561 }
2562 }
2563}
2564
Glenn Kasten000f0e32012-03-01 17:10:56 -08002565bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002566{
2567 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002568
Glenn Kasten000f0e32012-03-01 17:10:56 -08002569 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002570
2571 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002572 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002573
Glenn Kasten000f0e32012-03-01 17:10:56 -08002574 // DUPLICATING
2575 // FIXME could this be made local to while loop?
2576 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002577
Glenn Kasten66fcab92012-02-24 14:59:21 -08002578 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002579 sleepTime = idleSleepTime;
2580
Glenn Kasten9f34a362012-03-20 16:46:41 -07002581 if (mType == MIXER) {
2582 sleepTimeShift = 0;
2583 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002584
Glenn Kasten83efdd02012-02-24 07:21:32 -08002585 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002586 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002587
Eric Laurentfeb0db62011-07-22 09:04:31 -07002588 acquireWakeLock();
2589
Mathias Agopian65ab4712010-07-14 17:59:35 -07002590 while (!exitPending())
2591 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002592 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002593
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002594 Vector< sp<EffectChain> > effectChains;
2595
Mathias Agopian65ab4712010-07-14 17:59:35 -07002596 processConfigEvents();
2597
Mathias Agopian65ab4712010-07-14 17:59:35 -07002598 { // scope for mLock
2599
2600 Mutex::Autolock _l(mLock);
2601
2602 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002603 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002604 }
2605
Glenn Kastenfa26a852012-03-06 11:28:04 -08002606 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002607
Mathias Agopian65ab4712010-07-14 17:59:35 -07002608 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002609 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002610 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002611 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002612
2613 threadLoop_standby();
2614
Mathias Agopian65ab4712010-07-14 17:59:35 -07002615 mStandby = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002616 }
2617
Glenn Kasten3e074702012-02-28 18:40:35 -08002618 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002619 // we're about to wait, flush the binder command buffer
2620 IPCThreadState::self()->flushCommands();
2621
Glenn Kastenfa26a852012-03-06 11:28:04 -08002622 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002623
Mathias Agopian65ab4712010-07-14 17:59:35 -07002624 if (exitPending()) break;
2625
Eric Laurentfeb0db62011-07-22 09:04:31 -07002626 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002627 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002628 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002629 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002630 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002631 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002632
Eric Laurentda747442012-04-25 18:53:13 -07002633 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002634 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Eric Laurent1afc26d2012-09-23 15:20:50 -07002635 mBytesWritten = 0;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002636
Glenn Kasten37d825e2012-02-24 07:21:48 -08002637 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002638
Glenn Kasten000f0e32012-03-01 17:10:56 -08002639 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002640 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002641 if (mType == MIXER) {
2642 sleepTimeShift = 0;
2643 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002644
Mathias Agopian65ab4712010-07-14 17:59:35 -07002645 continue;
2646 }
2647 }
2648
Glenn Kasten81028042012-04-30 18:15:12 -07002649 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002650 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002651
2652 // prevent any changes in effect chain list and in each effect chain
2653 // during mixing and effect process as the audio buffers could be deleted
2654 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002655 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002656 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002657
Glenn Kastenfec279f2012-03-08 07:47:15 -08002658 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002659 threadLoop_mix();
2660 } else {
2661 threadLoop_sleepTime();
2662 }
2663
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002664 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002665 sleepTime = suspendSleepTimeUs();
Eric Laurent1afc26d2012-09-23 15:20:50 -07002666 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002667 }
2668
2669 // only process effects if we're going to write
2670 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002671 for (size_t i = 0; i < effectChains.size(); i ++) {
2672 effectChains[i]->process_l();
2673 }
2674 }
2675
2676 // enable changes in effect chain
2677 unlockEffectChains(effectChains);
2678
2679 // sleepTime == 0 means we must write to audio hardware
2680 if (sleepTime == 0) {
2681
2682 threadLoop_write();
2683
2684if (mType == MIXER) {
2685 // write blocked detection
2686 nsecs_t now = systemTime();
2687 nsecs_t delta = now - mLastWriteTime;
2688 if (!mStandby && delta > maxPeriod) {
2689 mNumDelayedWrites++;
2690 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002691#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002692 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002693#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002694 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2695 ns2ms(delta), mNumDelayedWrites, this);
2696 lastWarning = now;
2697 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002698 }
2699}
2700
2701 mStandby = false;
2702 } else {
2703 usleep(sleepTime);
2704 }
2705
Glenn Kasten58912562012-04-03 10:45:00 -07002706 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002707 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002708 // same lock. This will also mutate and push a new fast mixer state.
2709 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002710 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002711
Glenn Kastenfa26a852012-03-06 11:28:04 -08002712 // FIXME I don't understand the need for this here;
2713 // it was in the original code but maybe the
2714 // assignment in saveOutputTracks() makes this unnecessary?
2715 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002716
2717 // Effect chains will be actually deleted here if they were removed from
2718 // mEffectChains list during mixing or effects processing
2719 effectChains.clear();
2720
2721 // FIXME Note that the above .clear() is no longer necessary since effectChains
2722 // is now local to this block, but will keep it for now (at least until merge done).
2723 }
2724
Glenn Kasten9f34a362012-03-20 16:46:41 -07002725 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2726 if (mType == MIXER || mType == DIRECT) {
2727 // put output stream into standby mode
2728 if (!mStandby) {
2729 mOutput->stream->common.standby(&mOutput->stream->common);
2730 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002731 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002732
2733 releaseWakeLock();
2734
2735 ALOGV("Thread %p type %d exiting", this, mType);
2736 return false;
2737}
2738
Glenn Kasten58912562012-04-03 10:45:00 -07002739void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2740{
Glenn Kasten58912562012-04-03 10:45:00 -07002741 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2742}
2743
2744void AudioFlinger::MixerThread::threadLoop_write()
2745{
2746 // FIXME we should only do one push per cycle; confirm this is true
2747 // Start the fast mixer if it's not already running
2748 if (mFastMixer != NULL) {
2749 FastMixerStateQueue *sq = mFastMixer->sq();
2750 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002751 if (state->mCommand != FastMixerState::MIX_WRITE &&
2752 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002753 if (state->mCommand == FastMixerState::COLD_IDLE) {
2754 int32_t old = android_atomic_inc(&mFastMixerFutex);
2755 if (old == -1) {
2756 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2757 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002758#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002759 if (mAudioWatchdog != 0) {
2760 mAudioWatchdog->resume();
2761 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002762#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002763 }
2764 state->mCommand = FastMixerState::MIX_WRITE;
2765 sq->end();
2766 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002767 if (kUseFastMixer == FastMixer_Dynamic) {
2768 mNormalSink = mPipeSink;
2769 }
Glenn Kasten58912562012-04-03 10:45:00 -07002770 } else {
2771 sq->end(false /*didModify*/);
2772 }
2773 }
2774 PlaybackThread::threadLoop_write();
2775}
2776
Glenn Kasten000f0e32012-03-01 17:10:56 -08002777// shared by MIXER and DIRECT, overridden by DUPLICATING
2778void AudioFlinger::PlaybackThread::threadLoop_write()
2779{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002780 // FIXME rewrite to reduce number of system calls
2781 mLastWriteTime = systemTime();
2782 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002783 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002784
Eric Laurent67c0a582012-05-01 19:31:12 -07002785 // If an NBAIO sink is present, use it to write the normal mixer's submix
2786 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002787#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002788 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002789#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002790 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002791#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002792 // update the setpoint when gScreenState changes
2793 uint32_t screenState = gScreenState;
2794 if (screenState != mScreenState) {
2795 mScreenState = screenState;
2796 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2797 if (pipe != NULL) {
2798 pipe->setAvgFrames((mScreenState & 1) ?
2799 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2800 }
2801 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002802 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002803#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002804 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002805#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002806 if (framesWritten > 0) {
2807 bytesWritten = framesWritten << mBitShift;
2808 } else {
2809 bytesWritten = framesWritten;
2810 }
2811 // otherwise use the HAL / AudioStreamOut directly
2812 } else {
2813 // Direct output thread.
2814 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002815 }
2816
Eric Laurent67c0a582012-05-01 19:31:12 -07002817 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002818 mNumWrites++;
2819 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002820}
2821
Glenn Kasten58912562012-04-03 10:45:00 -07002822void AudioFlinger::MixerThread::threadLoop_standby()
2823{
2824 // Idle the fast mixer if it's currently running
2825 if (mFastMixer != NULL) {
2826 FastMixerStateQueue *sq = mFastMixer->sq();
2827 FastMixerState *state = sq->begin();
2828 if (!(state->mCommand & FastMixerState::IDLE)) {
2829 state->mCommand = FastMixerState::COLD_IDLE;
2830 state->mColdFutexAddr = &mFastMixerFutex;
2831 state->mColdGen++;
2832 mFastMixerFutex = 0;
2833 sq->end();
2834 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2835 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002836 if (kUseFastMixer == FastMixer_Dynamic) {
2837 mNormalSink = mOutputSink;
2838 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002839#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07002840 if (mAudioWatchdog != 0) {
2841 mAudioWatchdog->pause();
2842 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07002843#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002844 } else {
2845 sq->end(false /*didModify*/);
2846 }
2847 }
2848 PlaybackThread::threadLoop_standby();
2849}
2850
Glenn Kasten000f0e32012-03-01 17:10:56 -08002851// shared by MIXER and DIRECT, overridden by DUPLICATING
2852void AudioFlinger::PlaybackThread::threadLoop_standby()
2853{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002854 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002855 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002856}
2857
2858void AudioFlinger::MixerThread::threadLoop_mix()
2859{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002860 // obtain the presentation timestamp of the next output buffer
2861 int64_t pts;
2862 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002863
John Grossman2c3b2da2012-08-02 17:08:54 -07002864 if (mNormalSink != 0) {
2865 status = mNormalSink->getNextWriteTimestamp(&pts);
2866 } else {
2867 status = mOutputSink->getNextWriteTimestamp(&pts);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002868 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002869
Glenn Kasten952eeb22012-03-06 11:30:57 -08002870 if (status != NO_ERROR) {
2871 pts = AudioBufferProvider::kInvalidPTS;
2872 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002873
Glenn Kasten952eeb22012-03-06 11:30:57 -08002874 // mix buffers...
2875 mAudioMixer->process(pts);
2876 // increase sleep time progressively when application underrun condition clears.
2877 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2878 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2879 // such that we would underrun the audio HAL.
2880 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2881 sleepTimeShift--;
2882 }
2883 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002884 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002885 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002886}
2887
2888void AudioFlinger::MixerThread::threadLoop_sleepTime()
2889{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002890 // If no tracks are ready, sleep once for the duration of an output
2891 // buffer size, then write 0s to the output
2892 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002893 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002894 sleepTime = activeSleepTime >> sleepTimeShift;
2895 if (sleepTime < kMinThreadSleepTimeUs) {
2896 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002897 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002898 // reduce sleep time in case of consecutive application underruns to avoid
2899 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2900 // duration we would end up writing less data than needed by the audio HAL if
2901 // the condition persists.
2902 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2903 sleepTimeShift++;
2904 }
2905 } else {
2906 sleepTime = idleSleepTime;
2907 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002908 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002909 memset (mMixBuffer, 0, mixBufferSize);
2910 sleepTime = 0;
Glenn Kasten85ab62c2012-11-01 11:11:38 -07002911 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)),
2912 "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002913 }
2914 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002915}
2916
2917// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002918AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002919 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002920{
2921
Glenn Kasten29c23c32012-01-26 13:37:52 -08002922 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002924 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002925 size_t mixedTracks = 0;
2926 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002927 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002928 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002929 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002930
2931 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002932 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002933
Eric Laurent571d49c2010-08-11 05:20:11 -07002934 if (masterMute) {
2935 masterVolume = 0;
2936 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002937 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002938 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002939 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002940 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002941 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002942 masterVolume = (float)((v + (1 << 23)) >> 24);
2943 chain.clear();
2944 }
2945
Glenn Kasten288ed212012-04-25 17:52:27 -07002946 // prepare a new state to push
2947 FastMixerStateQueue *sq = NULL;
2948 FastMixerState *state = NULL;
2949 bool didModify = false;
2950 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2951 if (mFastMixer != NULL) {
2952 sq = mFastMixer->sq();
2953 state = sq->begin();
2954 }
2955
Mathias Agopian65ab4712010-07-14 17:59:35 -07002956 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002957 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002958 if (t == 0) continue;
2959
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002960 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002961 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002962
Glenn Kasten288ed212012-04-25 17:52:27 -07002963 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002964 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002965
2966 // It's theoretically possible (though unlikely) for a fast track to be created
2967 // and then removed within the same normal mix cycle. This is not a problem, as
2968 // the track never becomes active so it's fast mixer slot is never touched.
2969 // The converse, of removing an (active) track and then creating a new track
2970 // at the identical fast mixer slot within the same normal mix cycle,
2971 // is impossible because the slot isn't marked available until the end of each cycle.
2972 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002973 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2974 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002975 FastTrack *fastTrack = &state->mFastTracks[j];
2976
2977 // Determine whether the track is currently in underrun condition,
2978 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002979 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2980 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002981 uint32_t recentFull = (underruns.mBitFields.mFull -
2982 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2983 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2984 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2985 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2986 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2987 uint32_t recentUnderruns = recentPartial + recentEmpty;
2988 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002989 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002990 // or stopped which can occur when flush() is called while active
2991 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002992 track->mUnderrunCount += recentUnderruns;
2993 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002994
Glenn Kastend08f48c2012-05-01 18:14:02 -07002995 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002996 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002997 bool isActive = true;
2998 switch (track->mState) {
2999 case TrackBase::STOPPING_1:
3000 // track stays active in STOPPING_1 state until first underrun
3001 if (recentUnderruns > 0) {
3002 track->mState = TrackBase::STOPPING_2;
3003 }
3004 break;
3005 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003006 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003007 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07003008 break;
3009 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07003010 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07003011 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003012 break;
3013 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07003014 if (recentFull > 0 || recentPartial > 0) {
3015 // track has provided at least some frames recently: reset retry count
3016 track->mRetryCount = kMaxTrackRetries;
3017 }
3018 if (recentUnderruns == 0) {
3019 // no recent underruns: stay active
3020 break;
3021 }
3022 // there has recently been an underrun of some kind
3023 if (track->sharedBuffer() == 0) {
3024 // were any of the recent underruns "empty" (no frames available)?
3025 if (recentEmpty == 0) {
3026 // no, then ignore the partial underruns as they are allowed indefinitely
3027 break;
3028 }
3029 // there has recently been an "empty" underrun: decrement the retry counter
3030 if (--(track->mRetryCount) > 0) {
3031 break;
3032 }
3033 // indicate to client process that the track was disabled because of underrun;
3034 // it will then automatically call start() when data is available
3035 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
3036 // remove from active list, but state remains ACTIVE [confusing but true]
3037 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003038 break;
3039 }
3040 // fall through
3041 case TrackBase::STOPPING_2:
3042 case TrackBase::PAUSED:
3043 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07003044 case TrackBase::STOPPED:
3045 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07003046 // Check for presentation complete if track is inactive
3047 // We have consumed all the buffers of this track.
3048 // This would be incomplete if we auto-paused on underrun
3049 {
3050 size_t audioHALFrames =
3051 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3052 size_t framesWritten =
3053 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003054 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
Glenn Kastend08f48c2012-05-01 18:14:02 -07003055 // track stays in active list until presentation is complete
3056 break;
3057 }
3058 }
3059 if (track->isStopping_2()) {
3060 track->mState = TrackBase::STOPPED;
3061 }
3062 if (track->isStopped()) {
3063 // Can't reset directly, as fast mixer is still polling this track
3064 // track->reset();
3065 // So instead mark this track as needing to be reset after push with ack
3066 resetMask |= 1 << i;
3067 }
3068 isActive = false;
3069 break;
3070 case TrackBase::IDLE:
3071 default:
3072 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003073 }
3074
3075 if (isActive) {
3076 // was it previously inactive?
3077 if (!(state->mTrackMask & (1 << j))) {
3078 ExtendedAudioBufferProvider *eabp = track;
3079 VolumeProvider *vp = track;
3080 fastTrack->mBufferProvider = eabp;
3081 fastTrack->mVolumeProvider = vp;
3082 fastTrack->mSampleRate = track->mSampleRate;
3083 fastTrack->mChannelMask = track->mChannelMask;
3084 fastTrack->mGeneration++;
3085 state->mTrackMask |= 1 << j;
3086 didModify = true;
3087 // no acknowledgement required for newly active tracks
3088 }
3089 // cache the combined master volume and stream type volume for fast mixer; this
3090 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3091 track->mCachedVolume = track->isMuted() ?
3092 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3093 ++fastTracks;
3094 } else {
3095 // was it previously active?
3096 if (state->mTrackMask & (1 << j)) {
3097 fastTrack->mBufferProvider = NULL;
3098 fastTrack->mGeneration++;
3099 state->mTrackMask &= ~(1 << j);
3100 didModify = true;
3101 // If any fast tracks were removed, we must wait for acknowledgement
3102 // because we're about to decrement the last sp<> on those tracks.
3103 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003104 } else {
3105 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003106 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003107 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003108 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003109 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003110 }
3111 continue;
3112 }
3113
3114 { // local variable scope to avoid goto warning
3115
Mathias Agopian65ab4712010-07-14 17:59:35 -07003116 audio_track_cblk_t* cblk = track->cblk();
3117
3118 // The first time a track is added we wait
3119 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003120 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003121 // make sure that we have enough frames to mix one full buffer.
3122 // enforce this condition only once to enable draining the buffer in case the client
3123 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003124 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003125 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003126 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003127 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003128 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003129 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003130 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003131 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003132 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003133 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003134 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003135 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003136 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3137 // the minimum track buffer size is normally twice the number of frames necessary
3138 // to fill one buffer and the resampler should not leave more than one buffer worth
3139 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003140 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003141 }
3142 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003143 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003144 !track->isPaused() && !track->isTerminated())
3145 {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07003146 ALOGVV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server,
3147 this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003148
3149 mixedTracks++;
3150
3151 // track->mainBuffer() != mMixBuffer means there is an effect chain
3152 // connected to the track
3153 chain.clear();
3154 if (track->mainBuffer() != mMixBuffer) {
3155 chain = getEffectChain_l(track->sessionId());
3156 // Delegate volume control to effect in track effect chain if needed
3157 if (chain != 0) {
3158 tracksWithEffect++;
3159 } else {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07003160 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
3161 "session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003162 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003163 }
3164 }
3165
3166
3167 int param = AudioMixer::VOLUME;
3168 if (track->mFillingUpStatus == Track::FS_FILLED) {
3169 // no ramp for the first volume setting
3170 track->mFillingUpStatus = Track::FS_ACTIVE;
3171 if (track->mState == TrackBase::RESUMING) {
3172 track->mState = TrackBase::ACTIVE;
3173 param = AudioMixer::RAMP_VOLUME;
3174 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003175 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003176 } else if (cblk->server != 0) {
3177 // If the track is stopped before the first frame was mixed,
3178 // do not apply ramp
3179 param = AudioMixer::RAMP_VOLUME;
3180 }
3181
3182 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003183 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003184 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003185 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003186 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003187 if (track->isPausing()) {
3188 track->setPaused();
3189 }
3190 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003191
Mathias Agopian65ab4712010-07-14 17:59:35 -07003192 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003193 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003194 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003195 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003196 vl = vlr & 0xFFFF;
3197 vr = vlr >> 16;
3198 // track volumes come from shared memory, so can't be trusted and must be clamped
3199 if (vl > MAX_GAIN_INT) {
3200 ALOGV("Track left volume out of range: %04X", vl);
3201 vl = MAX_GAIN_INT;
3202 }
3203 if (vr > MAX_GAIN_INT) {
3204 ALOGV("Track right volume out of range: %04X", vr);
3205 vr = MAX_GAIN_INT;
3206 }
3207 // now apply the master volume and stream type volume
3208 vl = (uint32_t)(v * vl) << 12;
3209 vr = (uint32_t)(v * vr) << 12;
3210 // assuming master volume and stream type volume each go up to 1.0,
3211 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003212
Glenn Kasten05632a52012-01-03 14:22:33 -08003213 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3214 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003215 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003216 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003217 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003218 }
3219 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003221 // Delegate volume control to effect in track effect chain if needed
3222 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3223 // Do not ramp volume if volume is controlled by effect
3224 param = AudioMixer::VOLUME;
3225 track->mHasVolumeController = true;
3226 } else {
3227 // force no volume ramp when volume controller was just disabled or removed
3228 // from effect chain to avoid volume spike
3229 if (track->mHasVolumeController) {
3230 param = AudioMixer::VOLUME;
3231 }
3232 track->mHasVolumeController = false;
3233 }
3234
3235 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003236 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003237 vl = (vl + (1 << 11)) >> 12;
3238 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3239 vr = (vr + (1 << 11)) >> 12;
3240 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003241
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003242 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 -07003243
Mathias Agopian65ab4712010-07-14 17:59:35 -07003244 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003245 mAudioMixer->setBufferProvider(name, track);
3246 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003247
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003248 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3249 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3250 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003251 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003252 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003253 AudioMixer::TRACK,
3254 AudioMixer::FORMAT, (void *)track->format());
3255 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003256 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003257 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003258 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003259 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003260 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003261 AudioMixer::RESAMPLE,
3262 AudioMixer::SAMPLE_RATE,
3263 (void *)(cblk->sampleRate));
3264 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003265 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003266 AudioMixer::TRACK,
3267 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3268 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003269 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003270 AudioMixer::TRACK,
3271 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3272
3273 // reset retry count
3274 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003275
Eric Laurent27741442012-01-17 19:20:12 -08003276 // If one track is ready, set the mixer ready if:
3277 // - the mixer was not ready during previous round OR
3278 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003279 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003280 mixerStatus != MIXER_TRACKS_ENABLED) {
3281 mixerStatus = MIXER_TRACKS_READY;
3282 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003283 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003284 // clear effect chain input buffer if an active track underruns to avoid sending
3285 // previous audio buffer again to effects
3286 chain = getEffectChain_l(track->sessionId());
3287 if (chain != 0) {
3288 chain->clearInputBuffer();
3289 }
3290
Glenn Kasten85ab62c2012-11-01 11:11:38 -07003291 ALOGVV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user,
3292 cblk->server, this);
Glenn Kasten842c5d92012-09-26 08:34:10 -07003293 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent83faee02012-04-27 18:24:29 -07003294 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003295 // We have consumed all the buffers of this track.
3296 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003297 // TODO: use actual buffer filling status instead of latency when available from
3298 // audio HAL
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07003299 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07003300 size_t framesWritten =
3301 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003302 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003303 if (track->isStopped()) {
3304 track->reset();
3305 }
Eric Laurenta011e352012-03-29 15:51:43 -07003306 tracksToRemove->add(track);
3307 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003308 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003309 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003310 // No buffers for this track. Give it a few chances to
3311 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07003312 if (--(track->mRetryCount) <= 0) {
3313 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003314 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003315 // indicate to client process that the track was disabled because of underrun;
3316 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003317 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003318 // If one track is not ready, mark the mixer also not ready if:
3319 // - the mixer was ready during previous round OR
3320 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003321 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003322 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003323 mixerStatus = MIXER_TRACKS_ENABLED;
3324 }
3325 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003326 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003327 }
Glenn Kasten58912562012-04-03 10:45:00 -07003328
3329 } // local variable scope to avoid goto warning
3330track_is_ready: ;
3331
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332 }
3333
Glenn Kasten288ed212012-04-25 17:52:27 -07003334 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003335 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003336 if (didModify) {
3337 state->mFastTracksGen++;
3338 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3339 if (kUseFastMixer == FastMixer_Dynamic &&
3340 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3341 state->mCommand = FastMixerState::COLD_IDLE;
3342 state->mColdFutexAddr = &mFastMixerFutex;
3343 state->mColdGen++;
3344 mFastMixerFutex = 0;
3345 if (kUseFastMixer == FastMixer_Dynamic) {
3346 mNormalSink = mOutputSink;
3347 }
3348 // If we go into cold idle, need to wait for acknowledgement
3349 // so that fast mixer stops doing I/O.
3350 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003351 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003352 }
3353 sq->end();
3354 }
3355 if (sq != NULL) {
3356 sq->end(didModify);
3357 sq->push(block);
3358 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003359#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003360 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3361 mAudioWatchdog->pause();
3362 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003363#endif
Glenn Kasten288ed212012-04-25 17:52:27 -07003364
3365 // Now perform the deferred reset on fast tracks that have stopped
3366 while (resetMask != 0) {
3367 size_t i = __builtin_ctz(resetMask);
3368 ALOG_ASSERT(i < count);
3369 resetMask &= ~(1 << i);
3370 sp<Track> t = mActiveTracks[i].promote();
3371 if (t == 0) continue;
3372 Track* track = t.get();
3373 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3374 track->reset();
3375 }
Glenn Kasten58912562012-04-03 10:45:00 -07003376
Mathias Agopian65ab4712010-07-14 17:59:35 -07003377 // remove all the tracks that need to be...
3378 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003379 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003380 for (size_t i=0 ; i<count ; i++) {
3381 const sp<Track>& track = tracksToRemove->itemAt(i);
3382 mActiveTracks.remove(track);
3383 if (track->mainBuffer() != mMixBuffer) {
3384 chain = getEffectChain_l(track->sessionId());
3385 if (chain != 0) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07003386 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3387 track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003388 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003389 }
3390 }
3391 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003392 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003393 }
3394 }
3395 }
3396
3397 // mix buffer must be cleared if all tracks are connected to an
3398 // effect chain as in this case the mixer will not write to
3399 // mix buffer and track effects will accumulate into it
Glenn Kasten85ab62c2012-11-01 11:11:38 -07003400 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
3401 (mixedTracks == 0 && fastTracks > 0)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003402 // FIXME as a performance optimization, should remember previous zero status
3403 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003404 }
3405
Glenn Kasten58912562012-04-03 10:45:00 -07003406 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003407 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003408 if (fastTracks > 0) {
3409 mixerStatus = MIXER_TRACKS_READY;
3410 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003411 return mixerStatus;
3412}
3413
Glenn Kasten66fcab92012-02-24 14:59:21 -08003414/*
3415The derived values that are cached:
3416 - mixBufferSize from frame count * frame size
3417 - activeSleepTime from activeSleepTimeUs()
3418 - idleSleepTime from idleSleepTimeUs()
3419 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3420 - maxPeriod from frame count and sample rate (MIXER only)
3421
3422The parameters that affect these derived values are:
3423 - frame count
3424 - frame size
3425 - sample rate
3426 - device type: A2DP or not
3427 - device latency
3428 - format: PCM or not
3429 - active sleep time
3430 - idle sleep time
3431*/
3432
3433void AudioFlinger::PlaybackThread::cacheParameters_l()
3434{
Glenn Kasten58912562012-04-03 10:45:00 -07003435 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003436 activeSleepTime = activeSleepTimeUs();
3437 idleSleepTime = idleSleepTimeUs();
3438}
3439
Eric Laurent22167852012-06-20 12:26:32 -07003440void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003441{
Steve Block3856b092011-10-20 11:56:00 +01003442 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003443 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003444 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003445
Mathias Agopian65ab4712010-07-14 17:59:35 -07003446 size_t size = mTracks.size();
3447 for (size_t i = 0; i < size; i++) {
3448 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003449 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003450 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003451 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003452 }
3453 }
3454}
3455
Mathias Agopian65ab4712010-07-14 17:59:35 -07003456// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003457int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask, int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003458{
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003459 return mAudioMixer->getTrackName(channelMask, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003460}
3461
3462// deleteTrackName_l() must be called with ThreadBase::mLock held
3463void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3464{
Steve Block3856b092011-10-20 11:56:00 +01003465 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003466 mAudioMixer->deleteTrackName(name);
3467}
3468
3469// checkForNewParameters_l() must be called with ThreadBase::mLock held
3470bool AudioFlinger::MixerThread::checkForNewParameters_l()
3471{
Glenn Kasten58912562012-04-03 10:45:00 -07003472 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3473 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003474 bool reconfig = false;
3475
3476 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003477
3478 if (mFastMixer != NULL) {
3479 FastMixerStateQueue *sq = mFastMixer->sq();
3480 FastMixerState *state = sq->begin();
3481 if (!(state->mCommand & FastMixerState::IDLE)) {
3482 previousCommand = state->mCommand;
3483 state->mCommand = FastMixerState::HOT_IDLE;
3484 sq->end();
3485 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3486 } else {
3487 sq->end(false /*didModify*/);
3488 }
3489 }
3490
Mathias Agopian65ab4712010-07-14 17:59:35 -07003491 status_t status = NO_ERROR;
3492 String8 keyValuePair = mNewParameters[0];
3493 AudioParameter param = AudioParameter(keyValuePair);
3494 int value;
3495
3496 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3497 reconfig = true;
3498 }
3499 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003500 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003501 status = BAD_VALUE;
3502 } else {
3503 reconfig = true;
3504 }
3505 }
3506 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003507 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003508 status = BAD_VALUE;
3509 } else {
3510 reconfig = true;
3511 }
3512 }
3513 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3514 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003515 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003516 // if frame count is changed after track creation
3517 if (!mTracks.isEmpty()) {
3518 status = INVALID_OPERATION;
3519 } else {
3520 reconfig = true;
3521 }
3522 }
3523 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003524#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003525 // when changing the audio output device, call addBatteryData to notify
3526 // the change
Eric Laurentf1c04f92012-08-28 14:26:53 -07003527 if (mOutDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003528 uint32_t params = 0;
3529 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003530 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003531 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3532 }
3533
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003534 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003535 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003536 // check if any other device (except speaker) is on
3537 if (value & deviceWithoutSpeaker ) {
3538 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3539 }
3540
3541 if (params != 0) {
3542 addBatteryData(params);
3543 }
3544 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003545#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003546
Mathias Agopian65ab4712010-07-14 17:59:35 -07003547 // forward device change to effects that have requested to be
3548 // aware of attached audio device.
Eric Laurentf1c04f92012-08-28 14:26:53 -07003549 mOutDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003550 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07003551 mEffectChains[i]->setDevice_l(mOutDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003552 }
3553 }
3554
3555 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003556 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003557 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003558 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003559 mOutput->stream->common.standby(&mOutput->stream->common);
3560 mStandby = true;
3561 mBytesWritten = 0;
3562 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003563 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003564 }
3565 if (status == NO_ERROR && reconfig) {
3566 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003567 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3568 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003569 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003570 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003571 for (size_t i = 0; i < mTracks.size() ; i++) {
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003572 int name = getTrackName_l(mTracks[i]->mChannelMask, mTracks[i]->mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003573 if (name < 0) break;
3574 mTracks[i]->mName = name;
3575 // limit track sample rate to 2 x new output sample rate
3576 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3577 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3578 }
3579 }
Eric Laurent896adcd2012-09-13 11:18:23 -07003580 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003581 }
3582 }
3583
3584 mNewParameters.removeAt(0);
3585
3586 mParamStatus = status;
3587 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003588 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3589 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003590 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591 }
Glenn Kasten58912562012-04-03 10:45:00 -07003592
3593 if (!(previousCommand & FastMixerState::IDLE)) {
3594 ALOG_ASSERT(mFastMixer != NULL);
3595 FastMixerStateQueue *sq = mFastMixer->sq();
3596 FastMixerState *state = sq->begin();
3597 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3598 state->mCommand = previousCommand;
3599 sq->end();
3600 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3601 }
3602
Mathias Agopian65ab4712010-07-14 17:59:35 -07003603 return reconfig;
3604}
3605
Glenn Kastend06785b2012-09-30 12:29:28 -07003606void AudioFlinger::dumpTee(int fd, const sp<NBAIO_Source>& source, audio_io_handle_t id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003607{
Glenn Kastend06785b2012-09-30 12:29:28 -07003608 NBAIO_Source *teeSource = source.get();
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003609 if (teeSource != NULL) {
Glenn Kastend06785b2012-09-30 12:29:28 -07003610 char teeTime[16];
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003611 struct timeval tv;
3612 gettimeofday(&tv, NULL);
3613 struct tm tm;
3614 localtime_r(&tv.tv_sec, &tm);
Glenn Kastend06785b2012-09-30 12:29:28 -07003615 strftime(teeTime, sizeof(teeTime), "%T", &tm);
3616 char teePath[64];
3617 sprintf(teePath, "/data/misc/media/%s_%d.wav", teeTime, id);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003618 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3619 if (teeFd >= 0) {
3620 char wavHeader[44];
3621 memcpy(wavHeader,
3622 "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",
3623 sizeof(wavHeader));
3624 NBAIO_Format format = teeSource->format();
3625 unsigned channelCount = Format_channelCount(format);
3626 ALOG_ASSERT(channelCount <= FCC_2);
3627 unsigned sampleRate = Format_sampleRate(format);
3628 wavHeader[22] = channelCount; // number of channels
3629 wavHeader[24] = sampleRate; // sample rate
3630 wavHeader[25] = sampleRate >> 8;
3631 wavHeader[32] = channelCount * 2; // block alignment
3632 write(teeFd, wavHeader, sizeof(wavHeader));
3633 size_t total = 0;
3634 bool firstRead = true;
3635 for (;;) {
3636#define TEE_SINK_READ 1024
3637 short buffer[TEE_SINK_READ * FCC_2];
3638 size_t count = TEE_SINK_READ;
John Grossman2c3b2da2012-08-02 17:08:54 -07003639 ssize_t actual = teeSource->read(buffer, count,
3640 AudioBufferProvider::kInvalidPTS);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003641 bool wasFirstRead = firstRead;
3642 firstRead = false;
3643 if (actual <= 0) {
3644 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3645 continue;
3646 }
3647 break;
3648 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003649 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003650 write(teeFd, buffer, actual * channelCount * sizeof(short));
3651 total += actual;
3652 }
3653 lseek(teeFd, (off_t) 4, SEEK_SET);
3654 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3655 write(teeFd, &temp, sizeof(temp));
3656 lseek(teeFd, (off_t) 40, SEEK_SET);
3657 temp = total * channelCount * sizeof(short);
3658 write(teeFd, &temp, sizeof(temp));
3659 close(teeFd);
3660 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3661 } else {
3662 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3663 }
3664 }
Glenn Kastend06785b2012-09-30 12:29:28 -07003665}
3666
3667void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
3668{
3669 const size_t SIZE = 256;
3670 char buffer[SIZE];
3671 String8 result;
3672
3673 PlaybackThread::dumpInternals(fd, args);
3674
3675 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3676 result.append(buffer);
3677 write(fd, result.string(), result.size());
3678
3679 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3680 FastMixerDumpState copy = mFastMixerDumpState;
3681 copy.dump(fd);
3682
3683#ifdef STATE_QUEUE_DUMP
3684 // Similar for state queue
3685 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3686 observerCopy.dump(fd);
3687 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3688 mutatorCopy.dump(fd);
3689#endif
3690
3691 // Write the tee output to a .wav file
3692 dumpTee(fd, mTeeSource, mId);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003693
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003694#ifdef AUDIO_WATCHDOG
Glenn Kastenc15d6652012-05-30 14:52:57 -07003695 if (mAudioWatchdog != 0) {
3696 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3697 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3698 wdCopy.dump(fd);
3699 }
Glenn Kasten087dd8e2012-09-27 13:49:02 -07003700#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07003701}
3702
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003703uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003704{
Glenn Kasten58912562012-04-03 10:45:00 -07003705 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003706}
3707
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003708uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003709{
Glenn Kasten58912562012-04-03 10:45:00 -07003710 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003711}
3712
Glenn Kasten66fcab92012-02-24 14:59:21 -08003713void AudioFlinger::MixerThread::cacheParameters_l()
3714{
3715 PlaybackThread::cacheParameters_l();
3716
3717 // FIXME: Relaxed timing because of a certain device that can't meet latency
3718 // Should be reduced to 2x after the vendor fixes the driver issue
3719 // increase threshold again due to low power audio mode. The way this warning
3720 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003721 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003722}
3723
Mathias Agopian65ab4712010-07-14 17:59:35 -07003724// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003725AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003726 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003727 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003728 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003729{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003730}
3731
3732AudioFlinger::DirectOutputThread::~DirectOutputThread()
3733{
3734}
3735
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003736AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3737 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003738)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003739{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003740 sp<Track> trackToRemove;
3741
Glenn Kastenfec279f2012-03-08 07:47:15 -08003742 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003743
Glenn Kasten952eeb22012-03-06 11:30:57 -08003744 // find out which tracks need to be processed
3745 if (mActiveTracks.size() != 0) {
3746 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003747 // The track died recently
3748 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003749
Glenn Kasten952eeb22012-03-06 11:30:57 -08003750 Track* const track = t.get();
3751 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003752
Glenn Kasten952eeb22012-03-06 11:30:57 -08003753 // The first time a track is added we wait
3754 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003755 uint32_t minFrames;
3756 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3757 minFrames = mNormalFrameCount;
3758 } else {
3759 minFrames = 1;
3760 }
3761 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003762 !track->isPaused() && !track->isTerminated())
3763 {
Glenn Kasten26dd66e2012-10-18 15:51:03 -07003764 ALOGVV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003765
Glenn Kasten952eeb22012-03-06 11:30:57 -08003766 if (track->mFillingUpStatus == Track::FS_FILLED) {
3767 track->mFillingUpStatus = Track::FS_ACTIVE;
3768 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003769 if (track->mState == TrackBase::RESUMING) {
3770 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003771 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003772 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003773
Glenn Kasten952eeb22012-03-06 11:30:57 -08003774 // compute volume for this track
3775 float left, right;
3776 if (track->isMuted() || mMasterMute || track->isPausing() ||
3777 mStreamTypes[track->streamType()].mute) {
3778 left = right = 0;
3779 if (track->isPausing()) {
3780 track->setPaused();
3781 }
3782 } else {
3783 float typeVolume = mStreamTypes[track->streamType()].volume;
3784 float v = mMasterVolume * typeVolume;
3785 uint32_t vlr = cblk->getVolumeLR();
3786 float v_clamped = v * (vlr & 0xFFFF);
3787 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3788 left = v_clamped/MAX_GAIN;
3789 v_clamped = v * (vlr >> 16);
3790 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3791 right = v_clamped/MAX_GAIN;
3792 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003793
Glenn Kasten952eeb22012-03-06 11:30:57 -08003794 if (left != mLeftVolFloat || right != mRightVolFloat) {
3795 mLeftVolFloat = left;
3796 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003797
Glenn Kasten952eeb22012-03-06 11:30:57 -08003798 // Convert volumes from float to 8.24
3799 uint32_t vl = (uint32_t)(left * (1 << 24));
3800 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003801
Glenn Kasten952eeb22012-03-06 11:30:57 -08003802 // Delegate volume control to effect in track effect chain if needed
3803 // only one effect chain can be present on DirectOutputThread, so if
3804 // there is one, the track is connected to it
3805 if (!mEffectChains.isEmpty()) {
3806 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003807 mEffectChains[0]->setVolume_l(&vl, &vr);
3808 left = (float)vl / (1 << 24);
3809 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003810 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003811 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003812 }
3813
3814 // reset retry count
3815 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003816 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003817 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003818 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003819 // clear effect chain input buffer if an active track underruns to avoid sending
3820 // previous audio buffer again to effects
3821 if (!mEffectChains.isEmpty()) {
3822 mEffectChains[0]->clearInputBuffer();
3823 }
3824
Glenn Kasten26dd66e2012-10-18 15:51:03 -07003825 ALOGVV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten842c5d92012-09-26 08:34:10 -07003826 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
Eric Laurent67c0a582012-05-01 19:31:12 -07003827 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003828 // We have consumed all the buffers of this track.
3829 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003830 // TODO: implement behavior for compressed audio
Jean-Michel Trivia045dca2012-10-16 10:29:01 -07003831 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Eric Laurenta011e352012-03-29 15:51:43 -07003832 size_t framesWritten =
3833 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Glenn Kasten291f8242012-10-18 15:51:31 -07003834 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003835 if (track->isStopped()) {
3836 track->reset();
3837 }
Eric Laurenta011e352012-03-29 15:51:43 -07003838 trackToRemove = track;
3839 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003840 } else {
3841 // No buffers for this track. Give it a few chances to
3842 // fill a buffer, then remove it from active list.
Glenn Kasten842c5d92012-09-26 08:34:10 -07003843 if (--(track->mRetryCount) <= 0) {
3844 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Glenn Kasten952eeb22012-03-06 11:30:57 -08003845 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003846 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003847 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003848 }
3849 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003850 }
3851 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003852
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003853 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003854 // remove all the tracks that need to be...
3855 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003856 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003857 mActiveTracks.remove(trackToRemove);
3858 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003859 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003860 trackToRemove->sessionId());
3861 mEffectChains[0]->decActiveTrackCnt();
3862 }
3863 if (trackToRemove->isTerminated()) {
3864 removeTrack_l(trackToRemove);
3865 }
3866 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003867
Glenn Kastenfec279f2012-03-08 07:47:15 -08003868 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003869}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003870
Glenn Kasten000f0e32012-03-01 17:10:56 -08003871void AudioFlinger::DirectOutputThread::threadLoop_mix()
3872{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003873 AudioBufferProvider::Buffer buffer;
3874 size_t frameCount = mFrameCount;
3875 int8_t *curBuf = (int8_t *)mMixBuffer;
3876 // output audio to hardware
3877 while (frameCount) {
3878 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003879 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003880 if (CC_UNLIKELY(buffer.raw == NULL)) {
3881 memset(curBuf, 0, frameCount * mFrameSize);
3882 break;
3883 }
3884 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3885 frameCount -= buffer.frameCount;
3886 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003887 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003888 }
3889 sleepTime = 0;
3890 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003891 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003892
Glenn Kasten000f0e32012-03-01 17:10:56 -08003893}
3894
3895void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3896{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003897 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003898 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003899 sleepTime = activeSleepTime;
3900 } else {
3901 sleepTime = idleSleepTime;
3902 }
3903 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003904 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003905 sleepTime = 0;
3906 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003907}
3908
3909// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07003910int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask,
3911 int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003912{
3913 return 0;
3914}
3915
3916// deleteTrackName_l() must be called with ThreadBase::mLock held
3917void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3918{
3919}
3920
3921// checkForNewParameters_l() must be called with ThreadBase::mLock held
3922bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3923{
3924 bool reconfig = false;
3925
3926 while (!mNewParameters.isEmpty()) {
3927 status_t status = NO_ERROR;
3928 String8 keyValuePair = mNewParameters[0];
3929 AudioParameter param = AudioParameter(keyValuePair);
3930 int value;
3931
3932 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3933 // do not accept frame count changes if tracks are open as the track buffer
3934 // size depends on frame count and correct behavior would not be garantied
3935 // if frame count is changed after track creation
3936 if (!mTracks.isEmpty()) {
3937 status = INVALID_OPERATION;
3938 } else {
3939 reconfig = true;
3940 }
3941 }
3942 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003943 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003944 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003945 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003946 mOutput->stream->common.standby(&mOutput->stream->common);
3947 mStandby = true;
3948 mBytesWritten = 0;
3949 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003950 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003951 }
3952 if (status == NO_ERROR && reconfig) {
3953 readOutputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07003954 sendIoConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003955 }
3956 }
3957
3958 mNewParameters.removeAt(0);
3959
3960 mParamStatus = status;
3961 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003962 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3963 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003964 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003965 }
3966 return reconfig;
3967}
3968
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003969uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003970{
3971 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003972 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003973 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003974 } else {
3975 time = 10000;
3976 }
3977 return time;
3978}
3979
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003980uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003981{
3982 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003983 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003984 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003985 } else {
3986 time = 10000;
3987 }
3988 return time;
3989}
3990
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003991uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003992{
3993 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003994 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003995 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3996 } else {
3997 time = 10000;
3998 }
3999 return time;
4000}
4001
Glenn Kasten66fcab92012-02-24 14:59:21 -08004002void AudioFlinger::DirectOutputThread::cacheParameters_l()
4003{
4004 PlaybackThread::cacheParameters_l();
4005
4006 // use shorter standby delay as on normal output to release
4007 // hardware resources as soon as possible
4008 standbyDelay = microseconds(activeSleepTime*2);
4009}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07004010
Mathias Agopian65ab4712010-07-14 17:59:35 -07004011// ----------------------------------------------------------------------------
4012
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004013AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004014 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten85ab62c2012-11-01 11:11:38 -07004015 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
4016 DUPLICATING),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004017 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004018{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004019 addOutputTrack(mainThread);
4020}
4021
4022AudioFlinger::DuplicatingThread::~DuplicatingThread()
4023{
4024 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4025 mOutputTracks[i]->destroy();
4026 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004027}
4028
Glenn Kasten000f0e32012-03-01 17:10:56 -08004029void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004030{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004031 // mix buffers...
4032 if (outputsReady(outputTracks)) {
4033 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
4034 } else {
4035 memset(mMixBuffer, 0, mixBufferSize);
4036 }
4037 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07004038 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004039 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004040}
4041
4042void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
4043{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004044 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08004045 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08004046 sleepTime = activeSleepTime;
4047 } else {
4048 sleepTime = idleSleepTime;
4049 }
4050 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004051 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
4052 writeFrames = mNormalFrameCount;
4053 memset(mMixBuffer, 0, mixBufferSize);
4054 } else {
4055 // flush remaining overflow buffers in output tracks
4056 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004057 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07004058 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08004059 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08004060}
Mathias Agopian65ab4712010-07-14 17:59:35 -07004061
Glenn Kasten000f0e32012-03-01 17:10:56 -08004062void AudioFlinger::DuplicatingThread::threadLoop_write()
4063{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004064 for (size_t i = 0; i < outputTracks.size(); i++) {
4065 outputTracks[i]->write(mMixBuffer, writeFrames);
4066 }
4067 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08004068}
Glenn Kasten688a6402012-02-29 07:57:06 -08004069
Glenn Kasten000f0e32012-03-01 17:10:56 -08004070void AudioFlinger::DuplicatingThread::threadLoop_standby()
4071{
Glenn Kasten952eeb22012-03-06 11:30:57 -08004072 // DuplicatingThread implements standby by stopping all tracks
4073 for (size_t i = 0; i < outputTracks.size(); i++) {
4074 outputTracks[i]->stop();
4075 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004076}
4077
Glenn Kastenfa26a852012-03-06 11:28:04 -08004078void AudioFlinger::DuplicatingThread::saveOutputTracks()
4079{
4080 outputTracks = mOutputTracks;
4081}
4082
4083void AudioFlinger::DuplicatingThread::clearOutputTracks()
4084{
4085 outputTracks.clear();
4086}
4087
Mathias Agopian65ab4712010-07-14 17:59:35 -07004088void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4089{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004090 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004091 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004092 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004093 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004094 this,
4095 mSampleRate,
4096 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004097 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004098 frameCount);
4099 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004100 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004101 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004102 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004103 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004104 }
4105}
4106
4107void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4108{
4109 Mutex::Autolock _l(mLock);
4110 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004111 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004112 mOutputTracks[i]->destroy();
4113 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004114 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004115 return;
4116 }
4117 }
Steve Block3856b092011-10-20 11:56:00 +01004118 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004119}
4120
Glenn Kasten438b0362012-03-06 11:24:48 -08004121// caller must hold mLock
4122void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004123{
4124 mWaitTimeMs = UINT_MAX;
4125 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4126 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004127 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004128 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4129 if (waitTimeMs < mWaitTimeMs) {
4130 mWaitTimeMs = waitTimeMs;
4131 }
4132 }
4133 }
4134}
4135
4136
Glenn Kasten85ab62c2012-11-01 11:11:38 -07004137bool AudioFlinger::DuplicatingThread::outputsReady(
4138 const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004139{
4140 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004141 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004142 if (thread == 0) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07004143 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
4144 outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004145 return false;
4146 }
4147 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004148 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004149 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07004150 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
4151 thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004152 return false;
4153 }
4154 }
4155 return true;
4156}
4157
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004158uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004159{
4160 return (mWaitTimeMs * 1000) / 2;
4161}
4162
Glenn Kasten66fcab92012-02-24 14:59:21 -08004163void AudioFlinger::DuplicatingThread::cacheParameters_l()
4164{
4165 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4166 updateWaitTime_l();
4167
4168 MixerThread::cacheParameters_l();
4169}
4170
Mathias Agopian65ab4712010-07-14 17:59:35 -07004171// ----------------------------------------------------------------------------
4172
4173// TrackBase constructor must be called with AudioFlinger::mLock held
4174AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004175 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004176 const sp<Client>& client,
4177 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004178 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004179 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004180 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004181 const sp<IMemory>& sharedBuffer,
4182 int sessionId)
4183 : RefBase(),
4184 mThread(thread),
4185 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004186 mCblk(NULL),
4187 // mBuffer
4188 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004189 mFrameCount(0),
4190 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004191 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004192 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004193 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004194 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004195 // mChannelCount
4196 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004197{
Glenn Kasten85ab62c2012-11-01 11:11:38 -07004198 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
4199 sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200
Steve Blockb8a80522011-12-20 16:23:08 +00004201 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004202 size_t size = sizeof(audio_track_cblk_t);
4203 uint8_t channelCount = popcount(channelMask);
4204 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4205 if (sharedBuffer == 0) {
4206 size += bufferSize;
4207 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004208
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004209 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004210 mCblkMemory = client->heap()->allocate(size);
4211 if (mCblkMemory != 0) {
4212 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004213 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004214 new(mCblk) audio_track_cblk_t();
4215 // clear all buffers
4216 mCblk->frameCount = frameCount;
4217 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004218// uncomment the following lines to quickly test 32-bit wraparound
4219// mCblk->user = 0xffff0000;
4220// mCblk->server = 0xffff0000;
4221// mCblk->userBase = 0xffff0000;
4222// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004223 mChannelCount = channelCount;
4224 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004225 if (sharedBuffer == 0) {
4226 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4227 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4228 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004229 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004230 mCblk->flags = CBLK_UNDERRUN_ON;
4231 } else {
4232 mBuffer = sharedBuffer->pointer();
4233 }
4234 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4235 }
4236 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004237 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004238 client->heap()->dump("AudioTrack");
4239 return;
4240 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004241 } else {
4242 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004243 // construct the shared structure in-place.
4244 new(mCblk) audio_track_cblk_t();
4245 // clear all buffers
4246 mCblk->frameCount = frameCount;
4247 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004248// uncomment the following lines to quickly test 32-bit wraparound
4249// mCblk->user = 0xffff0000;
4250// mCblk->server = 0xffff0000;
4251// mCblk->userBase = 0xffff0000;
4252// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004253 mChannelCount = channelCount;
4254 mChannelMask = channelMask;
4255 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4256 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4257 // Force underrun condition to avoid false underrun callback until first data is
4258 // written to buffer (other flags are cleared)
4259 mCblk->flags = CBLK_UNDERRUN_ON;
4260 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004261 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004262}
4263
4264AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4265{
Glenn Kastena0d68332012-01-27 16:47:15 -08004266 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004267 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004268 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004269 } else {
4270 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004271 }
4272 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004273 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004274 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004275 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004276 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004277 // If the client's reference count drops to zero, the associated destructor
4278 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4279 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004280 mClient.clear();
4281 }
4282}
4283
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004284// AudioBufferProvider interface
4285// getNextBuffer() = 0;
4286// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004287void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4288{
Glenn Kastene0feee32011-12-13 11:53:26 -08004289 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004290 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004291 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004292 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004293 buffer->frameCount = 0;
4294}
4295
4296bool AudioFlinger::ThreadBase::TrackBase::step() {
4297 bool result;
4298 audio_track_cblk_t* cblk = this->cblk();
4299
4300 result = cblk->stepServer(mFrameCount);
4301 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004302 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004303 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004304 }
4305 return result;
4306}
4307
4308void AudioFlinger::ThreadBase::TrackBase::reset() {
4309 audio_track_cblk_t* cblk = this->cblk();
4310
4311 cblk->user = 0;
4312 cblk->server = 0;
4313 cblk->userBase = 0;
4314 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004315 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004316 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004317}
4318
Mathias Agopian65ab4712010-07-14 17:59:35 -07004319int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4320 return (int)mCblk->sampleRate;
4321}
4322
Mathias Agopian65ab4712010-07-14 17:59:35 -07004323void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4324 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004325 size_t frameSize = cblk->frameSize;
4326 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4327 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004328
4329 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004330 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4331 "TrackBase::getBuffer buffer out of range:\n"
4332 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4333 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004334 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004335 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004336
4337 return bufferStart;
4338}
4339
Eric Laurenta011e352012-03-29 15:51:43 -07004340status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4341{
4342 mSyncEvents.add(event);
4343 return NO_ERROR;
4344}
4345
Mathias Agopian65ab4712010-07-14 17:59:35 -07004346// ----------------------------------------------------------------------------
4347
4348// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4349AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004350 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004351 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004352 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004353 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004354 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004355 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004356 int frameCount,
4357 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004358 int sessionId,
4359 IAudioFlinger::track_flags_t flags)
Glenn Kasten85ab62c2012-11-01 11:11:38 -07004360 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer,
4361 sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004362 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004363 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004364 // mRetryCount initialized later when needed
4365 mSharedBuffer(sharedBuffer),
4366 mStreamType(streamType),
4367 mName(-1), // see note below
4368 mMainBuffer(thread->mixBuffer()),
4369 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004370 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004371 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004372 mFlags(flags),
4373 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004374 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004375 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004376{
4377 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004378 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4379 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Glenn Kasten85ab62c2012-11-01 11:11:38 -07004380 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) :
4381 sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004382 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Jean-Michel Trivife3156e2012-09-10 18:58:27 -07004383 mName = thread->getTrackName_l(channelMask, sessionId);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004384 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004385 if (mName < 0) {
4386 ALOGE("no more track names available");
4387 return;
4388 }
4389 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004390 if (flags & IAudioFlinger::TRACK_FAST) {
4391 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4392 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4393 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004394 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004395 // FIXME This is too eager. We allocate a fast track index before the
4396 // fast track becomes active. Since fast tracks are a scarce resource,
4397 // this means we are potentially denying other more important fast tracks from
4398 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004399 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004400 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004401 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004402 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004403 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004404 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004405 }
Glenn Kasten85ab62c2012-11-01 11:11:38 -07004406 ALOGV("Track constructor name %d, calling pid %d", mName,
4407 IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004408}
4409
4410AudioFlinger::PlaybackThread::Track::~Track()
4411{
Steve Block3856b092011-10-20 11:56:00 +01004412 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004413}
4414
4415void AudioFlinger::PlaybackThread::Track::destroy()
4416{
4417 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4418 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004419 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004420 // we must acquire a strong reference on this Track before locking mLock
4421 // here so that the destructor is called only when exiting this function.
4422 // On the other hand, as long as Track::destroy() is only called by
4423 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4424 // this Track with its member mTrack.
4425 sp<Track> keep(this);
4426 { // scope for mLock
4427 sp<ThreadBase> thread = mThread.promote();
4428 if (thread != 0) {
4429 if (!isOutputTrack()) {
4430 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004431 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004432
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004433#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004434 // to track the speaker usage
4435 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004436#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004437 }
4438 AudioSystem::releaseOutput(thread->id());
4439 }
4440 Mutex::Autolock _l(thread->mLock);
4441 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4442 playbackThread->destroyTrack_l(this);
4443 }
4444 }
4445}
4446
Glenn Kasten288ed212012-04-25 17:52:27 -07004447/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4448{
Glenn Kasten85ab62c2012-11-01 11:11:38 -07004449 result.append(" Name Client Type Fmt Chn mask Session mFrCnt fCount S M F SRate "
4450 "L dB R dB Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004451}
4452
Mathias Agopian65ab4712010-07-14 17:59:35 -07004453void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4454{
Glenn Kasten83d86532012-01-17 14:39:34 -08004455 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004456 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004457 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004458 } else {
4459 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4460 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004461 track_state state = mState;
4462 char stateChar;
4463 switch (state) {
4464 case IDLE:
4465 stateChar = 'I';
4466 break;
4467 case TERMINATED:
4468 stateChar = 'T';
4469 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004470 case STOPPING_1:
4471 stateChar = 's';
4472 break;
4473 case STOPPING_2:
4474 stateChar = '5';
4475 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004476 case STOPPED:
4477 stateChar = 'S';
4478 break;
4479 case RESUMING:
4480 stateChar = 'R';
4481 break;
4482 case ACTIVE:
4483 stateChar = 'A';
4484 break;
4485 case PAUSING:
4486 stateChar = 'p';
4487 break;
4488 case PAUSED:
4489 stateChar = 'P';
4490 break;
Eric Laurent29864602012-05-08 18:57:51 -07004491 case FLUSHED:
4492 stateChar = 'F';
4493 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004494 default:
4495 stateChar = '?';
4496 break;
4497 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004498 char nowInUnderrun;
4499 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4500 case UNDERRUN_FULL:
4501 nowInUnderrun = ' ';
4502 break;
4503 case UNDERRUN_PARTIAL:
4504 nowInUnderrun = '<';
4505 break;
4506 case UNDERRUN_EMPTY:
4507 nowInUnderrun = '*';
4508 break;
4509 default:
4510 nowInUnderrun = '?';
4511 break;
4512 }
Glenn Kastene213c862012-04-25 13:46:15 -07004513 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4514 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004515 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004516 mStreamType,
4517 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004518 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004519 mSessionId,
4520 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004521 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004522 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004523 mMute,
4524 mFillingUpStatus,
4525 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004526 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4527 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004528 mCblk->server,
4529 mCblk->user,
4530 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004531 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004532 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004533 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004534 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004535}
4536
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004537// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004538status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004539 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004540{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004541 audio_track_cblk_t* cblk = this->cblk();
4542 uint32_t framesReady;
4543 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004544
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004545 // Check if last stepServer failed, try to step now
4546 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004547 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4548 // Since the fast mixer is higher priority than client callback thread,
4549 // it does not result in priority inversion for client.
4550 // But a non-blocking solution would be preferable to avoid
4551 // fast mixer being unable to tryLock(), and
4552 // to avoid the extra context switches if the client wakes up,
4553 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004554 if (!step()) goto getNextBuffer_exit;
4555 ALOGV("stepServer recovered");
4556 mStepServerFailed = false;
4557 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004558
Glenn Kasten288ed212012-04-25 17:52:27 -07004559 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004560 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004561
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004562 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004563 uint32_t s = cblk->server;
4564 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4565
4566 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4567 if (framesReq > framesReady) {
4568 framesReq = framesReady;
4569 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004570 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004571 framesReq = bufferEnd - s;
4572 }
4573
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004574 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004575 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004576 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004577 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004578
4579getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004580 buffer->raw = NULL;
4581 buffer->frameCount = 0;
4582 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4583 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004584}
4585
Glenn Kasten288ed212012-04-25 17:52:27 -07004586// Note that framesReady() takes a mutex on the control block using tryLock().
4587// This could result in priority inversion if framesReady() is called by the normal mixer,
4588// as the normal mixer thread runs at lower
4589// priority than the client's callback thread: there is a short window within framesReady()
4590// during which the normal mixer could be preempted, and the client callback would block.
4591// Another problem can occur if framesReady() is called by the fast mixer:
4592// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4593// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4594size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004595 return mCblk->framesReady();
4596}
4597
Glenn Kasten288ed212012-04-25 17:52:27 -07004598// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004599bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004600 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004601
John Grossman4ff14ba2012-02-08 16:37:41 -08004602 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004603 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4604 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004605 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004606 return true;
4607 }
4608 return false;
4609}
4610
Glenn Kasten3acbd052012-02-28 10:39:56 -08004611status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004612 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004613{
4614 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004615 ALOGV("start(%d), calling pid %d session %d",
4616 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004617
Mathias Agopian65ab4712010-07-14 17:59:35 -07004618 sp<ThreadBase> thread = mThread.promote();
4619 if (thread != 0) {
4620 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004621 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004622 // here the track could be either new, or restarted
4623 // in both cases "unstop" the track
4624 if (mState == PAUSED) {
4625 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004626 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004627 } else {
4628 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004629 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004630 }
4631
4632 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4633 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004634 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004635 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004636
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004637#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004638 // to track the speaker usage
4639 if (status == NO_ERROR) {
4640 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4641 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004642#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004643 }
4644 if (status == NO_ERROR) {
4645 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4646 playbackThread->addTrack_l(this);
4647 } else {
4648 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004649 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004650 }
4651 } else {
4652 status = BAD_VALUE;
4653 }
4654 return status;
4655}
4656
4657void AudioFlinger::PlaybackThread::Track::stop()
4658{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004659 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004660 sp<ThreadBase> thread = mThread.promote();
4661 if (thread != 0) {
4662 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004663 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004664 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004665 // If the track is not active (PAUSED and buffers full), flush buffers
4666 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4667 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4668 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004669 mState = STOPPED;
4670 } else if (!isFastTrack()) {
4671 mState = STOPPED;
4672 } else {
4673 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4674 // and then to STOPPED and reset() when presentation is complete
4675 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004676 }
Glenn Kasten85ab62c2012-11-01 11:11:38 -07004677 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
4678 playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004679 }
4680 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4681 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004682 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004683 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004684
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004685#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004686 // to track the speaker usage
4687 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004688#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004689 }
4690 }
4691}
4692
4693void AudioFlinger::PlaybackThread::Track::pause()
4694{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004695 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004696 sp<ThreadBase> thread = mThread.promote();
4697 if (thread != 0) {
4698 Mutex::Autolock _l(thread->mLock);
4699 if (mState == ACTIVE || mState == RESUMING) {
4700 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004701 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004702 if (!isOutputTrack()) {
4703 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004704 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004705 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004706
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004707#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004708 // to track the speaker usage
4709 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004710#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004711 }
4712 }
4713 }
4714}
4715
4716void AudioFlinger::PlaybackThread::Track::flush()
4717{
Steve Block3856b092011-10-20 11:56:00 +01004718 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004719 sp<ThreadBase> thread = mThread.promote();
4720 if (thread != 0) {
4721 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004722 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4723 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004724 return;
4725 }
4726 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004727 // FLUSHED state
4728 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004729 // do not reset the track if it is still in the process of being stopped or paused.
4730 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004731 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004732 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004733 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4734 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4735 reset();
4736 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004737 }
4738}
4739
4740void AudioFlinger::PlaybackThread::Track::reset()
4741{
4742 // Do not reset twice to avoid discarding data written just after a flush and before
4743 // the audioflinger thread detects the track is stopped.
4744 if (!mResetDone) {
4745 TrackBase::reset();
4746 // Force underrun condition to avoid false underrun callback until first data is
4747 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004748 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4749 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004750 mFillingUpStatus = FS_FILLING;
4751 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004752 if (mState == FLUSHED) {
4753 mState = IDLE;
4754 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004755 }
4756}
4757
4758void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4759{
4760 mMute = muted;
4761}
4762
Mathias Agopian65ab4712010-07-14 17:59:35 -07004763status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4764{
4765 status_t status = DEAD_OBJECT;
4766 sp<ThreadBase> thread = mThread.promote();
4767 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004768 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004769 sp<AudioFlinger> af = mClient->audioFlinger();
4770
4771 Mutex::Autolock _l(af->mLock);
4772
4773 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004774
Eric Laurent109347d2012-07-02 12:31:03 -07004775 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004776 Mutex::Autolock _dl(playbackThread->mLock);
4777 Mutex::Autolock _sl(srcThread->mLock);
4778 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4779 if (chain == 0) {
4780 return INVALID_OPERATION;
4781 }
4782
4783 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4784 if (effect == 0) {
4785 return INVALID_OPERATION;
4786 }
4787 srcThread->removeEffect_l(effect);
4788 playbackThread->addEffect_l(effect);
4789 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4790 if (effect->state() == EffectModule::ACTIVE ||
4791 effect->state() == EffectModule::STOPPING) {
4792 effect->start();
4793 }
4794
4795 sp<EffectChain> dstChain = effect->chain().promote();
4796 if (dstChain == 0) {
4797 srcThread->addEffect_l(effect);
4798 return INVALID_OPERATION;
4799 }
4800 AudioSystem::unregisterEffect(effect->id());
4801 AudioSystem::registerEffect(&effect->desc(),
4802 srcThread->id(),
4803 dstChain->strategy(),
4804 AUDIO_SESSION_OUTPUT_MIX,
4805 effect->id());
4806 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004807 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004808 }
4809 return status;
4810}
4811
4812void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4813{
4814 mAuxEffectId = EffectId;
4815 mAuxBuffer = buffer;
4816}
4817
Eric Laurenta011e352012-03-29 15:51:43 -07004818bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4819 size_t audioHalFrames)
4820{
4821 // a track is considered presented when the total number of frames written to audio HAL
4822 // corresponds to the number of frames written when presentationComplete() is called for the
4823 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4824 if (mPresentationCompleteFrames == 0) {
4825 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4826 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4827 mPresentationCompleteFrames, audioHalFrames);
4828 }
4829 if (framesWritten >= mPresentationCompleteFrames) {
4830 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4831 mSessionId, framesWritten);
4832 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004833 return true;
4834 }
4835 return false;
4836}
4837
4838void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4839{
4840 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4841 if (mSyncEvents[i]->type() == type) {
4842 mSyncEvents[i]->trigger();
4843 mSyncEvents.removeAt(i);
4844 i--;
4845 }
4846 }
4847}
4848
Glenn Kasten58912562012-04-03 10:45:00 -07004849// implement VolumeBufferProvider interface
4850
4851uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4852{
4853 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4854 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4855 uint32_t vlr = mCblk->getVolumeLR();
4856 uint32_t vl = vlr & 0xFFFF;
4857 uint32_t vr = vlr >> 16;
4858 // track volumes come from shared memory, so can't be trusted and must be clamped
4859 if (vl > MAX_GAIN_INT) {
4860 vl = MAX_GAIN_INT;
4861 }
4862 if (vr > MAX_GAIN_INT) {
4863 vr = MAX_GAIN_INT;
4864 }
4865 // now apply the cached master volume and stream type volume;
4866 // this is trusted but lacks any synchronization or barrier so may be stale
4867 float v = mCachedVolume;
4868 vl *= v;
4869 vr *= v;
4870 // re-combine into U4.16
4871 vlr = (vr << 16) | (vl & 0xFFFF);
4872 // FIXME look at mute, pause, and stop flags
4873 return vlr;
4874}
Eric Laurenta011e352012-03-29 15:51:43 -07004875
Eric Laurent29864602012-05-08 18:57:51 -07004876status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4877{
4878 if (mState == TERMINATED || mState == PAUSED ||
4879 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4880 (mState == STOPPED)))) {
4881 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4882 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4883 event->cancel();
4884 return INVALID_OPERATION;
4885 }
Glenn Kastend23eedc2012-08-02 13:35:47 -07004886 (void) TrackBase::setSyncEvent(event);
Eric Laurent29864602012-05-08 18:57:51 -07004887 return NO_ERROR;
4888}
4889
John Grossman4ff14ba2012-02-08 16:37:41 -08004890// timed audio tracks
4891
4892sp<AudioFlinger::PlaybackThread::TimedTrack>
4893AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004894 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004895 const sp<Client>& client,
4896 audio_stream_type_t streamType,
4897 uint32_t sampleRate,
4898 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004899 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004900 int frameCount,
4901 const sp<IMemory>& sharedBuffer,
4902 int sessionId) {
4903 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004904 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004905
Glenn Kastena0356762012-03-19 10:38:51 -07004906 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004907 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4908 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004909}
4910
4911AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004912 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004913 const sp<Client>& client,
4914 audio_stream_type_t streamType,
4915 uint32_t sampleRate,
4916 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004917 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004918 int frameCount,
4919 const sp<IMemory>& sharedBuffer,
4920 int sessionId)
4921 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004922 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004923 mQueueHeadInFlight(false),
4924 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004925 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004926 mTimedSilenceBuffer(NULL),
4927 mTimedSilenceBufferSize(0),
4928 mTimedAudioOutputOnTime(false),
4929 mMediaTimeTransformValid(false)
4930{
4931 LocalClock lc;
4932 mLocalTimeFreq = lc.getLocalFreq();
4933
4934 mLocalTimeToSampleTransform.a_zero = 0;
4935 mLocalTimeToSampleTransform.b_zero = 0;
4936 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4937 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4938 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4939 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004940
4941 mMediaTimeToSampleTransform.a_zero = 0;
4942 mMediaTimeToSampleTransform.b_zero = 0;
4943 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4944 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4945 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4946 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004947}
4948
4949AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4950 mClient->releaseTimedTrack();
4951 delete [] mTimedSilenceBuffer;
4952}
4953
4954status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4955 size_t size, sp<IMemory>* buffer) {
4956
4957 Mutex::Autolock _l(mTimedBufferQueueLock);
4958
4959 trimTimedBufferQueue_l();
4960
4961 // lazily initialize the shared memory heap for timed buffers
4962 if (mTimedMemoryDealer == NULL) {
4963 const int kTimedBufferHeapSize = 512 << 10;
4964
4965 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4966 "AudioFlingerTimed");
4967 if (mTimedMemoryDealer == NULL)
4968 return NO_MEMORY;
4969 }
4970
4971 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4972 if (newBuffer == NULL) {
4973 newBuffer = mTimedMemoryDealer->allocate(size);
4974 if (newBuffer == NULL)
4975 return NO_MEMORY;
4976 }
4977
4978 *buffer = newBuffer;
4979 return NO_ERROR;
4980}
4981
4982// caller must hold mTimedBufferQueueLock
4983void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4984 int64_t mediaTimeNow;
4985 {
4986 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4987 if (!mMediaTimeTransformValid)
4988 return;
4989
4990 int64_t targetTimeNow;
4991 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4992 ? mCCHelper.getCommonTime(&targetTimeNow)
4993 : mCCHelper.getLocalTime(&targetTimeNow);
4994
4995 if (OK != res)
4996 return;
4997
4998 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4999 &mediaTimeNow)) {
5000 return;
5001 }
5002 }
5003
John Grossman1c345192012-03-27 14:00:17 -07005004 size_t trimEnd;
5005 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07005006 int64_t bufEnd;
5007
John Grossmanc95cfbb2012-04-12 11:53:11 -07005008 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
5009 // We have a next buffer. Just use its PTS as the PTS of the frame
5010 // following the last frame in this buffer. If the stream is sparse
5011 // (ie, there are deliberate gaps left in the stream which should be
5012 // filled with silence by the TimedAudioTrack), then this can result
5013 // in one extra buffer being left un-trimmed when it could have
5014 // been. In general, this is not typical, and we would rather
5015 // optimized away the TS calculation below for the more common case
5016 // where PTSes are contiguous.
5017 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
5018 } else {
5019 // We have no next buffer. Compute the PTS of the frame following
5020 // the last frame in this buffer by computing the duration of of
5021 // this frame in media time units and adding it to the PTS of the
5022 // buffer.
5023 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
5024 / mCblk->frameSize;
5025
5026 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
5027 &bufEnd)) {
5028 ALOGE("Failed to convert frame count of %lld to media time"
5029 " duration" " (scale factor %d/%u) in %s",
5030 frameCount,
5031 mMediaTimeToSampleTransform.a_to_b_numer,
5032 mMediaTimeToSampleTransform.a_to_b_denom,
5033 __PRETTY_FUNCTION__);
5034 break;
5035 }
5036 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07005037 }
John Grossman9fbdee12012-03-26 17:51:46 -07005038
5039 if (bufEnd > mediaTimeNow)
5040 break;
5041
5042 // Is the buffer we want to use in the middle of a mix operation right
5043 // now? If so, don't actually trim it. Just wait for the releaseBuffer
5044 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07005045 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07005046 mTrimQueueHeadOnRelease = true;
5047 }
John Grossman4ff14ba2012-02-08 16:37:41 -08005048 }
5049
John Grossman9fbdee12012-03-26 17:51:46 -07005050 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07005051 if (trimStart < trimEnd) {
5052 // Update the bookkeeping for framesReady()
5053 for (size_t i = trimStart; i < trimEnd; ++i) {
5054 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
5055 }
5056
5057 // Now actually remove the buffers from the queue.
5058 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08005059 }
5060}
5061
John Grossman1c345192012-03-27 14:00:17 -07005062void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
5063 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07005064 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
5065 "%s called (reason \"%s\"), but timed buffer queue has no"
5066 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005067
5068 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
5069 mTimedBufferQueue.removeAt(0);
5070}
5071
5072void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
5073 const TimedBuffer& buf,
5074 const char* logTag) {
5075 uint32_t bufBytes = buf.buffer()->size();
5076 uint32_t consumedAlready = buf.position();
5077
Eric Laurentb388e532012-04-14 13:32:48 -07005078 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07005079 "Bad bookkeeping while updating frames pending. Timed buffer is"
5080 " only %u bytes long, but claims to have consumed %u"
5081 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07005082 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005083
5084 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07005085 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
5086 "Bad bookkeeping while updating frames pending. Should have at"
5087 " least %u queued frames, but we think we have only %u. (update"
5088 " reason: \"%s\")",
5089 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07005090
5091 mFramesPendingInQueue -= bufFrames;
5092}
5093
John Grossman4ff14ba2012-02-08 16:37:41 -08005094status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5095 const sp<IMemory>& buffer, int64_t pts) {
5096
5097 {
5098 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5099 if (!mMediaTimeTransformValid)
5100 return INVALID_OPERATION;
5101 }
5102
5103 Mutex::Autolock _l(mTimedBufferQueueLock);
5104
John Grossman1c345192012-03-27 14:00:17 -07005105 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5106 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005107 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5108
5109 return NO_ERROR;
5110}
5111
5112status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5113 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5114
John Grossman1c345192012-03-27 14:00:17 -07005115 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5116 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5117 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005118
5119 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5120 target == TimedAudioTrack::COMMON_TIME)) {
5121 return BAD_VALUE;
5122 }
5123
5124 Mutex::Autolock lock(mMediaTimeTransformLock);
5125 mMediaTimeTransform = xform;
5126 mMediaTimeTransformTarget = target;
5127 mMediaTimeTransformValid = true;
5128
5129 return NO_ERROR;
5130}
5131
5132#define min(a, b) ((a) < (b) ? (a) : (b))
5133
5134// implementation of getNextBuffer for tracks whose buffers have timestamps
5135status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5136 AudioBufferProvider::Buffer* buffer, int64_t pts)
5137{
5138 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005139 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005140 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005141 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005142 return INVALID_OPERATION;
5143 }
5144
John Grossman4ff14ba2012-02-08 16:37:41 -08005145 Mutex::Autolock _l(mTimedBufferQueueLock);
5146
John Grossman9fbdee12012-03-26 17:51:46 -07005147 ALOG_ASSERT(!mQueueHeadInFlight,
5148 "getNextBuffer called without releaseBuffer!");
5149
John Grossman4ff14ba2012-02-08 16:37:41 -08005150 while (true) {
5151
5152 // if we have no timed buffers, then fail
5153 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005154 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005155 buffer->frameCount = 0;
5156 return NOT_ENOUGH_DATA;
5157 }
5158
5159 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5160
5161 // calculate the PTS of the head of the timed buffer queue expressed in
5162 // local time
5163 int64_t headLocalPTS;
5164 {
5165 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5166
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005167 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005168
5169 if (mMediaTimeTransform.a_to_b_denom == 0) {
5170 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005171 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005172 return NO_ERROR;
5173 }
5174
5175 int64_t transformedPTS;
5176 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5177 &transformedPTS)) {
5178 // the transform failed. this shouldn't happen, but if it does
5179 // then just drop this buffer
5180 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005181 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005182 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005183 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005184 return NO_ERROR;
5185 }
5186
5187 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5188 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5189 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005190 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005191 buffer->frameCount = 0;
5192 return INVALID_OPERATION;
5193 }
5194 } else {
5195 headLocalPTS = transformedPTS;
5196 }
5197 }
5198
5199 // adjust the head buffer's PTS to reflect the portion of the head buffer
5200 // that has already been consumed
5201 int64_t effectivePTS = headLocalPTS +
5202 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5203
5204 // Calculate the delta in samples between the head of the input buffer
5205 // queue and the start of the next output buffer that will be written.
5206 // If the transformation fails because of over or underflow, it means
5207 // that the sample's position in the output stream is so far out of
5208 // whack that it should just be dropped.
5209 int64_t sampleDelta;
5210 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5211 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005212 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5213 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005214 continue;
5215 }
5216 if (!mLocalTimeToSampleTransform.doForwardTransform(
5217 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005218 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005219 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005220 continue;
5221 }
5222
John Grossman1c345192012-03-27 14:00:17 -07005223 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5224 " sampleDelta=[%d.%08x]",
5225 head.pts(), head.position(), pts,
5226 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5227 + (sampleDelta >> 32)),
5228 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005229
5230 // if the delta between the ideal placement for the next input sample and
5231 // the current output position is within this threshold, then we will
5232 // concatenate the next input samples to the previous output
5233 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005234 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005235
5236 // if this is the first buffer of audio that we're emitting from this track
5237 // then it should be almost exactly on time.
5238 const int64_t kSampleStartupThreshold = 1LL << 32;
5239
5240 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005241 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005242 // the next input is close enough to being on time, so concatenate it
5243 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005244 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005245
John Grossman1c345192012-03-27 14:00:17 -07005246 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5247 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005248 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005249 }
5250
5251 // Looks like our output is not on time. Reset our on timed status.
5252 // Next time we mix samples from our input queue, then should be within
5253 // the StartupThreshold.
5254 mTimedAudioOutputOnTime = false;
5255 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005256 // the gap between the current output position and the proper start of
5257 // the next input sample is too big, so fill it with silence
5258 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5259
John Grossman9fbdee12012-03-26 17:51:46 -07005260 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005261 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5262 return NO_ERROR;
5263 } else {
5264 // the next input sample is late
5265 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5266 size_t onTimeSamplePosition =
5267 head.position() + lateFrames * mCblk->frameSize;
5268
5269 if (onTimeSamplePosition > head.buffer()->size()) {
5270 // all the remaining samples in the head are too late, so
5271 // drop it and move on
5272 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005273 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005274 continue;
5275 } else {
5276 // skip over the late samples
5277 head.setPosition(onTimeSamplePosition);
5278
5279 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005280 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005281
5282 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5283 return NO_ERROR;
5284 }
5285 }
5286 }
5287}
5288
5289// Yield samples from the timed buffer queue head up to the given output
5290// buffer's capacity.
5291//
5292// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005293void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005294 AudioBufferProvider::Buffer* buffer) {
5295
5296 const TimedBuffer& head = mTimedBufferQueue[0];
5297
5298 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5299 head.position());
5300
5301 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5302 mCblk->frameSize);
5303 size_t framesRequested = buffer->frameCount;
5304 buffer->frameCount = min(framesLeftInHead, framesRequested);
5305
John Grossman9fbdee12012-03-26 17:51:46 -07005306 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005307 mTimedAudioOutputOnTime = true;
5308}
5309
5310// Yield samples of silence up to the given output buffer's capacity
5311//
5312// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005313void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005314 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5315
5316 // lazily allocate a buffer filled with silence
5317 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5318 delete [] mTimedSilenceBuffer;
5319 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5320 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5321 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5322 }
5323
5324 buffer->raw = mTimedSilenceBuffer;
5325 size_t framesRequested = buffer->frameCount;
5326 buffer->frameCount = min(numFrames, framesRequested);
5327
5328 mTimedAudioOutputOnTime = false;
5329}
5330
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005331// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005332void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5333 AudioBufferProvider::Buffer* buffer) {
5334
5335 Mutex::Autolock _l(mTimedBufferQueueLock);
5336
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005337 // If the buffer which was just released is part of the buffer at the head
5338 // of the queue, be sure to update the amt of the buffer which has been
5339 // consumed. If the buffer being returned is not part of the head of the
5340 // queue, its either because the buffer is part of the silence buffer, or
5341 // because the head of the timed queue was trimmed after the mixer called
5342 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005343 if (buffer->raw == mTimedSilenceBuffer) {
5344 ALOG_ASSERT(!mQueueHeadInFlight,
5345 "Queue head in flight during release of silence buffer!");
5346 goto done;
5347 }
5348
5349 ALOG_ASSERT(mQueueHeadInFlight,
5350 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5351 " head in flight.");
5352
5353 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005354 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005355
5356 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005357 void* end = reinterpret_cast<void*>(
5358 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5359 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005360
John Grossman9fbdee12012-03-26 17:51:46 -07005361 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5362 "released buffer not within the head of the timed buffer"
5363 " queue; qHead = [%p, %p], released buffer = %p",
5364 start, end, buffer->raw);
5365
5366 head.setPosition(head.position() +
5367 (buffer->frameCount * mCblk->frameSize));
5368 mQueueHeadInFlight = false;
5369
John Grossman1c345192012-03-27 14:00:17 -07005370 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5371 "Bad bookkeeping during releaseBuffer! Should have at"
5372 " least %u queued frames, but we think we have only %u",
5373 buffer->frameCount, mFramesPendingInQueue);
5374
5375 mFramesPendingInQueue -= buffer->frameCount;
5376
John Grossman9fbdee12012-03-26 17:51:46 -07005377 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5378 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005379 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005380 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005381 }
John Grossman9fbdee12012-03-26 17:51:46 -07005382 } else {
5383 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5384 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005385 }
5386
John Grossman9fbdee12012-03-26 17:51:46 -07005387done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005388 buffer->raw = 0;
5389 buffer->frameCount = 0;
5390}
5391
Glenn Kasten288ed212012-04-25 17:52:27 -07005392size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005393 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005394 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005395}
5396
5397AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5398 : mPTS(0), mPosition(0) {}
5399
5400AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5401 const sp<IMemory>& buffer, int64_t pts)
5402 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5403
Mathias Agopian65ab4712010-07-14 17:59:35 -07005404// ----------------------------------------------------------------------------
5405
5406// RecordTrack constructor must be called with AudioFlinger::mLock held
5407AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005408 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005409 const sp<Client>& client,
5410 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005411 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005412 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005413 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005414 int sessionId)
5415 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005416 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005417 mOverflow(false)
5418{
5419 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005420 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5421 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5422 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5423 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5424 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5425 } else {
5426 mCblk->frameSize = sizeof(int8_t);
5427 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005428 }
5429}
5430
5431AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5432{
Glenn Kasten510a3d62012-07-16 14:24:34 -07005433 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005434}
5435
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005436// AudioBufferProvider interface
Glenn Kasten85ab62c2012-11-01 11:11:38 -07005437status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
5438 int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005439{
5440 audio_track_cblk_t* cblk = this->cblk();
5441 uint32_t framesAvail;
5442 uint32_t framesReq = buffer->frameCount;
5443
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005444 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005445 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005447 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005448 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005449 }
5450
5451 framesAvail = cblk->framesAvailable_l();
5452
Glenn Kastenf6b16782011-12-15 09:51:17 -08005453 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005454 uint32_t s = cblk->server;
5455 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5456
5457 if (framesReq > framesAvail) {
5458 framesReq = framesAvail;
5459 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005460 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005461 framesReq = bufferEnd - s;
5462 }
5463
5464 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005465 buffer->frameCount = framesReq;
5466 return NO_ERROR;
5467 }
5468
5469getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005470 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005471 buffer->frameCount = 0;
5472 return NOT_ENOUGH_DATA;
5473}
5474
Glenn Kasten3acbd052012-02-28 10:39:56 -08005475status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005476 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005477{
5478 sp<ThreadBase> thread = mThread.promote();
5479 if (thread != 0) {
5480 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005481 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005482 } else {
5483 return BAD_VALUE;
5484 }
5485}
5486
5487void AudioFlinger::RecordThread::RecordTrack::stop()
5488{
5489 sp<ThreadBase> thread = mThread.promote();
5490 if (thread != 0) {
5491 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005492 recordThread->mLock.lock();
5493 bool doStop = recordThread->stop_l(this);
5494 if (doStop) {
5495 TrackBase::reset();
5496 // Force overrun condition to avoid false overrun callback until first data is
5497 // read from buffer
5498 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5499 }
5500 recordThread->mLock.unlock();
5501 if (doStop) {
5502 AudioSystem::stopInput(recordThread->id());
5503 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005504 }
5505}
5506
Glenn Kasten510a3d62012-07-16 14:24:34 -07005507/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
5508{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005509 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User FrameCount\n");
Glenn Kasten510a3d62012-07-16 14:24:34 -07005510}
5511
Mathias Agopian65ab4712010-07-14 17:59:35 -07005512void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5513{
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005514 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x %05d\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005515 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005516 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005517 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005518 mSessionId,
5519 mFrameCount,
5520 mState,
5521 mCblk->sampleRate,
5522 mCblk->server,
Jean-Michel Trivi52762412012-09-12 18:48:33 -07005523 mCblk->user,
5524 mCblk->frameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005525}
5526
5527
5528// ----------------------------------------------------------------------------
5529
5530AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005531 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005532 DuplicatingThread *sourceThread,
5533 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005534 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005535 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005536 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005537 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5538 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005539 mActive(false), mSourceThread(sourceThread)
5540{
5541
Mathias Agopian65ab4712010-07-14 17:59:35 -07005542 if (mCblk != NULL) {
5543 mCblk->flags |= CBLK_DIRECTION_OUT;
5544 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005545 mOutBuffer.frameCount = 0;
5546 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005547 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005548 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5549 mCblk, mBuffer, mCblk->buffers,
5550 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005551 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005552 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005553 }
5554}
5555
5556AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5557{
5558 clearBufferQueue();
5559}
5560
Glenn Kasten3acbd052012-02-28 10:39:56 -08005561status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005562 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005563{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005564 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005565 if (status != NO_ERROR) {
5566 return status;
5567 }
5568
5569 mActive = true;
5570 mRetryCount = 127;
5571 return status;
5572}
5573
5574void AudioFlinger::PlaybackThread::OutputTrack::stop()
5575{
5576 Track::stop();
5577 clearBufferQueue();
5578 mOutBuffer.frameCount = 0;
5579 mActive = false;
5580}
5581
5582bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5583{
5584 Buffer *pInBuffer;
5585 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005586 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005587 bool outputBufferFull = false;
5588 inBuffer.frameCount = frames;
5589 inBuffer.i16 = data;
5590
5591 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5592
5593 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005594 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005595 sp<ThreadBase> thread = mThread.promote();
5596 if (thread != 0) {
5597 MixerThread *mixerThread = (MixerThread *)thread.get();
5598 if (mCblk->frameCount > frames){
5599 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5600 uint32_t startFrames = (mCblk->frameCount - frames);
5601 pInBuffer = new Buffer;
5602 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5603 pInBuffer->frameCount = startFrames;
5604 pInBuffer->i16 = pInBuffer->mBuffer;
5605 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5606 mBufferQueue.add(pInBuffer);
5607 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005608 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005609 }
5610 }
5611 }
5612 }
5613
5614 while (waitTimeLeftMs) {
5615 // First write pending buffers, then new data
5616 if (mBufferQueue.size()) {
5617 pInBuffer = mBufferQueue.itemAt(0);
5618 } else {
5619 pInBuffer = &inBuffer;
5620 }
5621
5622 if (pInBuffer->frameCount == 0) {
5623 break;
5624 }
5625
5626 if (mOutBuffer.frameCount == 0) {
5627 mOutBuffer.frameCount = pInBuffer->frameCount;
5628 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005629 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07005630 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this,
5631 mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005632 outputBufferFull = true;
5633 break;
5634 }
5635 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5636 if (waitTimeLeftMs >= waitTimeMs) {
5637 waitTimeLeftMs -= waitTimeMs;
5638 } else {
5639 waitTimeLeftMs = 0;
5640 }
5641 }
5642
Glenn Kasten85ab62c2012-11-01 11:11:38 -07005643 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
5644 pInBuffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005645 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5646 mCblk->stepUser(outFrames);
5647 pInBuffer->frameCount -= outFrames;
5648 pInBuffer->i16 += outFrames * channelCount;
5649 mOutBuffer.frameCount -= outFrames;
5650 mOutBuffer.i16 += outFrames * channelCount;
5651
5652 if (pInBuffer->frameCount == 0) {
5653 if (mBufferQueue.size()) {
5654 mBufferQueue.removeAt(0);
5655 delete [] pInBuffer->mBuffer;
5656 delete pInBuffer;
Glenn Kasten85ab62c2012-11-01 11:11:38 -07005657 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
5658 mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005659 } else {
5660 break;
5661 }
5662 }
5663 }
5664
5665 // If we could not write all frames, allocate a buffer and queue it for next time.
5666 if (inBuffer.frameCount) {
5667 sp<ThreadBase> thread = mThread.promote();
5668 if (thread != 0 && !thread->standby()) {
5669 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5670 pInBuffer = new Buffer;
5671 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5672 pInBuffer->frameCount = inBuffer.frameCount;
5673 pInBuffer->i16 = pInBuffer->mBuffer;
Glenn Kasten85ab62c2012-11-01 11:11:38 -07005674 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
5675 sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005676 mBufferQueue.add(pInBuffer);
Glenn Kasten85ab62c2012-11-01 11:11:38 -07005677 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
5678 mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005679 } else {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07005680 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
5681 mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005682 }
5683 }
5684 }
5685
5686 // Calling write() with a 0 length buffer, means that no more data will be written:
5687 // If no more buffers are pending, fill output track buffer to make sure it is started
5688 // by output mixer.
5689 if (frames == 0 && mBufferQueue.size() == 0) {
5690 if (mCblk->user < mCblk->frameCount) {
5691 frames = mCblk->frameCount - mCblk->user;
5692 pInBuffer = new Buffer;
5693 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5694 pInBuffer->frameCount = frames;
5695 pInBuffer->i16 = pInBuffer->mBuffer;
5696 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5697 mBufferQueue.add(pInBuffer);
5698 } else if (mActive) {
5699 stop();
5700 }
5701 }
5702
5703 return outputBufferFull;
5704}
5705
Glenn Kasten85ab62c2012-11-01 11:11:38 -07005706status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
5707 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005708{
5709 int active;
5710 status_t result;
5711 audio_track_cblk_t* cblk = mCblk;
5712 uint32_t framesReq = buffer->frameCount;
5713
Glenn Kasten26dd66e2012-10-18 15:51:03 -07005714 ALOGVV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005715 buffer->frameCount = 0;
5716
5717 uint32_t framesAvail = cblk->framesAvailable();
5718
5719
5720 if (framesAvail == 0) {
5721 Mutex::Autolock _l(cblk->lock);
5722 goto start_loop_here;
5723 while (framesAvail == 0) {
5724 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005725 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005726 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005727 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005728 }
5729 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5730 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005731 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005732 }
5733 // read the server count again
5734 start_loop_here:
5735 framesAvail = cblk->framesAvailable_l();
5736 }
5737 }
5738
5739// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005740// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005741// }
5742
5743 if (framesReq > framesAvail) {
5744 framesReq = framesAvail;
5745 }
5746
5747 uint32_t u = cblk->user;
5748 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5749
Marco Nelissena1472d92012-03-30 14:36:54 -07005750 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005751 framesReq = bufferEnd - u;
5752 }
5753
5754 buffer->frameCount = framesReq;
5755 buffer->raw = (void *)cblk->buffer(u);
5756 return NO_ERROR;
5757}
5758
5759
5760void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5761{
5762 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005763
5764 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005765 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005766 delete [] pBuffer->mBuffer;
5767 delete pBuffer;
5768 }
5769 mBufferQueue.clear();
5770}
5771
5772// ----------------------------------------------------------------------------
5773
5774AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5775 : RefBase(),
5776 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005777 // 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 -07005778 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005779 mPid(pid),
5780 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005781{
5782 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5783}
5784
5785// Client destructor must be called with AudioFlinger::mLock held
5786AudioFlinger::Client::~Client()
5787{
5788 mAudioFlinger->removeClient_l(mPid);
5789}
5790
Glenn Kasten435dbe62012-01-30 10:15:48 -08005791sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005792{
5793 return mMemoryDealer;
5794}
5795
John Grossman4ff14ba2012-02-08 16:37:41 -08005796// Reserve one of the limited slots for a timed audio track associated
5797// with this client
5798bool AudioFlinger::Client::reserveTimedTrack()
5799{
5800 const int kMaxTimedTracksPerClient = 4;
5801
5802 Mutex::Autolock _l(mTimedTrackLock);
5803
5804 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5805 ALOGW("can not create timed track - pid %d has exceeded the limit",
5806 mPid);
5807 return false;
5808 }
5809
5810 mTimedTrackCount++;
5811 return true;
5812}
5813
5814// Release a slot for a timed audio track
5815void AudioFlinger::Client::releaseTimedTrack()
5816{
5817 Mutex::Autolock _l(mTimedTrackLock);
5818 mTimedTrackCount--;
5819}
5820
Mathias Agopian65ab4712010-07-14 17:59:35 -07005821// ----------------------------------------------------------------------------
5822
5823AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5824 const sp<IAudioFlingerClient>& client,
5825 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005826 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005827{
5828}
5829
5830AudioFlinger::NotificationClient::~NotificationClient()
5831{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005832}
5833
5834void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5835{
5836 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005837 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005838}
5839
5840// ----------------------------------------------------------------------------
5841
5842AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5843 : BnAudioTrack(),
5844 mTrack(track)
5845{
5846}
5847
5848AudioFlinger::TrackHandle::~TrackHandle() {
5849 // just stop the track on deletion, associated resources
5850 // will be freed from the main thread once all pending buffers have
5851 // been played. Unless it's not in the active track list, in which
5852 // case we free everything now...
5853 mTrack->destroy();
5854}
5855
Glenn Kasten90716c52012-01-26 13:40:12 -08005856sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5857 return mTrack->getCblk();
5858}
5859
Glenn Kasten3acbd052012-02-28 10:39:56 -08005860status_t AudioFlinger::TrackHandle::start() {
5861 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005862}
5863
5864void AudioFlinger::TrackHandle::stop() {
5865 mTrack->stop();
5866}
5867
5868void AudioFlinger::TrackHandle::flush() {
5869 mTrack->flush();
5870}
5871
5872void AudioFlinger::TrackHandle::mute(bool e) {
5873 mTrack->mute(e);
5874}
5875
5876void AudioFlinger::TrackHandle::pause() {
5877 mTrack->pause();
5878}
5879
Mathias Agopian65ab4712010-07-14 17:59:35 -07005880status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5881{
5882 return mTrack->attachAuxEffect(EffectId);
5883}
5884
John Grossman4ff14ba2012-02-08 16:37:41 -08005885status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5886 sp<IMemory>* buffer) {
5887 if (!mTrack->isTimedTrack())
5888 return INVALID_OPERATION;
5889
5890 PlaybackThread::TimedTrack* tt =
5891 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5892 return tt->allocateTimedBuffer(size, buffer);
5893}
5894
5895status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5896 int64_t pts) {
5897 if (!mTrack->isTimedTrack())
5898 return INVALID_OPERATION;
5899
5900 PlaybackThread::TimedTrack* tt =
5901 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5902 return tt->queueTimedBuffer(buffer, pts);
5903}
5904
5905status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5906 const LinearTransform& xform, int target) {
5907
5908 if (!mTrack->isTimedTrack())
5909 return INVALID_OPERATION;
5910
5911 PlaybackThread::TimedTrack* tt =
5912 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5913 return tt->setMediaTimeTransform(
5914 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5915}
5916
Mathias Agopian65ab4712010-07-14 17:59:35 -07005917status_t AudioFlinger::TrackHandle::onTransact(
5918 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5919{
5920 return BnAudioTrack::onTransact(code, data, reply, flags);
5921}
5922
5923// ----------------------------------------------------------------------------
5924
5925sp<IAudioRecord> AudioFlinger::openRecord(
5926 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005927 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005928 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005929 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005930 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005931 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005932 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07005933 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005934 int *sessionId,
5935 status_t *status)
5936{
5937 sp<RecordThread::RecordTrack> recordTrack;
5938 sp<RecordHandle> recordHandle;
5939 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005940 status_t lStatus;
5941 RecordThread *thread;
5942 size_t inFrameCount;
5943 int lSessionId;
5944
5945 // check calling permissions
5946 if (!recordingAllowed()) {
5947 lStatus = PERMISSION_DENIED;
5948 goto Exit;
5949 }
5950
5951 // add client to list
5952 { // scope for mLock
5953 Mutex::Autolock _l(mLock);
5954 thread = checkRecordThread_l(input);
5955 if (thread == NULL) {
5956 lStatus = BAD_VALUE;
5957 goto Exit;
5958 }
5959
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005960 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005961
5962 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005963 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005964 lSessionId = *sessionId;
5965 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005966 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005967 if (sessionId != NULL) {
5968 *sessionId = lSessionId;
5969 }
5970 }
Glenn Kasten85ab62c2012-11-01 11:11:38 -07005971 // create new record track.
5972 // The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07005973 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5974 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005975 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005976 if (lStatus != NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07005977 // remove local strong reference to Client before deleting the RecordTrack so that the
5978 // Client destructor is called by the TrackBase destructor with mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07005979 client.clear();
5980 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005981 goto Exit;
5982 }
5983
5984 // return to handle to client
5985 recordHandle = new RecordHandle(recordTrack);
5986 lStatus = NO_ERROR;
5987
5988Exit:
5989 if (status) {
5990 *status = lStatus;
5991 }
5992 return recordHandle;
5993}
5994
5995// ----------------------------------------------------------------------------
5996
Glenn Kasten85ab62c2012-11-01 11:11:38 -07005997AudioFlinger::RecordHandle::RecordHandle(
5998 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005999 : BnAudioRecord(),
6000 mRecordTrack(recordTrack)
6001{
6002}
6003
6004AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07006005 stop_nonvirtual();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006006 mRecordTrack->destroy();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006007}
6008
Glenn Kasten90716c52012-01-26 13:40:12 -08006009sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
6010 return mRecordTrack->getCblk();
6011}
6012
Glenn Kasten85ab62c2012-11-01 11:11:38 -07006013status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
6014 int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01006015 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08006016 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006017}
6018
6019void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07006020 stop_nonvirtual();
6021}
6022
6023void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01006024 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006025 mRecordTrack->stop();
6026}
6027
Mathias Agopian65ab4712010-07-14 17:59:35 -07006028status_t AudioFlinger::RecordHandle::onTransact(
6029 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6030{
6031 return BnAudioRecord::onTransact(code, data, reply, flags);
6032}
6033
6034// ----------------------------------------------------------------------------
6035
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006036AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6037 AudioStreamIn *input,
6038 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07006039 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006040 audio_io_handle_t id,
Glenn Kastend06785b2012-09-30 12:29:28 -07006041 audio_devices_t device,
6042 const sp<NBAIO_Sink>& teeSink) :
Eric Laurentf1c04f92012-08-28 14:26:53 -07006043 ThreadBase(audioFlinger, id, AUDIO_DEVICE_NONE, device, RECORD),
Glenn Kasten510a3d62012-07-16 14:24:34 -07006044 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006045 // mRsmpInIndex and mInputBytes set by readInputParameters()
Glenn Kasten254af182012-07-03 14:59:05 -07006046 mReqChannelCount(popcount(channelMask)),
Glenn Kastend06785b2012-09-30 12:29:28 -07006047 mReqSampleRate(sampleRate),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08006048 // mBytesRead is only meaningful while active, and so is cleared in start()
6049 // (but might be better to also clear here for dump?)
Glenn Kastend06785b2012-09-30 12:29:28 -07006050 mTeeSink(teeSink)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006051{
Glenn Kasten480b4682012-02-28 12:30:08 -08006052 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07006053
Mathias Agopian65ab4712010-07-14 17:59:35 -07006054 readInputParameters();
Glenn Kastend06785b2012-09-30 12:29:28 -07006055
Mathias Agopian65ab4712010-07-14 17:59:35 -07006056}
6057
6058
6059AudioFlinger::RecordThread::~RecordThread()
6060{
6061 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08006062 delete mResampler;
6063 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006064}
6065
6066void AudioFlinger::RecordThread::onFirstRef()
6067{
Eric Laurentfeb0db62011-07-22 09:04:31 -07006068 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006069}
6070
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006071status_t AudioFlinger::RecordThread::readyToRun()
6072{
6073 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00006074 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006075 return status;
6076}
6077
Mathias Agopian65ab4712010-07-14 17:59:35 -07006078bool AudioFlinger::RecordThread::threadLoop()
6079{
6080 AudioBufferProvider::Buffer buffer;
6081 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006082 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006083
Eric Laurent44d98482010-09-30 16:12:31 -07006084 nsecs_t lastWarning = 0;
6085
Glenn Kastene4e2a372012-07-23 12:55:09 -07006086 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07006087 acquireWakeLock();
6088
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07006089 // used to verify we've read at least once before evaluating how many bytes were read
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006090 bool readOnce = false;
6091
Mathias Agopian65ab4712010-07-14 17:59:35 -07006092 // start recording
6093 while (!exitPending()) {
6094
6095 processConfigEvents();
6096
6097 { // scope for mLock
6098 Mutex::Autolock _l(mLock);
6099 checkForNewParameters_l();
6100 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006101 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006102
6103 if (exitPending()) break;
6104
Eric Laurentfeb0db62011-07-22 09:04:31 -07006105 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01006106 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006107 // go to sleep
6108 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006109 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006110 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006111 continue;
6112 }
6113 if (mActiveTrack != 0) {
6114 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006115 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006116 mActiveTrack.clear();
6117 mStartStopCond.broadcast();
6118 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6119 if (mReqChannelCount != mActiveTrack->channelCount()) {
6120 mActiveTrack.clear();
6121 mStartStopCond.broadcast();
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006122 } else if (readOnce) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006123 // record start succeeds only if first read from audio input
6124 // succeeds
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006125 if (mBytesRead >= 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006126 mActiveTrack->mState = TrackBase::ACTIVE;
6127 } else {
6128 mActiveTrack.clear();
6129 }
6130 mStartStopCond.broadcast();
6131 }
6132 mStandby = false;
Glenn Kasten510a3d62012-07-16 14:24:34 -07006133 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
6134 removeTrack_l(mActiveTrack);
6135 mActiveTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006136 }
6137 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006138 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006139 }
6140
6141 if (mActiveTrack != 0) {
6142 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6143 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006144 unlockEffectChains(effectChains);
6145 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006146 continue;
6147 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006148 for (size_t i = 0; i < effectChains.size(); i ++) {
6149 effectChains[i]->process_l();
6150 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006151
Mathias Agopian65ab4712010-07-14 17:59:35 -07006152 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006153 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006154 readOnce = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006155 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006156 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006157 // no resampling
6158 while (framesOut) {
6159 size_t framesIn = mFrameCount - mRsmpInIndex;
6160 if (framesIn) {
6161 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
Glenn Kasten85ab62c2012-11-01 11:11:38 -07006162 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) *
6163 mActiveTrack->mCblk->frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006164 if (framesIn > framesOut)
6165 framesIn = framesOut;
6166 mRsmpInIndex += framesIn;
6167 framesOut -= framesIn;
6168 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006169 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006170 memcpy(dst, src, framesIn * mFrameSize);
6171 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006172 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006173 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6174 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006175 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006176 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6177 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006178 }
6179 }
6180 }
6181 if (framesOut && mFrameCount == mRsmpInIndex) {
Glenn Kastend06785b2012-09-30 12:29:28 -07006182 void *readInto;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006183 if (framesOut == mFrameCount &&
Glenn Kasten85ab62c2012-11-01 11:11:38 -07006184 ((int)mChannelCount == mReqChannelCount ||
6185 mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Glenn Kastend06785b2012-09-30 12:29:28 -07006186 readInto = buffer.raw;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006187 framesOut = 0;
6188 } else {
Glenn Kastend06785b2012-09-30 12:29:28 -07006189 readInto = mRsmpInBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006190 mRsmpInIndex = 0;
6191 }
Glenn Kastend06785b2012-09-30 12:29:28 -07006192 mBytesRead = mInput->stream->read(mInput->stream, readInto, mInputBytes);
Jean-Michel Trivi52762412012-09-12 18:48:33 -07006193 if (mBytesRead <= 0) {
6194 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE))
6195 {
6196 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006197 // Force input into standby so that it tries to
6198 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006199 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006200 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006201 }
6202 mRsmpInIndex = mFrameCount;
6203 framesOut = 0;
6204 buffer.frameCount = 0;
Glenn Kastend06785b2012-09-30 12:29:28 -07006205 } else if (mTeeSink != 0) {
6206 (void) mTeeSink->write(readInto,
6207 mBytesRead >> Format_frameBitShift(mTeeSink->format()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006208 }
6209 }
6210 }
6211 } else {
6212 // resampling
6213
6214 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6215 // alter output frame count as if we were expecting stereo samples
6216 if (mChannelCount == 1 && mReqChannelCount == 1) {
6217 framesOut >>= 1;
6218 }
Glenn Kasten85ab62c2012-11-01 11:11:38 -07006219 mResampler->resample(mRsmpOutBuffer, framesOut,
6220 this /* AudioBufferProvider* */);
6221 // ditherAndClamp() works as long as all buffers returned by
6222 // mActiveTrack->getNextBuffer() are 32 bit aligned which should be always true.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006223 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006224 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Glenn Kasten85ab62c2012-11-01 11:11:38 -07006225 // the resampler always outputs stereo samples:
6226 // do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006227 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6228 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006229 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006230 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006231 }
6232
6233 }
Eric Laurenta011e352012-03-29 15:51:43 -07006234 if (mFramestoDrop == 0) {
6235 mActiveTrack->releaseBuffer(&buffer);
6236 } else {
6237 if (mFramestoDrop > 0) {
6238 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006239 if (mFramestoDrop <= 0) {
6240 clearSyncStartEvent();
6241 }
6242 } else {
6243 mFramestoDrop += buffer.frameCount;
6244 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6245 mSyncStartEvent->isCancelled()) {
6246 ALOGW("Synced record %s, session %d, trigger session %d",
6247 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6248 mActiveTrack->sessionId(),
6249 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6250 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006251 }
6252 }
6253 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006254 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006255 }
6256 // client isn't retrieving buffers fast enough
6257 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006258 if (!mActiveTrack->setOverflow()) {
6259 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006260 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006261 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006262 lastWarning = now;
6263 }
6264 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006265 // Release the processor for a while before asking for a new buffer.
6266 // This will give the application more chance to read from the buffer and
6267 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006268 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006269 }
6270 }
Eric Laurentec437d82011-07-26 20:54:46 -07006271 // enable changes in effect chain
6272 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006273 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006274 }
6275
Glenn Kastene4e2a372012-07-23 12:55:09 -07006276 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006277
Glenn Kasten33e6e352012-07-16 15:56:57 -07006278 {
6279 Mutex::Autolock _l(mLock);
6280 mActiveTrack.clear();
6281 mStartStopCond.broadcast();
6282 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006283
Eric Laurentfeb0db62011-07-22 09:04:31 -07006284 releaseWakeLock();
6285
Steve Block3856b092011-10-20 11:56:00 +01006286 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006287 return false;
6288}
6289
Glenn Kastene4e2a372012-07-23 12:55:09 -07006290void AudioFlinger::RecordThread::standby()
6291{
6292 if (!mStandby) {
6293 inputStandBy();
6294 mStandby = true;
6295 }
6296}
6297
6298void AudioFlinger::RecordThread::inputStandBy()
6299{
6300 mInput->stream->common.standby(&mInput->stream->common);
6301}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006302
6303sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6304 const sp<AudioFlinger::Client>& client,
6305 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006306 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006307 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006308 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006309 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006310 IAudioFlinger::track_flags_t flags,
6311 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006312 status_t *status)
6313{
6314 sp<RecordTrack> track;
6315 status_t lStatus;
6316
6317 lStatus = initCheck();
6318 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006319 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006320 goto Exit;
6321 }
6322
Glenn Kasten1879fff2012-07-11 15:36:59 -07006323 // FIXME use flags and tid similar to createTrack_l()
6324
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006325 { // scope for mLock
6326 Mutex::Autolock _l(mLock);
6327
6328 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006329 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006330
Glenn Kasten7378ca52012-01-20 13:44:40 -08006331 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006332 lStatus = NO_MEMORY;
6333 goto Exit;
6334 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006335 mTracks.add(track);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006336
Eric Laurent59bd0da2011-08-01 09:52:20 -07006337 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Eric Laurentf1c04f92012-08-28 14:26:53 -07006338 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006339 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006340 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6341 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006342 }
6343 lStatus = NO_ERROR;
6344
6345Exit:
6346 if (status) {
6347 *status = lStatus;
6348 }
6349 return track;
6350}
6351
Eric Laurenta011e352012-03-29 15:51:43 -07006352status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006353 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006354 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006355{
Glenn Kasten58912562012-04-03 10:45:00 -07006356 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006357 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006358 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006359
6360 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006361 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006362 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6363 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6364 triggerSession,
6365 recordTrack->sessionId(),
6366 syncStartEventCallback,
6367 this);
Eric Laurent29864602012-05-08 18:57:51 -07006368 // Sync event can be cancelled by the trigger session if the track is not in a
6369 // compatible state in which case we start record immediately
6370 if (mSyncStartEvent->isCancelled()) {
6371 clearSyncStartEvent();
6372 } else {
6373 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6374 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6375 }
Eric Laurenta011e352012-03-29 15:51:43 -07006376 }
6377
Mathias Agopian65ab4712010-07-14 17:59:35 -07006378 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006379 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006380 if (mActiveTrack != 0) {
6381 if (recordTrack != mActiveTrack.get()) {
6382 status = -EBUSY;
6383 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6384 mActiveTrack->mState = TrackBase::ACTIVE;
6385 }
6386 return status;
6387 }
6388
6389 recordTrack->mState = TrackBase::IDLE;
6390 mActiveTrack = recordTrack;
6391 mLock.unlock();
6392 status_t status = AudioSystem::startInput(mId);
6393 mLock.lock();
6394 if (status != NO_ERROR) {
6395 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006396 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006397 return status;
6398 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006399 mRsmpInIndex = mFrameCount;
6400 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006401 if (mResampler != NULL) {
6402 mResampler->reset();
6403 }
6404 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006405 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006406 ALOGV("Signal record thread");
Eric Laurentb6ba2fd2012-09-24 15:02:17 -07006407 mWaitWorkCV.broadcast();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006408 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006409 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006410 mActiveTrack.clear();
6411 status = INVALID_OPERATION;
6412 goto startError;
6413 }
6414 mStartStopCond.wait(mLock);
6415 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006416 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006417 status = BAD_VALUE;
6418 goto startError;
6419 }
Steve Block3856b092011-10-20 11:56:00 +01006420 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006421 return status;
6422 }
6423startError:
6424 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006425 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006426 return status;
6427}
6428
Eric Laurenta011e352012-03-29 15:51:43 -07006429void AudioFlinger::RecordThread::clearSyncStartEvent()
6430{
6431 if (mSyncStartEvent != 0) {
6432 mSyncStartEvent->cancel();
6433 }
6434 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006435 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006436}
6437
6438void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6439{
6440 sp<SyncEvent> strongEvent = event.promote();
6441
6442 if (strongEvent != 0) {
6443 RecordThread *me = (RecordThread *)strongEvent->cookie();
6444 me->handleSyncStartEvent(strongEvent);
6445 }
6446}
6447
6448void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6449{
Eric Laurent29864602012-05-08 18:57:51 -07006450 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006451 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6452 // from audio HAL
6453 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006454 }
6455}
6456
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006457bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006458 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006459 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
6460 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006461 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006462 recordTrack->mState = TrackBase::PAUSING;
6463 // do not wait for mStartStopCond if exiting
6464 if (exitPending()) {
6465 return true;
6466 }
6467 mStartStopCond.wait(mLock);
6468 // if we have been restarted, recordTrack == mActiveTrack.get() here
6469 if (exitPending() || recordTrack != mActiveTrack.get()) {
6470 ALOGV("Record stopped OK");
6471 return true;
6472 }
6473 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006474}
6475
Glenn Kasten106e8a42012-08-02 13:37:12 -07006476bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07006477{
6478 return false;
6479}
6480
6481status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6482{
Glenn Kasten7aa25592012-08-02 16:37:07 -07006483#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 -07006484 if (!isValidSyncEvent(event)) {
6485 return BAD_VALUE;
6486 }
6487
Glenn Kasten510a3d62012-07-16 14:24:34 -07006488 int eventSession = event->triggerSession();
6489 status_t ret = NAME_NOT_FOUND;
6490
Eric Laurenta011e352012-03-29 15:51:43 -07006491 Mutex::Autolock _l(mLock);
6492
Glenn Kasten510a3d62012-07-16 14:24:34 -07006493 for (size_t i = 0; i < mTracks.size(); i++) {
6494 sp<RecordTrack> track = mTracks[i];
6495 if (eventSession == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07006496 (void) track->setSyncEvent(event);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006497 ret = NO_ERROR;
6498 }
Eric Laurenta011e352012-03-29 15:51:43 -07006499 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006500 return ret;
Glenn Kasten7aa25592012-08-02 16:37:07 -07006501#else
6502 return BAD_VALUE;
6503#endif
Glenn Kasten510a3d62012-07-16 14:24:34 -07006504}
6505
6506void AudioFlinger::RecordThread::RecordTrack::destroy()
6507{
6508 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
6509 sp<RecordTrack> keep(this);
6510 {
6511 sp<ThreadBase> thread = mThread.promote();
6512 if (thread != 0) {
6513 if (mState == ACTIVE || mState == RESUMING) {
6514 AudioSystem::stopInput(thread->id());
6515 }
6516 AudioSystem::releaseInput(thread->id());
6517 Mutex::Autolock _l(thread->mLock);
6518 RecordThread *recordThread = (RecordThread *) thread.get();
6519 recordThread->destroyTrack_l(this);
6520 }
6521 }
6522}
6523
6524// destroyTrack_l() must be called with ThreadBase::mLock held
6525void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6526{
6527 track->mState = TrackBase::TERMINATED;
6528 // active tracks are removed by threadLoop()
6529 if (mActiveTrack != track) {
6530 removeTrack_l(track);
6531 }
6532}
6533
6534void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6535{
6536 mTracks.remove(track);
6537 // need anything related to effects here?
Eric Laurenta011e352012-03-29 15:51:43 -07006538}
6539
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07006540void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006541{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006542 dumpInternals(fd, args);
6543 dumpTracks(fd, args);
6544 dumpEffectChains(fd, args);
6545}
6546
6547void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6548{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006549 const size_t SIZE = 256;
6550 char buffer[SIZE];
6551 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006552
6553 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6554 result.append(buffer);
6555
6556 if (mActiveTrack != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006557 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6558 result.append(buffer);
6559 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6560 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006561 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006562 result.append(buffer);
6563 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6564 result.append(buffer);
6565 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6566 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006567 } else {
Glenn Kasten510a3d62012-07-16 14:24:34 -07006568 result.append("No active record client\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006569 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006570
Mathias Agopian65ab4712010-07-14 17:59:35 -07006571 write(fd, result.string(), result.size());
6572
6573 dumpBase(fd, args);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006574}
6575
6576void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
6577{
6578 const size_t SIZE = 256;
6579 char buffer[SIZE];
6580 String8 result;
6581
6582 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
6583 result.append(buffer);
6584 RecordTrack::appendDumpHeader(result);
6585 for (size_t i = 0; i < mTracks.size(); ++i) {
6586 sp<RecordTrack> track = mTracks[i];
6587 if (track != 0) {
6588 track->dump(buffer, SIZE);
6589 result.append(buffer);
6590 }
6591 }
6592
6593 if (mActiveTrack != 0) {
6594 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
6595 result.append(buffer);
6596 RecordTrack::appendDumpHeader(result);
6597 mActiveTrack->dump(buffer, SIZE);
6598 result.append(buffer);
6599
6600 }
6601 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006602}
6603
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006604// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006605status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006606{
6607 size_t framesReq = buffer->frameCount;
6608 size_t framesReady = mFrameCount - mRsmpInIndex;
6609 int channelCount;
6610
6611 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006612 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Jean-Michel Trivi4362f532012-09-13 11:44:00 -07006613 if (mBytesRead <= 0) {
6614 if ((mBytesRead < 0) && (mActiveTrack->mState == TrackBase::ACTIVE)) {
6615 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006616 // Force input into standby so that it tries to
6617 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006618 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006619 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006620 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006621 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006622 buffer->frameCount = 0;
6623 return NOT_ENOUGH_DATA;
6624 }
6625 mRsmpInIndex = 0;
6626 framesReady = mFrameCount;
6627 }
6628
6629 if (framesReq > framesReady) {
6630 framesReq = framesReady;
6631 }
6632
6633 if (mChannelCount == 1 && mReqChannelCount == 2) {
6634 channelCount = 1;
6635 } else {
6636 channelCount = 2;
6637 }
6638 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6639 buffer->frameCount = framesReq;
6640 return NO_ERROR;
6641}
6642
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006643// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006644void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6645{
6646 mRsmpInIndex += buffer->frameCount;
6647 buffer->frameCount = 0;
6648}
6649
6650bool AudioFlinger::RecordThread::checkForNewParameters_l()
6651{
6652 bool reconfig = false;
6653
6654 while (!mNewParameters.isEmpty()) {
6655 status_t status = NO_ERROR;
6656 String8 keyValuePair = mNewParameters[0];
6657 AudioParameter param = AudioParameter(keyValuePair);
6658 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006659 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006660 int reqSamplingRate = mReqSampleRate;
6661 int reqChannelCount = mReqChannelCount;
6662
6663 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6664 reqSamplingRate = value;
6665 reconfig = true;
6666 }
6667 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006668 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006669 reconfig = true;
6670 }
6671 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006672 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006673 reconfig = true;
6674 }
6675 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6676 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006677 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006678 // if frame count is changed after track creation
6679 if (mActiveTrack != 0) {
6680 status = INVALID_OPERATION;
6681 } else {
6682 reconfig = true;
6683 }
6684 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006685 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6686 // forward device change to effects that have requested to be
6687 // aware of attached audio device.
6688 for (size_t i = 0; i < mEffectChains.size(); i++) {
6689 mEffectChains[i]->setDevice_l(value);
6690 }
Eric Laurentf1c04f92012-08-28 14:26:53 -07006691
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006692 // store input device and output device but do not forward output device to audio HAL.
6693 // Note that status is ignored by the caller for output device
6694 // (see AudioFlinger::setParameters()
Eric Laurentf1c04f92012-08-28 14:26:53 -07006695 if (audio_is_output_devices(value)) {
6696 mOutDevice = value;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006697 status = BAD_VALUE;
6698 } else {
Eric Laurentf1c04f92012-08-28 14:26:53 -07006699 mInDevice = value;
Glenn Kasten85ab62c2012-11-01 11:11:38 -07006700 // disable AEC and NS if the device is a BT SCO headset supporting those
6701 // pre processings
Glenn Kasten510a3d62012-07-16 14:24:34 -07006702 if (mTracks.size() > 0) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07006703 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6704 mAudioFlinger->btNrecIsOff();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006705 for (size_t i = 0; i < mTracks.size(); i++) {
6706 sp<RecordTrack> track = mTracks[i];
6707 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6708 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6709 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07006710 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006711 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006712 }
Eric Laurent57b2dd12012-08-31 17:44:06 -07006713 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
6714 mAudioSource != (audio_source_t)value) {
6715 // forward device change to effects that have requested to be
6716 // aware of attached audio device.
6717 for (size_t i = 0; i < mEffectChains.size(); i++) {
6718 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
6719 }
6720 mAudioSource = (audio_source_t)value;
6721 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006722 if (status == NO_ERROR) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07006723 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6724 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006725 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006726 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006727 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6728 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006729 }
6730 if (reconfig) {
6731 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006732 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006733 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Glenn Kasten85ab62c2012-11-01 11:11:38 -07006734 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common)
6735 <= (2 * reqSamplingRate)) &&
6736 popcount(mInput->stream->common.get_channels(&mInput->stream->common))
6737 <= FCC_2 &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006738 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006739 status = NO_ERROR;
6740 }
6741 if (status == NO_ERROR) {
6742 readInputParameters();
Eric Laurent896adcd2012-09-13 11:18:23 -07006743 sendIoConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006744 }
6745 }
6746 }
6747
6748 mNewParameters.removeAt(0);
6749
6750 mParamStatus = status;
6751 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006752 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6753 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006754 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006755 }
6756 return reconfig;
6757}
6758
6759String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6760{
Dima Zavinfce7a472011-04-19 22:30:36 -07006761 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006762 String8 out_s8 = String8();
6763
6764 Mutex::Autolock _l(mLock);
6765 if (initCheck() != NO_ERROR) {
6766 return out_s8;
6767 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006768
Dima Zavin799a70e2011-04-18 16:57:27 -07006769 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006770 out_s8 = String8(s);
6771 free(s);
6772 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006773}
6774
6775void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6776 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006777 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006778
6779 switch (event) {
6780 case AudioSystem::INPUT_OPENED:
6781 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006782 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006783 desc.samplingRate = mSampleRate;
6784 desc.format = mFormat;
6785 desc.frameCount = mFrameCount;
6786 desc.latency = 0;
6787 param2 = &desc;
6788 break;
6789
6790 case AudioSystem::INPUT_CLOSED:
6791 default:
6792 break;
6793 }
6794 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6795}
6796
6797void AudioFlinger::RecordThread::readInputParameters()
6798{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006799 delete mRsmpInBuffer;
6800 // mRsmpInBuffer is always assigned a new[] below
6801 delete mRsmpOutBuffer;
6802 mRsmpOutBuffer = NULL;
6803 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006804 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006805
Dima Zavin799a70e2011-04-18 16:57:27 -07006806 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006807 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6808 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006809 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006810 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006811 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006812 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006813 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006814 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6815
Glenn Kasten53d76db2012-03-08 12:32:47 -08006816 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006817 {
6818 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006819 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6820 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006821 if (mChannelCount == 1 && mReqChannelCount == 2) {
6822 channelCount = 1;
6823 } else {
6824 channelCount = 2;
6825 }
6826 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6827 mResampler->setSampleRate(mSampleRate);
6828 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6829 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6830
Glenn Kasten85ab62c2012-11-01 11:11:38 -07006831 // optmization: if mono to mono, alter input frame count as if we were inputing
6832 // stereo samples
Mathias Agopian65ab4712010-07-14 17:59:35 -07006833 if (mChannelCount == 1 && mReqChannelCount == 1) {
6834 mFrameCount >>= 1;
6835 }
6836
6837 }
6838 mRsmpInIndex = mFrameCount;
6839}
6840
6841unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6842{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006843 Mutex::Autolock _l(mLock);
6844 if (initCheck() != NO_ERROR) {
6845 return 0;
6846 }
6847
Dima Zavin799a70e2011-04-18 16:57:27 -07006848 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006849}
6850
Glenn Kasten106e8a42012-08-02 13:37:12 -07006851uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006852{
6853 Mutex::Autolock _l(mLock);
6854 uint32_t result = 0;
6855 if (getEffectChain_l(sessionId) != 0) {
6856 result = EFFECT_SESSION;
6857 }
6858
Glenn Kasten510a3d62012-07-16 14:24:34 -07006859 for (size_t i = 0; i < mTracks.size(); ++i) {
6860 if (sessionId == mTracks[i]->sessionId()) {
6861 result |= TRACK_SESSION;
6862 break;
6863 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006864 }
6865
6866 return result;
6867}
6868
Glenn Kasten106e8a42012-08-02 13:37:12 -07006869KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent59bd0da2011-08-01 09:52:20 -07006870{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006871 KeyedVector<int, bool> ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006872 Mutex::Autolock _l(mLock);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006873 for (size_t j = 0; j < mTracks.size(); ++j) {
6874 sp<RecordThread::RecordTrack> track = mTracks[j];
6875 int sessionId = track->sessionId();
6876 if (ids.indexOfKey(sessionId) < 0) {
6877 ids.add(sessionId, true);
6878 }
6879 }
6880 return ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006881}
6882
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006883AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6884{
6885 Mutex::Autolock _l(mLock);
6886 AudioStreamIn *input = mInput;
6887 mInput = NULL;
6888 return input;
6889}
6890
6891// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006892audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006893{
6894 if (mInput == NULL) {
6895 return NULL;
6896 }
6897 return &mInput->stream->common;
6898}
6899
6900
Mathias Agopian65ab4712010-07-14 17:59:35 -07006901// ----------------------------------------------------------------------------
6902
Eric Laurenta4c5a552012-03-29 10:12:40 -07006903audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6904{
6905 if (!settingsAllowed()) {
6906 return 0;
6907 }
6908 Mutex::Autolock _l(mLock);
6909 return loadHwModule_l(name);
6910}
6911
6912// loadHwModule_l() must be called with AudioFlinger::mLock held
6913audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6914{
6915 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6916 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6917 ALOGW("loadHwModule() module %s already loaded", name);
6918 return mAudioHwDevs.keyAt(i);
6919 }
6920 }
6921
Eric Laurenta4c5a552012-03-29 10:12:40 -07006922 audio_hw_device_t *dev;
6923
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006924 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006925 if (rc) {
6926 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6927 return 0;
6928 }
6929
6930 mHardwareStatus = AUDIO_HW_INIT;
6931 rc = dev->init_check(dev);
6932 mHardwareStatus = AUDIO_HW_IDLE;
6933 if (rc) {
6934 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6935 return 0;
6936 }
6937
John Grossmanee578c02012-07-23 17:05:46 -07006938 // Check and cache this HAL's level of support for master mute and master
6939 // volume. If this is the first HAL opened, and it supports the get
6940 // methods, use the initial values provided by the HAL as the current
6941 // master mute and volume settings.
6942
6943 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
6944 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07006945 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07006946
6947 if (0 == mAudioHwDevs.size()) {
6948 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6949 if (NULL != dev->get_master_volume) {
6950 float mv;
6951 if (OK == dev->get_master_volume(dev, &mv)) {
6952 mMasterVolume = mv;
6953 }
6954 }
6955
6956 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
6957 if (NULL != dev->get_master_mute) {
6958 bool mm;
6959 if (OK == dev->get_master_mute(dev, &mm)) {
6960 mMasterMute = mm;
6961 }
6962 }
6963 }
6964
Eric Laurenta4c5a552012-03-29 10:12:40 -07006965 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07006966 if ((NULL != dev->set_master_volume) &&
6967 (OK == dev->set_master_volume(dev, mMasterVolume))) {
6968 flags = static_cast<AudioHwDevice::Flags>(flags |
6969 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
6970 }
6971
6972 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
6973 if ((NULL != dev->set_master_mute) &&
6974 (OK == dev->set_master_mute(dev, mMasterMute))) {
6975 flags = static_cast<AudioHwDevice::Flags>(flags |
6976 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
6977 }
6978
Eric Laurenta4c5a552012-03-29 10:12:40 -07006979 mHardwareStatus = AUDIO_HW_IDLE;
6980 }
6981
6982 audio_module_handle_t handle = nextUniqueId();
John Grossmanee578c02012-07-23 17:05:46 -07006983 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07006984
6985 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006986 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006987
6988 return handle;
6989
6990}
6991
Glenn Kastencc0f1cf2012-09-24 11:27:18 -07006992// ----------------------------------------------------------------------------
6993
6994int32_t AudioFlinger::getPrimaryOutputSamplingRate()
6995{
6996 Mutex::Autolock _l(mLock);
6997 PlaybackThread *thread = primaryPlaybackThread_l();
6998 return thread != NULL ? thread->sampleRate() : 0;
6999}
7000
7001int32_t AudioFlinger::getPrimaryOutputFrameCount()
7002{
7003 Mutex::Autolock _l(mLock);
7004 PlaybackThread *thread = primaryPlaybackThread_l();
7005 return thread != NULL ? thread->frameCountHAL() : 0;
7006}
7007
7008// ----------------------------------------------------------------------------
7009
Eric Laurenta4c5a552012-03-29 10:12:40 -07007010audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
7011 audio_devices_t *pDevices,
7012 uint32_t *pSamplingRate,
7013 audio_format_t *pFormat,
7014 audio_channel_mask_t *pChannelMask,
7015 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007016 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007017{
7018 status_t status;
7019 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007020 struct audio_config config = {
7021 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7022 channel_mask: pChannelMask ? *pChannelMask : 0,
7023 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7024 };
7025 audio_stream_out_t *outStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007026 AudioHwDevice *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007027
Eric Laurenta4c5a552012-03-29 10:12:40 -07007028 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
7029 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007030 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007031 config.sample_rate,
7032 config.format,
7033 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07007034 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007035
7036 if (pDevices == NULL || *pDevices == 0) {
7037 return 0;
7038 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007039
Mathias Agopian65ab4712010-07-14 17:59:35 -07007040 Mutex::Autolock _l(mLock);
7041
Eric Laurenta4c5a552012-03-29 10:12:40 -07007042 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007043 if (outHwDev == NULL)
7044 return 0;
7045
John Grossmanee578c02012-07-23 17:05:46 -07007046 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007047 audio_io_handle_t id = nextUniqueId();
7048
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007049 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007050
John Grossmanee578c02012-07-23 17:05:46 -07007051 status = hwDevHal->open_output_stream(hwDevHal,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007052 id,
7053 *pDevices,
7054 (audio_output_flags_t)flags,
7055 &config,
7056 &outStream);
7057
Glenn Kasten8abf44d2012-02-02 14:16:03 -08007058 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten85ab62c2012-11-01 11:11:38 -07007059 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, "
7060 "Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007061 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007062 config.sample_rate,
7063 config.format,
7064 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007065 status);
7066
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007067 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007068 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007069
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007070 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007071 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
7072 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007073 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007074 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007075 } else {
7076 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01007077 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007078 }
7079 mPlaybackThreads.add(id, thread);
7080
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007081 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
7082 if (pFormat != NULL) *pFormat = config.format;
7083 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08007084 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007085
7086 // notify client processes of the new output creation
7087 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007088
7089 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07007090 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07007091 ALOGI("Using module %d has the primary audio interface", module);
7092 mPrimaryHardwareDev = outHwDev;
7093
7094 AutoMutex lock(mHardwareLock);
7095 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -07007096 hwDevHal->set_mode(hwDevHal, mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007097 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007098 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007099 return id;
7100 }
7101
7102 return 0;
7103}
7104
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007105audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
7106 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007107{
7108 Mutex::Autolock _l(mLock);
7109 MixerThread *thread1 = checkMixerThread_l(output1);
7110 MixerThread *thread2 = checkMixerThread_l(output2);
7111
7112 if (thread1 == NULL || thread2 == NULL) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07007113 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1,
7114 output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007115 return 0;
7116 }
7117
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007118 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007119 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
7120 thread->addOutputTrack(thread2);
7121 mPlaybackThreads.add(id, thread);
7122 // notify client processes of the new output creation
7123 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
7124 return id;
7125}
7126
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007127status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007128{
Glenn Kastend96c5722012-04-25 13:44:49 -07007129 return closeOutput_nonvirtual(output);
7130}
7131
7132status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
7133{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007134 // keep strong reference on the playback thread so that
7135 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007136 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007137 {
7138 Mutex::Autolock _l(mLock);
7139 thread = checkPlaybackThread_l(output);
7140 if (thread == NULL) {
7141 return BAD_VALUE;
7142 }
7143
Steve Block3856b092011-10-20 11:56:00 +01007144 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007145
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007146 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007147 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007148 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07007149 DuplicatingThread *dupThread =
7150 (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007151 dupThread->removeOutputTrack((MixerThread *)thread.get());
7152 }
7153 }
7154 }
Glenn Kastena1117922012-01-26 10:53:32 -08007155 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007156 mPlaybackThreads.removeItem(output);
7157 }
7158 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007159 // The thread entity (active unit of execution) is no longer running here,
7160 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007161
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007162 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007163 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007164 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007165 // from now on thread->mOutput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007166 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007167 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007168 }
7169 return NO_ERROR;
7170}
7171
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007172status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007173{
7174 Mutex::Autolock _l(mLock);
7175 PlaybackThread *thread = checkPlaybackThread_l(output);
7176
7177 if (thread == NULL) {
7178 return BAD_VALUE;
7179 }
7180
Steve Block3856b092011-10-20 11:56:00 +01007181 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007182 thread->suspend();
7183
7184 return NO_ERROR;
7185}
7186
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007187status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007188{
7189 Mutex::Autolock _l(mLock);
7190 PlaybackThread *thread = checkPlaybackThread_l(output);
7191
7192 if (thread == NULL) {
7193 return BAD_VALUE;
7194 }
7195
Steve Block3856b092011-10-20 11:56:00 +01007196 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007197
7198 thread->restore();
7199
7200 return NO_ERROR;
7201}
7202
Eric Laurenta4c5a552012-03-29 10:12:40 -07007203audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
7204 audio_devices_t *pDevices,
7205 uint32_t *pSamplingRate,
7206 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07007207 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007208{
7209 status_t status;
7210 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007211 struct audio_config config = {
7212 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7213 channel_mask: pChannelMask ? *pChannelMask : 0,
7214 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7215 };
7216 uint32_t reqSamplingRate = config.sample_rate;
7217 audio_format_t reqFormat = config.format;
7218 audio_channel_mask_t reqChannels = config.channel_mask;
7219 audio_stream_in_t *inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007220 AudioHwDevice *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007221
7222 if (pDevices == NULL || *pDevices == 0) {
7223 return 0;
7224 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007225
Mathias Agopian65ab4712010-07-14 17:59:35 -07007226 Mutex::Autolock _l(mLock);
7227
Eric Laurenta4c5a552012-03-29 10:12:40 -07007228 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007229 if (inHwDev == NULL)
7230 return 0;
7231
John Grossmanee578c02012-07-23 17:05:46 -07007232 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007233 audio_io_handle_t id = nextUniqueId();
7234
John Grossmanee578c02012-07-23 17:05:46 -07007235 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007236 &inStream);
Glenn Kasten85ab62c2012-11-01 11:11:38 -07007237 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, "
7238 "status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007239 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007240 config.sample_rate,
7241 config.format,
7242 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007243 status);
7244
Glenn Kasten85ab62c2012-11-01 11:11:38 -07007245 // If the input could not be opened with the requested parameters and we can handle the
7246 // conversion internally, try to open again with the proposed parameters. The AudioFlinger can
7247 // resample the input and do mono to stereo or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007248 if (status == BAD_VALUE &&
7249 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7250 (config.sample_rate <= 2 * reqSamplingRate) &&
7251 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007252 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007253 inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007254 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007255 }
7256
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007257 if (status == NO_ERROR && inStream != NULL) {
Glenn Kastend06785b2012-09-30 12:29:28 -07007258
7259 // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,
7260 // or (re-)create if current Pipe is idle and does not match the new format
7261 sp<NBAIO_Sink> teeSink;
7262#ifdef TEE_SINK_INPUT_FRAMES
7263 enum {
7264 TEE_SINK_NO, // don't copy input
7265 TEE_SINK_NEW, // copy input using a new pipe
7266 TEE_SINK_OLD, // copy input using an existing pipe
7267 } kind;
7268 NBAIO_Format format = Format_from_SR_C(inStream->common.get_sample_rate(&inStream->common),
7269 popcount(inStream->common.get_channels(&inStream->common)));
7270 if (format == Format_Invalid) {
7271 kind = TEE_SINK_NO;
7272 } else if (mRecordTeeSink == 0) {
7273 kind = TEE_SINK_NEW;
7274 } else if (mRecordTeeSink->getStrongCount() != 1) {
7275 kind = TEE_SINK_NO;
7276 } else if (format == mRecordTeeSink->format()) {
7277 kind = TEE_SINK_OLD;
7278 } else {
7279 kind = TEE_SINK_NEW;
7280 }
7281 switch (kind) {
7282 case TEE_SINK_NEW: {
7283 Pipe *pipe = new Pipe(TEE_SINK_INPUT_FRAMES, format);
7284 size_t numCounterOffers = 0;
7285 const NBAIO_Format offers[1] = {format};
7286 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7287 ALOG_ASSERT(index == 0);
7288 PipeReader *pipeReader = new PipeReader(*pipe);
7289 numCounterOffers = 0;
7290 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7291 ALOG_ASSERT(index == 0);
7292 mRecordTeeSink = pipe;
7293 mRecordTeeSource = pipeReader;
7294 teeSink = pipe;
7295 }
7296 break;
7297 case TEE_SINK_OLD:
7298 teeSink = mRecordTeeSink;
7299 break;
7300 case TEE_SINK_NO:
7301 default:
7302 break;
7303 }
7304#endif
Dima Zavin799a70e2011-04-18 16:57:27 -07007305 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7306
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007307 // Start record thread
7308 // RecorThread require both input and output device indication to forward to audio
7309 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007310 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Glenn Kastend06785b2012-09-30 12:29:28 -07007311
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007312 thread = new RecordThread(this,
7313 input,
7314 reqSamplingRate,
7315 reqChannels,
7316 id,
Glenn Kastend06785b2012-09-30 12:29:28 -07007317 device, teeSink);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007318 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007319 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007320 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007321 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007322 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007323
Mathias Agopian65ab4712010-07-14 17:59:35 -07007324 // notify client processes of the new input creation
7325 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7326 return id;
7327 }
7328
7329 return 0;
7330}
7331
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007332status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007333{
Glenn Kastend96c5722012-04-25 13:44:49 -07007334 return closeInput_nonvirtual(input);
7335}
7336
7337status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7338{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007339 // keep strong reference on the record thread so that
7340 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007341 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007342 {
7343 Mutex::Autolock _l(mLock);
7344 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007345 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007346 return BAD_VALUE;
7347 }
7348
Steve Block3856b092011-10-20 11:56:00 +01007349 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007350 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007351 mRecordThreads.removeItem(input);
7352 }
7353 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007354 // The thread entity (active unit of execution) is no longer running here,
7355 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007356
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007357 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007358 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007359 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007360 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007361 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007362
7363 return NO_ERROR;
7364}
7365
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007366status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007367{
7368 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007369 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007370
7371 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7372 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007373 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007374 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007375
7376 return NO_ERROR;
7377}
7378
7379
7380int AudioFlinger::newAudioSessionId()
7381{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007382 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007383}
7384
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007385void AudioFlinger::acquireAudioSessionId(int audioSession)
7386{
7387 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007388 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007389 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007390 size_t num = mAudioSessionRefs.size();
7391 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007392 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007393 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7394 ref->mCnt++;
7395 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007396 return;
7397 }
7398 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007399 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7400 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007401}
7402
7403void AudioFlinger::releaseAudioSessionId(int audioSession)
7404{
7405 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007406 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007407 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007408 size_t num = mAudioSessionRefs.size();
7409 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007410 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007411 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7412 ref->mCnt--;
7413 ALOGV(" decremented refcount to %d", ref->mCnt);
7414 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007415 mAudioSessionRefs.removeAt(i);
7416 delete ref;
7417 purgeStaleEffects_l();
7418 }
7419 return;
7420 }
7421 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007422 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007423}
7424
7425void AudioFlinger::purgeStaleEffects_l() {
7426
Steve Block3856b092011-10-20 11:56:00 +01007427 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007428
7429 Vector< sp<EffectChain> > chains;
7430
7431 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7432 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7433 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7434 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007435 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7436 chains.push(ec);
7437 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007438 }
7439 }
7440 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7441 sp<RecordThread> t = mRecordThreads.valueAt(i);
7442 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7443 sp<EffectChain> ec = t->mEffectChains[j];
7444 chains.push(ec);
7445 }
7446 }
7447
7448 for (size_t i = 0; i < chains.size(); i++) {
7449 sp<EffectChain> ec = chains[i];
7450 int sessionid = ec->sessionId();
7451 sp<ThreadBase> t = ec->mThread.promote();
7452 if (t == 0) {
7453 continue;
7454 }
7455 size_t numsessionrefs = mAudioSessionRefs.size();
7456 bool found = false;
7457 for (size_t k = 0; k < numsessionrefs; k++) {
7458 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007459 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007460 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007461 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007462 found = true;
7463 break;
7464 }
7465 }
7466 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007467 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007468 // remove all effects from the chain
7469 while (ec->mEffects.size()) {
7470 sp<EffectModule> effect = ec->mEffects[0];
7471 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007472 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007473 if (effect->purgeHandles()) {
7474 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007475 }
7476 AudioSystem::unregisterEffect(effect->id());
7477 }
7478 }
7479 }
7480 return;
7481}
7482
Mathias Agopian65ab4712010-07-14 17:59:35 -07007483// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007484AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007485{
Glenn Kastena1117922012-01-26 10:53:32 -08007486 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007487}
7488
7489// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007490AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007491{
7492 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007493 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007494}
7495
7496// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007497AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007498{
Glenn Kastena1117922012-01-26 10:53:32 -08007499 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007500}
7501
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007502uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007503{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007504 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007505}
7506
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007507AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007508{
7509 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7510 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007511 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07007512 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007513 return thread;
7514 }
7515 }
7516 return NULL;
7517}
7518
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007519audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007520{
7521 PlaybackThread *thread = primaryPlaybackThread_l();
7522
7523 if (thread == NULL) {
7524 return 0;
7525 }
7526
Eric Laurentf1c04f92012-08-28 14:26:53 -07007527 return thread->outDevice();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007528}
7529
Eric Laurenta011e352012-03-29 15:51:43 -07007530sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7531 int triggerSession,
7532 int listenerSession,
7533 sync_event_callback_t callBack,
7534 void *cookie)
7535{
7536 Mutex::Autolock _l(mLock);
7537
7538 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7539 status_t playStatus = NAME_NOT_FOUND;
7540 status_t recStatus = NAME_NOT_FOUND;
7541 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7542 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7543 if (playStatus == NO_ERROR) {
7544 return event;
7545 }
7546 }
7547 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7548 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7549 if (recStatus == NO_ERROR) {
7550 return event;
7551 }
7552 }
7553 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7554 mPendingSyncEvents.add(event);
7555 } else {
7556 ALOGV("createSyncEvent() invalid event %d", event->type());
7557 event.clear();
7558 }
7559 return event;
7560}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007561
Mathias Agopian65ab4712010-07-14 17:59:35 -07007562// ----------------------------------------------------------------------------
7563// Effect management
7564// ----------------------------------------------------------------------------
7565
7566
Glenn Kastenf587ba52012-01-26 16:25:10 -08007567status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007568{
7569 Mutex::Autolock _l(mLock);
7570 return EffectQueryNumberEffects(numEffects);
7571}
7572
Glenn Kastenf587ba52012-01-26 16:25:10 -08007573status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007574{
7575 Mutex::Autolock _l(mLock);
7576 return EffectQueryEffect(index, descriptor);
7577}
7578
Glenn Kasten5e92a782012-01-30 07:40:52 -08007579status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007580 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007581{
7582 Mutex::Autolock _l(mLock);
7583 return EffectGetDescriptor(pUuid, descriptor);
7584}
7585
7586
Mathias Agopian65ab4712010-07-14 17:59:35 -07007587sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7588 effect_descriptor_t *pDesc,
7589 const sp<IEffectClient>& effectClient,
7590 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007591 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007592 int sessionId,
7593 status_t *status,
7594 int *id,
7595 int *enabled)
7596{
7597 status_t lStatus = NO_ERROR;
7598 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007599 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007600
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007601 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007602 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007603
7604 if (pDesc == NULL) {
7605 lStatus = BAD_VALUE;
7606 goto Exit;
7607 }
7608
Eric Laurent84e9a102010-09-23 16:10:16 -07007609 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007610 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007611 lStatus = PERMISSION_DENIED;
7612 goto Exit;
7613 }
7614
Dima Zavinfce7a472011-04-19 22:30:36 -07007615 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007616 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007617 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007618 lStatus = PERMISSION_DENIED;
7619 goto Exit;
7620 }
7621
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007622 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007623 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007624 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007625 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007626 lStatus = BAD_VALUE;
7627 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007628 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007629 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007630 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007631 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007632 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007633 }
7634 }
7635
Mathias Agopian65ab4712010-07-14 17:59:35 -07007636 {
7637 Mutex::Autolock _l(mLock);
7638
Mathias Agopian65ab4712010-07-14 17:59:35 -07007639
7640 if (!EffectIsNullUuid(&pDesc->uuid)) {
7641 // if uuid is specified, request effect descriptor
7642 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7643 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007644 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007645 goto Exit;
7646 }
7647 } else {
7648 // if uuid is not specified, look for an available implementation
7649 // of the required type in effect factory
7650 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007651 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007652 lStatus = BAD_VALUE;
7653 goto Exit;
7654 }
7655 uint32_t numEffects = 0;
7656 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007657 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007658 bool found = false;
7659
7660 lStatus = EffectQueryNumberEffects(&numEffects);
7661 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007662 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007663 goto Exit;
7664 }
7665 for (uint32_t i = 0; i < numEffects; i++) {
7666 lStatus = EffectQueryEffect(i, &desc);
7667 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007668 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007669 continue;
7670 }
7671 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7672 // If matching type found save effect descriptor. If the session is
7673 // 0 and the effect is not auxiliary, continue enumeration in case
7674 // an auxiliary version of this effect type is available
7675 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08007676 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07007677 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007678 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7679 break;
7680 }
7681 }
7682 }
7683 if (!found) {
7684 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007685 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007686 goto Exit;
7687 }
7688 // For same effect type, chose auxiliary version over insert version if
7689 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007690 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007691 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08007692 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007693 }
7694 }
7695
7696 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007697 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007698 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7699 lStatus = INVALID_OPERATION;
7700 goto Exit;
7701 }
7702
Eric Laurent59255e42011-07-27 19:49:51 -07007703 // check recording permission for visualizer
7704 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7705 !recordingAllowed()) {
7706 lStatus = PERMISSION_DENIED;
7707 goto Exit;
7708 }
7709
Mathias Agopian65ab4712010-07-14 17:59:35 -07007710 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08007711 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007712
7713 // If output is not specified try to find a matching audio session ID in one of the
7714 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007715 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7716 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007717 // Note: io is never 0 when creating an effect on an input
7718 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007719 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007720 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7721 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007722 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007723 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007724 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007725 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007726 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007727 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7728 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7729 io = mRecordThreads.keyAt(i);
7730 break;
7731 }
7732 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007733 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007734 // If no output thread contains the requested session ID, default to
7735 // first output. The effect chain will be moved to the correct output
7736 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007737 if (io == 0 && mPlaybackThreads.size()) {
7738 io = mPlaybackThreads.keyAt(0);
7739 }
Steve Block3856b092011-10-20 11:56:00 +01007740 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007741 }
7742 ThreadBase *thread = checkRecordThread_l(io);
7743 if (thread == NULL) {
7744 thread = checkPlaybackThread_l(io);
7745 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007746 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007747 lStatus = BAD_VALUE;
7748 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007749 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007750 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007751
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007752 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007753
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007754 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007755 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7756 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007757 if (handle != 0 && id != NULL) {
7758 *id = handle->id();
7759 }
7760 }
7761
7762Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007763 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007764 *status = lStatus;
7765 }
7766 return handle;
7767}
7768
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007769status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7770 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007771{
Steve Block3856b092011-10-20 11:56:00 +01007772 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007773 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007774 Mutex::Autolock _l(mLock);
7775 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007776 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007777 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007778 }
Eric Laurentde070132010-07-13 04:45:46 -07007779 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7780 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007781 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007782 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007783 }
Eric Laurentde070132010-07-13 04:45:46 -07007784 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7785 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007786 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007787 return BAD_VALUE;
7788 }
7789
7790 Mutex::Autolock _dl(dstThread->mLock);
7791 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007792 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007793
Mathias Agopian65ab4712010-07-14 17:59:35 -07007794 return NO_ERROR;
7795}
7796
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007797// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007798status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007799 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007800 AudioFlinger::PlaybackThread *dstThread,
7801 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007802{
Steve Block3856b092011-10-20 11:56:00 +01007803 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007804 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007805
Eric Laurent59255e42011-07-27 19:49:51 -07007806 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007807 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007808 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007809 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007810 return INVALID_OPERATION;
7811 }
7812
Eric Laurent39e94f82010-07-28 01:32:47 -07007813 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007814 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007815 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007816 // removed.
7817 srcThread->removeEffectChain_l(chain);
7818
7819 // transfer all effects one by one so that new effect chain is created on new thread with
7820 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007821 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007822 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007823 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007824 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7825 while (effect != 0) {
7826 srcThread->removeEffect_l(effect);
7827 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007828 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7829 if (effect->state() == EffectModule::ACTIVE ||
7830 effect->state() == EffectModule::STOPPING) {
7831 effect->start();
7832 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007833 // if the move request is not received from audio policy manager, the effect must be
7834 // re-registered with the new strategy and output
7835 if (dstChain == 0) {
7836 dstChain = effect->chain().promote();
7837 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007838 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007839 srcThread->addEffect_l(effect);
7840 return NO_INIT;
7841 }
7842 strategy = dstChain->strategy();
7843 }
7844 if (reRegister) {
7845 AudioSystem::unregisterEffect(effect->id());
7846 AudioSystem::registerEffect(&effect->desc(),
7847 dstOutput,
7848 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007849 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007850 effect->id());
7851 }
Eric Laurentde070132010-07-13 04:45:46 -07007852 effect = chain->getEffectFromId_l(0);
7853 }
7854
7855 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007856}
7857
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007858
Mathias Agopian65ab4712010-07-14 17:59:35 -07007859// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007860sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007861 const sp<AudioFlinger::Client>& client,
7862 const sp<IEffectClient>& effectClient,
7863 int32_t priority,
7864 int sessionId,
7865 effect_descriptor_t *desc,
7866 int *enabled,
7867 status_t *status
7868 )
7869{
7870 sp<EffectModule> effect;
7871 sp<EffectHandle> handle;
7872 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007873 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007874 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007875 bool effectCreated = false;
7876 bool effectRegistered = false;
7877
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007878 lStatus = initCheck();
7879 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007880 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007881 goto Exit;
7882 }
7883
7884 // Do not allow effects with session ID 0 on direct output or duplicating threads
7885 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007886 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007887 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007888 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007889 lStatus = BAD_VALUE;
7890 goto Exit;
7891 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007892 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007893 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007894 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007895 desc->name, desc->flags, mType);
7896 lStatus = BAD_VALUE;
7897 goto Exit;
7898 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007899
Steve Block3856b092011-10-20 11:56:00 +01007900 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007901
7902 { // scope for mLock
7903 Mutex::Autolock _l(mLock);
7904
7905 // check for existing effect chain with the requested audio session
7906 chain = getEffectChain_l(sessionId);
7907 if (chain == 0) {
7908 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007909 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007910 chain = new EffectChain(this, sessionId);
7911 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007912 chain->setStrategy(getStrategyForSession_l(sessionId));
7913 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007914 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007915 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007916 }
7917
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007918 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007919
7920 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007921 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007922 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007923 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007924 if (lStatus != NO_ERROR) {
7925 goto Exit;
7926 }
7927 effectRegistered = true;
7928 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007929 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007930 lStatus = effect->status();
7931 if (lStatus != NO_ERROR) {
7932 goto Exit;
7933 }
Eric Laurentcab11242010-07-15 12:50:15 -07007934 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007935 if (lStatus != NO_ERROR) {
7936 goto Exit;
7937 }
7938 effectCreated = true;
7939
Eric Laurentf1c04f92012-08-28 14:26:53 -07007940 effect->setDevice(mOutDevice);
7941 effect->setDevice(mInDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007942 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07007943 effect->setAudioSource(mAudioSource);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007944 }
7945 // create effect handle and connect it to effect module
7946 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007947 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007948 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007949 *enabled = (int)effect->isEnabled();
7950 }
7951 }
7952
7953Exit:
7954 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007955 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007956 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007957 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007958 }
7959 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007960 AudioSystem::unregisterEffect(effect->id());
7961 }
7962 if (chainCreated) {
7963 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007964 }
7965 handle.clear();
7966 }
7967
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007968 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007969 *status = lStatus;
7970 }
7971 return handle;
7972}
7973
Eric Laurent717e1282012-06-29 16:36:52 -07007974sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7975{
7976 Mutex::Autolock _l(mLock);
7977 return getEffect_l(sessionId, effectId);
7978}
7979
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007980sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7981{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007982 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007983 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007984}
7985
Eric Laurentde070132010-07-13 04:45:46 -07007986// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7987// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007988status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007989{
7990 // check for existing effect chain with the requested audio session
7991 int sessionId = effect->sessionId();
7992 sp<EffectChain> chain = getEffectChain_l(sessionId);
7993 bool chainCreated = false;
7994
7995 if (chain == 0) {
7996 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007997 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007998 chain = new EffectChain(this, sessionId);
7999 addEffectChain_l(chain);
8000 chain->setStrategy(getStrategyForSession_l(sessionId));
8001 chainCreated = true;
8002 }
Steve Block3856b092011-10-20 11:56:00 +01008003 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07008004
8005 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008006 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07008007 this, effect->desc().name, chain.get());
8008 return BAD_VALUE;
8009 }
8010
8011 status_t status = chain->addEffect_l(effect);
8012 if (status != NO_ERROR) {
8013 if (chainCreated) {
8014 removeEffectChain_l(chain);
8015 }
8016 return status;
8017 }
8018
Eric Laurentf1c04f92012-08-28 14:26:53 -07008019 effect->setDevice(mOutDevice);
8020 effect->setDevice(mInDevice);
Eric Laurentde070132010-07-13 04:45:46 -07008021 effect->setMode(mAudioFlinger->getMode());
Eric Laurent57b2dd12012-08-31 17:44:06 -07008022 effect->setAudioSource(mAudioSource);
Eric Laurentde070132010-07-13 04:45:46 -07008023 return NO_ERROR;
8024}
8025
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008026void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07008027
Steve Block3856b092011-10-20 11:56:00 +01008028 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008029 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07008030 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8031 detachAuxEffect_l(effect->id());
8032 }
8033
8034 sp<EffectChain> chain = effect->chain().promote();
8035 if (chain != 0) {
8036 // remove effect chain if removing last effect
8037 if (chain->removeEffect_l(effect) == 0) {
8038 removeEffectChain_l(chain);
8039 }
8040 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00008041 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07008042 }
8043}
8044
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008045void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008046 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008047{
8048 effectChains = mEffectChains;
8049 for (size_t i = 0; i < mEffectChains.size(); i++) {
8050 mEffectChains[i]->lock();
8051 }
8052}
8053
8054void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008055 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008056{
8057 for (size_t i = 0; i < effectChains.size(); i++) {
8058 effectChains[i]->unlock();
8059 }
8060}
8061
8062sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
8063{
8064 Mutex::Autolock _l(mLock);
8065 return getEffectChain_l(sessionId);
8066}
8067
Glenn Kasten106e8a42012-08-02 13:37:12 -07008068sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008069{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008070 size_t size = mEffectChains.size();
8071 for (size_t i = 0; i < size; i++) {
8072 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08008073 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008074 }
8075 }
Glenn Kasten090f0192012-01-30 13:00:02 -08008076 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008077}
8078
Glenn Kastenf78aee72012-01-04 11:00:47 -08008079void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008080{
8081 Mutex::Autolock _l(mLock);
8082 size_t size = mEffectChains.size();
8083 for (size_t i = 0; i < size; i++) {
8084 mEffectChains[i]->setMode_l(mode);
8085 }
8086}
8087
8088void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008089 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08008090 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07008091
Mathias Agopian65ab4712010-07-14 17:59:35 -07008092 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008093 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008094 // delete the effect module if removing last handle on it
8095 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008096 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008097 removeEffect_l(effect);
8098 AudioSystem::unregisterEffect(effect->id());
8099 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008100 }
8101}
8102
8103status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
8104{
8105 int session = chain->sessionId();
8106 int16_t *buffer = mMixBuffer;
8107 bool ownsBuffer = false;
8108
Steve Block3856b092011-10-20 11:56:00 +01008109 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008110 if (session > 0) {
8111 // Only one effect chain can be present in direct output thread and it uses
8112 // the mix buffer as input
8113 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07008114 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008115 buffer = new int16_t[numSamples];
8116 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01008117 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008118 ownsBuffer = true;
8119 }
8120
8121 // Attach all tracks with same session ID to this chain.
8122 for (size_t i = 0; i < mTracks.size(); ++i) {
8123 sp<Track> track = mTracks[i];
8124 if (session == track->sessionId()) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07008125 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
8126 buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008127 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008128 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008129 }
8130 }
8131
8132 // indicate all active tracks in the chain
8133 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8134 sp<Track> track = mActiveTracks[i].promote();
8135 if (track == 0) continue;
8136 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008137 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07008138 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008139 }
8140 }
8141 }
8142
8143 chain->setInBuffer(buffer, ownsBuffer);
8144 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07008145 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07008146 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07008147 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
8148 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008149 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07008150 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
8151 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07008152 // Effect chain for other sessions are inserted at beginning of effect
8153 // chains list to be processed before output mix effects. Relative order between other
8154 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07008155 size_t size = mEffectChains.size();
8156 size_t i = 0;
8157 for (i = 0; i < size; i++) {
8158 if (mEffectChains[i]->sessionId() < session) break;
8159 }
8160 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008161 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008162
8163 return NO_ERROR;
8164}
8165
8166size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
8167{
8168 int session = chain->sessionId();
8169
Steve Block3856b092011-10-20 11:56:00 +01008170 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008171
8172 for (size_t i = 0; i < mEffectChains.size(); i++) {
8173 if (chain == mEffectChains[i]) {
8174 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07008175 // detach all active tracks from the chain
8176 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
8177 sp<Track> track = mActiveTracks[i].promote();
8178 if (track == 0) continue;
8179 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01008180 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07008181 chain.get(), session);
8182 chain->decActiveTrackCnt();
8183 }
8184 }
8185
Mathias Agopian65ab4712010-07-14 17:59:35 -07008186 // detach all tracks with same session ID from this chain
8187 for (size_t i = 0; i < mTracks.size(); ++i) {
8188 sp<Track> track = mTracks[i];
8189 if (session == track->sessionId()) {
8190 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07008191 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008192 }
8193 }
Eric Laurentde070132010-07-13 04:45:46 -07008194 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008195 }
8196 }
8197 return mEffectChains.size();
8198}
8199
Eric Laurentde070132010-07-13 04:45:46 -07008200status_t AudioFlinger::PlaybackThread::attachAuxEffect(
8201 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008202{
8203 Mutex::Autolock _l(mLock);
8204 return attachAuxEffect_l(track, EffectId);
8205}
8206
Eric Laurentde070132010-07-13 04:45:46 -07008207status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
8208 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008209{
8210 status_t status = NO_ERROR;
8211
8212 if (EffectId == 0) {
8213 track->setAuxBuffer(0, NULL);
8214 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07008215 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
8216 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008217 if (effect != 0) {
8218 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8219 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
8220 } else {
8221 status = INVALID_OPERATION;
8222 }
8223 } else {
8224 status = BAD_VALUE;
8225 }
8226 }
8227 return status;
8228}
8229
8230void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
8231{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008232 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008233 sp<Track> track = mTracks[i];
8234 if (track->auxEffectId() == effectId) {
8235 attachAuxEffect_l(track, 0);
8236 }
8237 }
8238}
8239
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008240status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8241{
8242 // only one chain per input thread
8243 if (mEffectChains.size() != 0) {
8244 return INVALID_OPERATION;
8245 }
Steve Block3856b092011-10-20 11:56:00 +01008246 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008247
8248 chain->setInBuffer(NULL);
8249 chain->setOutBuffer(NULL);
8250
Eric Laurent59255e42011-07-27 19:49:51 -07008251 checkSuspendOnAddEffectChain_l(chain);
8252
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008253 mEffectChains.add(chain);
8254
8255 return NO_ERROR;
8256}
8257
8258size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8259{
Steve Block3856b092011-10-20 11:56:00 +01008260 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00008261 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008262 "removeEffectChain_l() %p invalid chain size %d on thread %p",
8263 chain.get(), mEffectChains.size(), this);
8264 if (mEffectChains.size() == 1) {
8265 mEffectChains.removeAt(0);
8266 }
8267 return 0;
8268}
8269
Mathias Agopian65ab4712010-07-14 17:59:35 -07008270// ----------------------------------------------------------------------------
8271// EffectModule implementation
8272// ----------------------------------------------------------------------------
8273
8274#undef LOG_TAG
8275#define LOG_TAG "AudioFlinger::EffectModule"
8276
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008277AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008278 const wp<AudioFlinger::EffectChain>& chain,
8279 effect_descriptor_t *desc,
8280 int id,
8281 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07008282 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
8283 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07008284 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07008285 // mConfig is set by configure() and not used before then
8286 mEffectInterface(NULL),
8287 mStatus(NO_INIT), mState(IDLE),
8288 // mMaxDisableWaitCnt is set by configure() and not used before then
8289 // mDisableWaitCnt is set by process() and updateState() and not used before then
8290 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008291{
Steve Block3856b092011-10-20 11:56:00 +01008292 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008293 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008294
8295 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008296 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008297
8298 if (mStatus != NO_ERROR) {
8299 return;
8300 }
8301 lStatus = init();
8302 if (lStatus < 0) {
8303 mStatus = lStatus;
8304 goto Error;
8305 }
8306
Steve Block3856b092011-10-20 11:56:00 +01008307 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008308 return;
8309Error:
8310 EffectRelease(mEffectInterface);
8311 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008312 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008313}
8314
8315AudioFlinger::EffectModule::~EffectModule()
8316{
Steve Block3856b092011-10-20 11:56:00 +01008317 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008318 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008319 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8320 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8321 sp<ThreadBase> thread = mThread.promote();
8322 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008323 audio_stream_t *stream = thread->stream();
8324 if (stream != NULL) {
8325 stream->remove_audio_effect(stream, mEffectInterface);
8326 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008327 }
8328 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008329 // release effect engine
8330 EffectRelease(mEffectInterface);
8331 }
8332}
8333
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008334status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008335{
8336 status_t status;
8337
8338 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008339 int priority = handle->priority();
8340 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008341 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008342 size_t i;
8343 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008344 EffectHandle *h = mHandles[i];
8345 if (h == NULL || h->destroyed_l()) continue;
8346 // first non destroyed handle is considered in control
8347 if (controlHandle == NULL)
8348 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008349 if (h->priority() <= priority) break;
8350 }
8351 // if inserted in first place, move effect control from previous owner to this handle
8352 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008353 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008354 if (controlHandle != NULL) {
8355 enabled = controlHandle->enabled();
8356 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008357 }
Eric Laurent59255e42011-07-27 19:49:51 -07008358 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008359 status = NO_ERROR;
8360 } else {
8361 status = ALREADY_EXISTS;
8362 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008363 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008364 mHandles.insertAt(handle, i);
8365 return status;
8366}
8367
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008368size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008369{
8370 Mutex::Autolock _l(mLock);
8371 size_t size = mHandles.size();
8372 size_t i;
8373 for (i = 0; i < size; i++) {
8374 if (mHandles[i] == handle) break;
8375 }
8376 if (i == size) {
8377 return size;
8378 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008379 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008380
Mathias Agopian65ab4712010-07-14 17:59:35 -07008381 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008382 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008383 if (i == 0) {
8384 EffectHandle *h = controlHandle_l();
8385 if (h != NULL) {
8386 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008387 }
8388 }
8389
Eric Laurentec437d82011-07-26 20:54:46 -07008390 // Prevent calls to process() and other functions on effect interface from now on.
8391 // The effect engine will be released by the destructor when the last strong reference on
8392 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008393 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008394 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008395 }
8396
Eric Laurente65c8912012-07-20 15:57:23 -07008397 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008398}
8399
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008400// must be called with EffectModule::mLock held
8401AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008402{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008403 // the first valid handle in the list has control over the module
8404 for (size_t i = 0; i < mHandles.size(); i++) {
8405 EffectHandle *h = mHandles[i];
8406 if (h != NULL && !h->destroyed_l()) {
8407 return h;
8408 }
8409 }
8410
8411 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008412}
8413
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008414size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008415{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008416 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008417 // keep a strong reference on this EffectModule to avoid calling the
8418 // destructor before we exit
8419 sp<EffectModule> keep(this);
8420 {
8421 sp<ThreadBase> thread = mThread.promote();
8422 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008423 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008424 }
8425 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008426 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008427}
8428
8429void AudioFlinger::EffectModule::updateState() {
8430 Mutex::Autolock _l(mLock);
8431
8432 switch (mState) {
8433 case RESTART:
8434 reset_l();
8435 // FALL THROUGH
8436
8437 case STARTING:
8438 // clear auxiliary effect input buffer for next accumulation
8439 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8440 memset(mConfig.inputCfg.buffer.raw,
8441 0,
8442 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8443 }
8444 start_l();
8445 mState = ACTIVE;
8446 break;
8447 case STOPPING:
8448 stop_l();
8449 mDisableWaitCnt = mMaxDisableWaitCnt;
8450 mState = STOPPED;
8451 break;
8452 case STOPPED:
8453 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8454 // turn off sequence.
8455 if (--mDisableWaitCnt == 0) {
8456 reset_l();
8457 mState = IDLE;
8458 }
8459 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008460 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008461 break;
8462 }
8463}
8464
8465void AudioFlinger::EffectModule::process()
8466{
8467 Mutex::Autolock _l(mLock);
8468
Eric Laurentec437d82011-07-26 20:54:46 -07008469 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008470 mConfig.inputCfg.buffer.raw == NULL ||
8471 mConfig.outputCfg.buffer.raw == NULL) {
8472 return;
8473 }
8474
Eric Laurent8f45bd72010-08-31 13:50:07 -07008475 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008476 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8477 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008478 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008479 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008480 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008481 }
8482
8483 // do the actual processing in the effect engine
8484 int ret = (*mEffectInterface)->process(mEffectInterface,
8485 &mConfig.inputCfg.buffer,
8486 &mConfig.outputCfg.buffer);
8487
8488 // force transition to IDLE state when engine is ready
8489 if (mState == STOPPED && ret == -ENODATA) {
8490 mDisableWaitCnt = 1;
8491 }
8492
8493 // clear auxiliary effect input buffer for next accumulation
8494 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008495 memset(mConfig.inputCfg.buffer.raw, 0,
8496 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008497 }
8498 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008499 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8500 // If an insert effect is idle and input buffer is different from output buffer,
8501 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008502 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008503 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008504 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8505 int16_t *in = mConfig.inputCfg.buffer.s16;
8506 int16_t *out = mConfig.outputCfg.buffer.s16;
8507 for (size_t i = 0; i < frameCnt; i++) {
8508 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008509 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008510 }
8511 }
8512}
8513
8514void AudioFlinger::EffectModule::reset_l()
8515{
8516 if (mEffectInterface == NULL) {
8517 return;
8518 }
8519 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8520}
8521
8522status_t AudioFlinger::EffectModule::configure()
8523{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008524 if (mEffectInterface == NULL) {
8525 return NO_INIT;
8526 }
8527
8528 sp<ThreadBase> thread = mThread.promote();
8529 if (thread == 0) {
8530 return DEAD_OBJECT;
8531 }
8532
8533 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07008534 audio_channel_mask_t channelMask = thread->channelMask();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008535
8536 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008537 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008538 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07008539 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008540 }
Glenn Kasten254af182012-07-03 14:59:05 -07008541 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07008542 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8543 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008544 mConfig.inputCfg.samplingRate = thread->sampleRate();
8545 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8546 mConfig.inputCfg.bufferProvider.cookie = NULL;
8547 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8548 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8549 mConfig.outputCfg.bufferProvider.cookie = NULL;
8550 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8551 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8552 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8553 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008554 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008555 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008556 // - in other sessions:
8557 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8558 // other effect: overwrites output buffer: input buffer == output buffer
8559 // Auxiliary effect:
8560 // accumulates in output buffer: input buffer != output buffer
8561 // Therefore: accumulate <=> input buffer != output buffer
8562 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8563 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8564 } else {
8565 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8566 }
8567 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8568 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8569 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8570 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8571
Steve Block3856b092011-10-20 11:56:00 +01008572 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008573 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8574
Mathias Agopian65ab4712010-07-14 17:59:35 -07008575 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008576 uint32_t size = sizeof(int);
8577 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008578 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008579 sizeof(effect_config_t),
8580 &mConfig,
8581 &size,
8582 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008583 if (status == 0) {
8584 status = cmdStatus;
8585 }
8586
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008587 if (status == 0 &&
8588 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8589 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8590 effect_param_t *p = (effect_param_t *)buf32;
8591
8592 p->psize = sizeof(uint32_t);
8593 p->vsize = sizeof(uint32_t);
8594 size = sizeof(int);
8595 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8596
8597 uint32_t latency = 0;
8598 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8599 if (pbt != NULL) {
8600 latency = pbt->latency_l();
8601 }
8602
8603 *((int32_t *)p->data + 1)= latency;
8604 (*mEffectInterface)->command(mEffectInterface,
8605 EFFECT_CMD_SET_PARAM,
8606 sizeof(effect_param_t) + 8,
8607 &buf32,
8608 &size,
8609 &cmdStatus);
8610 }
8611
Mathias Agopian65ab4712010-07-14 17:59:35 -07008612 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8613 (1000 * mConfig.outputCfg.buffer.frameCount);
8614
8615 return status;
8616}
8617
8618status_t AudioFlinger::EffectModule::init()
8619{
8620 Mutex::Autolock _l(mLock);
8621 if (mEffectInterface == NULL) {
8622 return NO_INIT;
8623 }
8624 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008625 uint32_t size = sizeof(status_t);
8626 status_t status = (*mEffectInterface)->command(mEffectInterface,
8627 EFFECT_CMD_INIT,
8628 0,
8629 NULL,
8630 &size,
8631 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008632 if (status == 0) {
8633 status = cmdStatus;
8634 }
8635 return status;
8636}
8637
Eric Laurentec35a142011-10-05 17:42:25 -07008638status_t AudioFlinger::EffectModule::start()
8639{
8640 Mutex::Autolock _l(mLock);
8641 return start_l();
8642}
8643
Mathias Agopian65ab4712010-07-14 17:59:35 -07008644status_t AudioFlinger::EffectModule::start_l()
8645{
8646 if (mEffectInterface == NULL) {
8647 return NO_INIT;
8648 }
8649 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008650 uint32_t size = sizeof(status_t);
8651 status_t status = (*mEffectInterface)->command(mEffectInterface,
8652 EFFECT_CMD_ENABLE,
8653 0,
8654 NULL,
8655 &size,
8656 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008657 if (status == 0) {
8658 status = cmdStatus;
8659 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008660 if (status == 0 &&
8661 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8662 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8663 sp<ThreadBase> thread = mThread.promote();
8664 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008665 audio_stream_t *stream = thread->stream();
8666 if (stream != NULL) {
8667 stream->add_audio_effect(stream, mEffectInterface);
8668 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008669 }
8670 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008671 return status;
8672}
8673
Eric Laurentec437d82011-07-26 20:54:46 -07008674status_t AudioFlinger::EffectModule::stop()
8675{
8676 Mutex::Autolock _l(mLock);
8677 return stop_l();
8678}
8679
Mathias Agopian65ab4712010-07-14 17:59:35 -07008680status_t AudioFlinger::EffectModule::stop_l()
8681{
8682 if (mEffectInterface == NULL) {
8683 return NO_INIT;
8684 }
8685 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008686 uint32_t size = sizeof(status_t);
8687 status_t status = (*mEffectInterface)->command(mEffectInterface,
8688 EFFECT_CMD_DISABLE,
8689 0,
8690 NULL,
8691 &size,
8692 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008693 if (status == 0) {
8694 status = cmdStatus;
8695 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008696 if (status == 0 &&
8697 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8698 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8699 sp<ThreadBase> thread = mThread.promote();
8700 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008701 audio_stream_t *stream = thread->stream();
8702 if (stream != NULL) {
8703 stream->remove_audio_effect(stream, mEffectInterface);
8704 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008705 }
8706 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008707 return status;
8708}
8709
Eric Laurent25f43952010-07-28 05:40:18 -07008710status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8711 uint32_t cmdSize,
8712 void *pCmdData,
8713 uint32_t *replySize,
8714 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008715{
8716 Mutex::Autolock _l(mLock);
Glenn Kasten26dd66e2012-10-18 15:51:03 -07008717 ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008718
Eric Laurentec437d82011-07-26 20:54:46 -07008719 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008720 return NO_INIT;
8721 }
Eric Laurent25f43952010-07-28 05:40:18 -07008722 status_t status = (*mEffectInterface)->command(mEffectInterface,
8723 cmdCode,
8724 cmdSize,
8725 pCmdData,
8726 replySize,
8727 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008728 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008729 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008730 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008731 EffectHandle *h = mHandles[i];
8732 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008733 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8734 }
8735 }
8736 }
8737 return status;
8738}
8739
8740status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8741{
8742 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008743 return setEnabled_l(enabled);
8744}
8745
8746// must be called with EffectModule::mLock held
8747status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8748{
8749
Steve Block3856b092011-10-20 11:56:00 +01008750 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008751
8752 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008753 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8754 if (enabled && status != NO_ERROR) {
8755 return status;
8756 }
8757
Mathias Agopian65ab4712010-07-14 17:59:35 -07008758 switch (mState) {
8759 // going from disabled to enabled
8760 case IDLE:
8761 mState = STARTING;
8762 break;
8763 case STOPPED:
8764 mState = RESTART;
8765 break;
8766 case STOPPING:
8767 mState = ACTIVE;
8768 break;
8769
8770 // going from enabled to disabled
8771 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008772 mState = STOPPED;
8773 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008774 case STARTING:
8775 mState = IDLE;
8776 break;
8777 case ACTIVE:
8778 mState = STOPPING;
8779 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008780 case DESTROYED:
8781 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008782 }
8783 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008784 EffectHandle *h = mHandles[i];
8785 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008786 h->setEnabled(enabled);
8787 }
8788 }
8789 }
8790 return NO_ERROR;
8791}
8792
Glenn Kastenc59c0042012-02-02 14:06:11 -08008793bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008794{
8795 switch (mState) {
8796 case RESTART:
8797 case STARTING:
8798 case ACTIVE:
8799 return true;
8800 case IDLE:
8801 case STOPPING:
8802 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008803 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008804 default:
8805 return false;
8806 }
8807}
8808
Glenn Kastenc59c0042012-02-02 14:06:11 -08008809bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008810{
8811 switch (mState) {
8812 case RESTART:
8813 case ACTIVE:
8814 case STOPPING:
8815 case STOPPED:
8816 return true;
8817 case IDLE:
8818 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008819 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008820 default:
8821 return false;
8822 }
8823}
8824
Mathias Agopian65ab4712010-07-14 17:59:35 -07008825status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8826{
8827 Mutex::Autolock _l(mLock);
8828 status_t status = NO_ERROR;
8829
8830 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8831 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008832 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008833 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8834 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008835 status_t cmdStatus;
8836 uint32_t volume[2];
8837 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008838 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008839 volume[0] = *left;
8840 volume[1] = *right;
8841 if (controller) {
8842 pVolume = volume;
8843 }
Eric Laurent25f43952010-07-28 05:40:18 -07008844 status = (*mEffectInterface)->command(mEffectInterface,
8845 EFFECT_CMD_SET_VOLUME,
8846 size,
8847 volume,
8848 &size,
8849 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008850 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8851 *left = volume[0];
8852 *right = volume[1];
8853 }
8854 }
8855 return status;
8856}
8857
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008858status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008859{
Eric Laurentf1c04f92012-08-28 14:26:53 -07008860 if (device == AUDIO_DEVICE_NONE) {
8861 return NO_ERROR;
8862 }
8863
Mathias Agopian65ab4712010-07-14 17:59:35 -07008864 Mutex::Autolock _l(mLock);
8865 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008866 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Eric Laurentf1c04f92012-08-28 14:26:53 -07008867 status_t cmdStatus;
8868 uint32_t size = sizeof(status_t);
8869 uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE :
8870 EFFECT_CMD_SET_INPUT_DEVICE;
8871 status = (*mEffectInterface)->command(mEffectInterface,
8872 cmd,
8873 sizeof(uint32_t),
8874 &device,
8875 &size,
8876 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008877 }
8878 return status;
8879}
8880
Glenn Kastenf78aee72012-01-04 11:00:47 -08008881status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008882{
8883 Mutex::Autolock _l(mLock);
8884 status_t status = NO_ERROR;
8885 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008886 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008887 uint32_t size = sizeof(status_t);
8888 status = (*mEffectInterface)->command(mEffectInterface,
8889 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008890 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008891 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008892 &size,
8893 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008894 if (status == NO_ERROR) {
8895 status = cmdStatus;
8896 }
8897 }
8898 return status;
8899}
8900
Eric Laurent57b2dd12012-08-31 17:44:06 -07008901status_t AudioFlinger::EffectModule::setAudioSource(audio_source_t source)
8902{
8903 Mutex::Autolock _l(mLock);
8904 status_t status = NO_ERROR;
8905 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_SOURCE_MASK) == EFFECT_FLAG_AUDIO_SOURCE_IND) {
8906 uint32_t size = 0;
8907 status = (*mEffectInterface)->command(mEffectInterface,
8908 EFFECT_CMD_SET_AUDIO_SOURCE,
8909 sizeof(audio_source_t),
8910 &source,
8911 &size,
8912 NULL);
8913 }
8914 return status;
8915}
8916
Eric Laurent59255e42011-07-27 19:49:51 -07008917void AudioFlinger::EffectModule::setSuspended(bool suspended)
8918{
8919 Mutex::Autolock _l(mLock);
8920 mSuspended = suspended;
8921}
Glenn Kastena3a85482012-01-04 11:01:11 -08008922
8923bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008924{
8925 Mutex::Autolock _l(mLock);
8926 return mSuspended;
8927}
8928
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008929bool AudioFlinger::EffectModule::purgeHandles()
8930{
8931 bool enabled = false;
8932 Mutex::Autolock _l(mLock);
8933 for (size_t i = 0; i < mHandles.size(); i++) {
8934 EffectHandle *handle = mHandles[i];
8935 if (handle != NULL && !handle->destroyed_l()) {
8936 handle->effect().clear();
8937 if (handle->hasControl()) {
8938 enabled = handle->enabled();
8939 }
8940 }
8941 }
8942 return enabled;
8943}
8944
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07008945void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008946{
8947 const size_t SIZE = 256;
8948 char buffer[SIZE];
8949 String8 result;
8950
8951 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8952 result.append(buffer);
8953
8954 bool locked = tryLock(mLock);
8955 // failed to lock - AudioFlinger is probably deadlocked
8956 if (!locked) {
8957 result.append("\t\tCould not lock Fx mutex:\n");
8958 }
8959
8960 result.append("\t\tSession Status State Engine:\n");
8961 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8962 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8963 result.append(buffer);
8964
8965 result.append("\t\tDescriptor:\n");
8966 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8967 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
Glenn Kasten85ab62c2012-11-01 11:11:38 -07008968 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],
8969 mDescriptor.uuid.node[2],
Mathias Agopian65ab4712010-07-14 17:59:35 -07008970 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8971 result.append(buffer);
8972 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
Glenn Kasten85ab62c2012-11-01 11:11:38 -07008973 mDescriptor.type.timeLow, mDescriptor.type.timeMid,
8974 mDescriptor.type.timeHiAndVersion,
8975 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],
8976 mDescriptor.type.node[2],
Mathias Agopian65ab4712010-07-14 17:59:35 -07008977 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8978 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008979 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008980 mDescriptor.apiVersion,
8981 mDescriptor.flags);
8982 result.append(buffer);
8983 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8984 mDescriptor.name);
8985 result.append(buffer);
8986 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8987 mDescriptor.implementor);
8988 result.append(buffer);
8989
8990 result.append("\t\t- Input configuration:\n");
8991 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8992 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8993 (uint32_t)mConfig.inputCfg.buffer.raw,
8994 mConfig.inputCfg.buffer.frameCount,
8995 mConfig.inputCfg.samplingRate,
8996 mConfig.inputCfg.channels,
8997 mConfig.inputCfg.format);
8998 result.append(buffer);
8999
9000 result.append("\t\t- Output configuration:\n");
9001 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
9002 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
9003 (uint32_t)mConfig.outputCfg.buffer.raw,
9004 mConfig.outputCfg.buffer.frameCount,
9005 mConfig.outputCfg.samplingRate,
9006 mConfig.outputCfg.channels,
9007 mConfig.outputCfg.format);
9008 result.append(buffer);
9009
9010 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
9011 result.append(buffer);
9012 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
9013 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009014 EffectHandle *handle = mHandles[i];
9015 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009016 handle->dump(buffer, SIZE);
9017 result.append(buffer);
9018 }
9019 }
9020
9021 result.append("\n");
9022
9023 write(fd, result.string(), result.length());
9024
9025 if (locked) {
9026 mLock.unlock();
9027 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009028}
9029
9030// ----------------------------------------------------------------------------
9031// EffectHandle implementation
9032// ----------------------------------------------------------------------------
9033
9034#undef LOG_TAG
9035#define LOG_TAG "AudioFlinger::EffectHandle"
9036
9037AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
9038 const sp<AudioFlinger::Client>& client,
9039 const sp<IEffectClient>& effectClient,
9040 int32_t priority)
9041 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009042 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009043 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009044{
Steve Block3856b092011-10-20 11:56:00 +01009045 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009046
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009047 if (client == 0) {
9048 return;
9049 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009050 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
9051 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
9052 if (mCblkMemory != 0) {
9053 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
9054
Glenn Kastena0d68332012-01-27 16:47:15 -08009055 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009056 new(mCblk) effect_param_cblk_t();
9057 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009058 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009059 } else {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07009060 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE +
9061 sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07009062 return;
9063 }
9064}
9065
9066AudioFlinger::EffectHandle::~EffectHandle()
9067{
Steve Block3856b092011-10-20 11:56:00 +01009068 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009069
9070 if (mEffect == 0) {
9071 mDestroyed = true;
9072 return;
9073 }
9074 mEffect->lock();
9075 mDestroyed = true;
9076 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009077 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009078}
9079
9080status_t AudioFlinger::EffectHandle::enable()
9081{
Steve Block3856b092011-10-20 11:56:00 +01009082 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009083 if (!mHasControl) return INVALID_OPERATION;
9084 if (mEffect == 0) return DEAD_OBJECT;
9085
Eric Laurentdb7c0792011-08-10 10:37:50 -07009086 if (mEnabled) {
9087 return NO_ERROR;
9088 }
9089
Eric Laurent59255e42011-07-27 19:49:51 -07009090 mEnabled = true;
9091
9092 sp<ThreadBase> thread = mEffect->thread().promote();
9093 if (thread != 0) {
9094 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
9095 }
9096
9097 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
9098 if (mEffect->suspended()) {
9099 return NO_ERROR;
9100 }
9101
Eric Laurentdb7c0792011-08-10 10:37:50 -07009102 status_t status = mEffect->setEnabled(true);
9103 if (status != NO_ERROR) {
9104 if (thread != 0) {
9105 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9106 }
9107 mEnabled = false;
9108 }
9109 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009110}
9111
9112status_t AudioFlinger::EffectHandle::disable()
9113{
Steve Block3856b092011-10-20 11:56:00 +01009114 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009115 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07009116 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009117
Eric Laurentdb7c0792011-08-10 10:37:50 -07009118 if (!mEnabled) {
9119 return NO_ERROR;
9120 }
Eric Laurent59255e42011-07-27 19:49:51 -07009121 mEnabled = false;
9122
9123 if (mEffect->suspended()) {
9124 return NO_ERROR;
9125 }
9126
9127 status_t status = mEffect->setEnabled(false);
9128
9129 sp<ThreadBase> thread = mEffect->thread().promote();
9130 if (thread != 0) {
9131 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9132 }
9133
9134 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009135}
9136
9137void AudioFlinger::EffectHandle::disconnect()
9138{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009139 disconnect(true);
9140}
9141
Glenn Kasten58123c32012-02-03 10:32:24 -08009142void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009143{
Glenn Kasten58123c32012-02-03 10:32:24 -08009144 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009145 if (mEffect == 0) {
9146 return;
9147 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009148 // restore suspended effects if the disconnected handle was enabled and the last one.
9149 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009150 sp<ThreadBase> thread = mEffect->thread().promote();
9151 if (thread != 0) {
9152 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
9153 }
Eric Laurent59255e42011-07-27 19:49:51 -07009154 }
9155
Mathias Agopian65ab4712010-07-14 17:59:35 -07009156 // release sp on module => module destructor can be called now
9157 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009158 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08009159 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08009160 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009161 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
9162 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08009163 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08009164 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07009165 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
9166 mClient.clear();
9167 }
9168}
9169
Eric Laurent25f43952010-07-28 05:40:18 -07009170status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
9171 uint32_t cmdSize,
9172 void *pCmdData,
9173 uint32_t *replySize,
9174 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009175{
Glenn Kasten26dd66e2012-10-18 15:51:03 -07009176 ALOGVV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
9177 cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07009178
9179 // only get parameter command is permitted for applications not controlling the effect
9180 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
9181 return INVALID_OPERATION;
9182 }
9183 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009184 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009185
9186 // handle commands that are not forwarded transparently to effect engine
9187 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07009188 // No need to trylock() here as this function is executed in the binder thread serving a
9189 // particular client process: no risk to block the whole media server process or mixer
9190 // threads if we are stuck here
Mathias Agopian65ab4712010-07-14 17:59:35 -07009191 Mutex::Autolock _l(mCblk->lock);
9192 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
9193 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
9194 mCblk->serverIndex = 0;
9195 mCblk->clientIndex = 0;
9196 return BAD_VALUE;
9197 }
9198 status_t status = NO_ERROR;
9199 while (mCblk->serverIndex < mCblk->clientIndex) {
9200 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07009201 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009202 int *p = (int *)(mBuffer + mCblk->serverIndex);
9203 int size = *p++;
9204 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009205 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009206 break;
9207 }
9208 effect_param_t *param = (effect_param_t *)p;
9209 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009210 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009211 mCblk->serverIndex += size;
9212 continue;
9213 }
Eric Laurent25f43952010-07-28 05:40:18 -07009214 uint32_t psize = sizeof(effect_param_t) +
9215 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
9216 param->vsize;
9217 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
9218 psize,
9219 p,
9220 &rsize,
9221 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07009222 // stop at first error encountered
9223 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009224 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07009225 *(int *)pReplyData = reply;
9226 break;
9227 } else if (reply != NO_ERROR) {
9228 *(int *)pReplyData = reply;
9229 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009230 }
9231 mCblk->serverIndex += size;
9232 }
9233 mCblk->serverIndex = 0;
9234 mCblk->clientIndex = 0;
9235 return status;
9236 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009237 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009238 return enable();
9239 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009240 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009241 return disable();
9242 }
9243
9244 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9245}
9246
Eric Laurent59255e42011-07-27 19:49:51 -07009247void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009248{
Steve Block3856b092011-10-20 11:56:00 +01009249 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009250
9251 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07009252 mEnabled = enabled;
9253
Mathias Agopian65ab4712010-07-14 17:59:35 -07009254 if (signal && mEffectClient != 0) {
9255 mEffectClient->controlStatusChanged(hasControl);
9256 }
9257}
9258
Eric Laurent25f43952010-07-28 05:40:18 -07009259void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
9260 uint32_t cmdSize,
9261 void *pCmdData,
9262 uint32_t replySize,
9263 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009264{
9265 if (mEffectClient != 0) {
9266 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9267 }
9268}
9269
9270
9271
9272void AudioFlinger::EffectHandle::setEnabled(bool enabled)
9273{
9274 if (mEffectClient != 0) {
9275 mEffectClient->enableStatusChanged(enabled);
9276 }
9277}
9278
9279status_t AudioFlinger::EffectHandle::onTransact(
9280 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9281{
9282 return BnEffect::onTransact(code, data, reply, flags);
9283}
9284
9285
9286void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
9287{
Glenn Kastena0d68332012-01-27 16:47:15 -08009288 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009289
9290 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08009291 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07009292 mPriority,
9293 mHasControl,
9294 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009295 mCblk ? mCblk->clientIndex : 0,
9296 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07009297 );
9298
9299 if (locked) {
9300 mCblk->lock.unlock();
9301 }
9302}
9303
9304#undef LOG_TAG
9305#define LOG_TAG "AudioFlinger::EffectChain"
9306
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009307AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009308 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009309 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07009310 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9311 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009312{
Dima Zavinfce7a472011-04-19 22:30:36 -07009313 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009314 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009315 return;
9316 }
9317 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9318 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009319}
9320
9321AudioFlinger::EffectChain::~EffectChain()
9322{
9323 if (mOwnInBuffer) {
9324 delete mInBuffer;
9325 }
9326
9327}
9328
Eric Laurent59255e42011-07-27 19:49:51 -07009329// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Glenn Kasten85ab62c2012-11-01 11:11:38 -07009330sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(
9331 effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009332{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009333 size_t size = mEffects.size();
9334
9335 for (size_t i = 0; i < size; i++) {
9336 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009337 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009338 }
9339 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009340 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009341}
9342
Eric Laurent59255e42011-07-27 19:49:51 -07009343// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009344sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009345{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009346 size_t size = mEffects.size();
9347
9348 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009349 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9350 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009351 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009352 }
9353 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009354 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009355}
9356
Eric Laurent59255e42011-07-27 19:49:51 -07009357// getEffectFromType_l() must be called with ThreadBase::mLock held
9358sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9359 const effect_uuid_t *type)
9360{
Eric Laurent59255e42011-07-27 19:49:51 -07009361 size_t size = mEffects.size();
9362
9363 for (size_t i = 0; i < size; i++) {
9364 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009365 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009366 }
9367 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009368 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009369}
9370
Eric Laurent91b14c42012-05-30 12:30:29 -07009371void AudioFlinger::EffectChain::clearInputBuffer()
9372{
9373 Mutex::Autolock _l(mLock);
9374 sp<ThreadBase> thread = mThread.promote();
9375 if (thread == 0) {
9376 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9377 return;
9378 }
9379 clearInputBuffer_l(thread);
9380}
9381
9382// Must be called with EffectChain::mLock locked
9383void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9384{
9385 size_t numSamples = thread->frameCount() * thread->channelCount();
9386 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9387
9388}
9389
Mathias Agopian65ab4712010-07-14 17:59:35 -07009390// Must be called with EffectChain::mLock locked
9391void AudioFlinger::EffectChain::process_l()
9392{
Eric Laurentdac69112010-09-28 14:09:57 -07009393 sp<ThreadBase> thread = mThread.promote();
9394 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009395 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009396 return;
9397 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009398 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9399 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009400 // always process effects unless no more tracks are on the session and the effect tail
9401 // has been rendered
9402 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009403 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009404 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009405
Eric Laurent544fe9b2011-11-11 15:42:52 -08009406 if (!tracksOnSession && mTailBufferCount == 0) {
9407 doProcess = false;
9408 }
9409
9410 if (activeTrackCnt() == 0) {
9411 // if no track is active and the effect tail has not been rendered,
9412 // the input buffer must be cleared here as the mixer process will not do it
9413 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009414 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009415 if (mTailBufferCount > 0) {
9416 mTailBufferCount--;
9417 }
9418 }
9419 }
Eric Laurentdac69112010-09-28 14:09:57 -07009420 }
9421
Mathias Agopian65ab4712010-07-14 17:59:35 -07009422 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009423 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009424 for (size_t i = 0; i < size; i++) {
9425 mEffects[i]->process();
9426 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009427 }
9428 for (size_t i = 0; i < size; i++) {
9429 mEffects[i]->updateState();
9430 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009431}
9432
Eric Laurentcab11242010-07-15 12:50:15 -07009433// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009434status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009435{
9436 effect_descriptor_t desc = effect->desc();
9437 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9438
9439 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009440 effect->setChain(this);
9441 sp<ThreadBase> thread = mThread.promote();
9442 if (thread == 0) {
9443 return NO_INIT;
9444 }
9445 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009446
9447 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9448 // Auxiliary effects are inserted at the beginning of mEffects vector as
9449 // they are processed first and accumulated in chain input buffer
9450 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009451
Mathias Agopian65ab4712010-07-14 17:59:35 -07009452 // the input buffer for auxiliary effect contains mono samples in
9453 // 32 bit format. This is to avoid saturation in AudoMixer
9454 // accumulation stage. Saturation is done in EffectModule::process() before
9455 // calling the process in effect engine
9456 size_t numSamples = thread->frameCount();
9457 int32_t *buffer = new int32_t[numSamples];
9458 memset(buffer, 0, numSamples * sizeof(int32_t));
9459 effect->setInBuffer((int16_t *)buffer);
9460 // auxiliary effects output samples to chain input buffer for further processing
9461 // by insert effects
9462 effect->setOutBuffer(mInBuffer);
9463 } else {
9464 // Insert effects are inserted at the end of mEffects vector as they are processed
9465 // after track and auxiliary effects.
9466 // Insert effect order as a function of indicated preference:
9467 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9468 // another effect is present
9469 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9470 // last effect claiming first position
9471 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9472 // first effect claiming last position
9473 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9474 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9475 // already present
9476
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009477 size_t size = mEffects.size();
9478 size_t idx_insert = size;
9479 ssize_t idx_insert_first = -1;
9480 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009481
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009482 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009483 effect_descriptor_t d = mEffects[i]->desc();
9484 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9485 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9486 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9487 // check invalid effect chaining combinations
9488 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9489 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Glenn Kasten85ab62c2012-11-01 11:11:38 -07009490 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s",
9491 desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009492 return INVALID_OPERATION;
9493 }
9494 // remember position of first insert effect and by default
9495 // select this as insert position for new effect
9496 if (idx_insert == size) {
9497 idx_insert = i;
9498 }
9499 // remember position of last insert effect claiming
9500 // first position
9501 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9502 idx_insert_first = i;
9503 }
9504 // remember position of first insert effect claiming
9505 // last position
9506 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9507 idx_insert_last == -1) {
9508 idx_insert_last = i;
9509 }
9510 }
9511 }
9512
9513 // modify idx_insert from first position if needed
9514 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9515 if (idx_insert_last != -1) {
9516 idx_insert = idx_insert_last;
9517 } else {
9518 idx_insert = size;
9519 }
9520 } else {
9521 if (idx_insert_first != -1) {
9522 idx_insert = idx_insert_first + 1;
9523 }
9524 }
9525
9526 // always read samples from chain input buffer
9527 effect->setInBuffer(mInBuffer);
9528
9529 // if last effect in the chain, output samples to chain
9530 // output buffer, otherwise to chain input buffer
9531 if (idx_insert == size) {
9532 if (idx_insert != 0) {
9533 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9534 mEffects[idx_insert-1]->configure();
9535 }
9536 effect->setOutBuffer(mOutBuffer);
9537 } else {
9538 effect->setOutBuffer(mInBuffer);
9539 }
9540 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009541
Glenn Kasten85ab62c2012-11-01 11:11:38 -07009542 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this,
9543 idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009544 }
9545 effect->configure();
9546 return NO_ERROR;
9547}
9548
Eric Laurentcab11242010-07-15 12:50:15 -07009549// removeEffect_l() must be called with PlaybackThread::mLock held
9550size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009551{
9552 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009553 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009554 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9555
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009556 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009557 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009558 // calling stop here will remove pre-processing effect from the audio HAL.
9559 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9560 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009561 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9562 mEffects[i]->state() == EffectModule::STOPPING) {
9563 mEffects[i]->stop();
9564 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009565 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9566 delete[] effect->inBuffer();
9567 } else {
9568 if (i == size - 1 && i != 0) {
9569 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9570 mEffects[i - 1]->configure();
9571 }
9572 }
9573 mEffects.removeAt(i);
Glenn Kasten85ab62c2012-11-01 11:11:38 -07009574 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(),
9575 this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009576 break;
9577 }
9578 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009579
9580 return mEffects.size();
9581}
9582
Eric Laurentcab11242010-07-15 12:50:15 -07009583// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009584void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009585{
9586 size_t size = mEffects.size();
9587 for (size_t i = 0; i < size; i++) {
9588 mEffects[i]->setDevice(device);
9589 }
9590}
9591
Eric Laurentcab11242010-07-15 12:50:15 -07009592// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009593void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009594{
9595 size_t size = mEffects.size();
9596 for (size_t i = 0; i < size; i++) {
9597 mEffects[i]->setMode(mode);
9598 }
9599}
9600
Eric Laurent57b2dd12012-08-31 17:44:06 -07009601// setAudioSource_l() must be called with PlaybackThread::mLock held
9602void AudioFlinger::EffectChain::setAudioSource_l(audio_source_t source)
9603{
9604 size_t size = mEffects.size();
9605 for (size_t i = 0; i < size; i++) {
9606 mEffects[i]->setAudioSource(source);
9607 }
9608}
9609
Eric Laurentcab11242010-07-15 12:50:15 -07009610// setVolume_l() must be called with PlaybackThread::mLock held
9611bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009612{
9613 uint32_t newLeft = *left;
9614 uint32_t newRight = *right;
9615 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009616 int ctrlIdx = -1;
9617 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009618
Eric Laurentcab11242010-07-15 12:50:15 -07009619 // first update volume controller
9620 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009621 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009622 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9623 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009624 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009625 break;
9626 }
9627 }
9628
9629 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009630 if (hasControl) {
9631 *left = mNewLeftVolume;
9632 *right = mNewRightVolume;
9633 }
9634 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009635 }
9636
9637 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009638 mLeftVolume = newLeft;
9639 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009640
9641 // second get volume update from volume controller
9642 if (ctrlIdx >= 0) {
9643 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009644 mNewLeftVolume = newLeft;
9645 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009646 }
9647 // then indicate volume to all other effects in chain.
9648 // Pass altered volume to effects before volume controller
9649 // and requested volume to effects after controller
9650 uint32_t lVol = newLeft;
9651 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009652
Mathias Agopian65ab4712010-07-14 17:59:35 -07009653 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009654 if ((int)i == ctrlIdx) continue;
9655 // this also works for ctrlIdx == -1 when there is no volume controller
9656 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009657 lVol = *left;
9658 rVol = *right;
9659 }
9660 mEffects[i]->setVolume(&lVol, &rVol, false);
9661 }
9662 *left = newLeft;
9663 *right = newRight;
9664
9665 return hasControl;
9666}
9667
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009668void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009669{
9670 const size_t SIZE = 256;
9671 char buffer[SIZE];
9672 String8 result;
9673
9674 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9675 result.append(buffer);
9676
9677 bool locked = tryLock(mLock);
9678 // failed to lock - AudioFlinger is probably deadlocked
9679 if (!locked) {
9680 result.append("\tCould not lock mutex:\n");
9681 }
9682
Eric Laurentcab11242010-07-15 12:50:15 -07009683 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9684 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009685 mEffects.size(),
9686 (uint32_t)mInBuffer,
9687 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009688 mActiveTrackCnt);
9689 result.append(buffer);
9690 write(fd, result.string(), result.size());
9691
9692 for (size_t i = 0; i < mEffects.size(); ++i) {
9693 sp<EffectModule> effect = mEffects[i];
9694 if (effect != 0) {
9695 effect->dump(fd, args);
9696 }
9697 }
9698
9699 if (locked) {
9700 mLock.unlock();
9701 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009702}
9703
Eric Laurent59255e42011-07-27 19:49:51 -07009704// must be called with ThreadBase::mLock held
9705void AudioFlinger::EffectChain::setEffectSuspended_l(
9706 const effect_uuid_t *type, bool suspend)
9707{
9708 sp<SuspendedEffectDesc> desc;
9709 // use effect type UUID timelow as key as there is no real risk of identical
9710 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009711 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009712 if (suspend) {
9713 if (index >= 0) {
9714 desc = mSuspendedEffects.valueAt(index);
9715 } else {
9716 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -08009717 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07009718 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009719 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009720 }
9721 if (desc->mRefCount++ == 0) {
9722 sp<EffectModule> effect = getEffectIfEnabled(type);
9723 if (effect != 0) {
9724 desc->mEffect = effect;
9725 effect->setSuspended(true);
9726 effect->setEnabled(false);
9727 }
9728 }
9729 } else {
9730 if (index < 0) {
9731 return;
9732 }
9733 desc = mSuspendedEffects.valueAt(index);
9734 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009735 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009736 desc->mRefCount = 1;
9737 }
9738 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009739 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009740 if (desc->mEffect != 0) {
9741 sp<EffectModule> effect = desc->mEffect.promote();
9742 if (effect != 0) {
9743 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009744 effect->lock();
9745 EffectHandle *handle = effect->controlHandle_l();
9746 if (handle != NULL && !handle->destroyed_l()) {
9747 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009748 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009749 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009750 }
9751 desc->mEffect.clear();
9752 }
9753 mSuspendedEffects.removeItemsAt(index);
9754 }
9755 }
9756}
9757
9758// must be called with ThreadBase::mLock held
9759void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9760{
9761 sp<SuspendedEffectDesc> desc;
9762
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009763 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009764 if (suspend) {
9765 if (index >= 0) {
9766 desc = mSuspendedEffects.valueAt(index);
9767 } else {
9768 desc = new SuspendedEffectDesc();
9769 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009770 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009771 }
9772 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009773 Vector< sp<EffectModule> > effects;
9774 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009775 for (size_t i = 0; i < effects.size(); i++) {
9776 setEffectSuspended_l(&effects[i]->desc().type, true);
9777 }
9778 }
9779 } else {
9780 if (index < 0) {
9781 return;
9782 }
9783 desc = mSuspendedEffects.valueAt(index);
9784 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009785 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009786 desc->mRefCount = 1;
9787 }
9788 if (--desc->mRefCount == 0) {
9789 Vector<const effect_uuid_t *> types;
9790 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9791 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9792 continue;
9793 }
9794 types.add(&mSuspendedEffects.valueAt(i)->mType);
9795 }
9796 for (size_t i = 0; i < types.size(); i++) {
9797 setEffectSuspended_l(types[i], false);
9798 }
Glenn Kasten85ab62c2012-11-01 11:11:38 -07009799 ALOGV("setEffectSuspendedAll_l() remove entry for %08x",
9800 mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009801 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9802 }
9803 }
9804}
9805
Eric Laurent6bffdb82011-09-23 08:40:41 -07009806
9807// The volume effect is used for automated tests only
9808#ifndef OPENSL_ES_H_
9809static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9810 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9811const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9812#endif //OPENSL_ES_H_
9813
Eric Laurentdb7c0792011-08-10 10:37:50 -07009814bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9815{
9816 // auxiliary effects and visualizer are never suspended on output mix
9817 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9818 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009819 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9820 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009821 return false;
9822 }
9823 return true;
9824}
9825
Glenn Kasten85ab62c2012-11-01 11:11:38 -07009826void AudioFlinger::EffectChain::getSuspendEligibleEffects(
9827 Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009828{
Glenn Kastend0539712012-01-30 12:56:03 -08009829 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009830 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009831 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9832 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009833 }
Eric Laurent59255e42011-07-27 19:49:51 -07009834 }
Eric Laurent59255e42011-07-27 19:49:51 -07009835}
9836
9837sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9838 const effect_uuid_t *type)
9839{
Glenn Kasten090f0192012-01-30 13:00:02 -08009840 sp<EffectModule> effect = getEffectFromType_l(type);
9841 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009842}
9843
9844void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9845 bool enabled)
9846{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009847 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009848 if (enabled) {
9849 if (index < 0) {
9850 // if the effect is not suspend check if all effects are suspended
9851 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9852 if (index < 0) {
9853 return;
9854 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009855 if (!isEffectEligibleForSuspend(effect->desc())) {
9856 return;
9857 }
Eric Laurent59255e42011-07-27 19:49:51 -07009858 setEffectSuspended_l(&effect->desc().type, enabled);
9859 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009860 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009861 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009862 return;
9863 }
Eric Laurent59255e42011-07-27 19:49:51 -07009864 }
Steve Block3856b092011-10-20 11:56:00 +01009865 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009866 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009867 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9868 // if effect is requested to suspended but was not yet enabled, supend it now.
9869 if (desc->mEffect == 0) {
9870 desc->mEffect = effect;
9871 effect->setEnabled(false);
9872 effect->setSuspended(true);
9873 }
9874 } else {
9875 if (index < 0) {
9876 return;
9877 }
Steve Block3856b092011-10-20 11:56:00 +01009878 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009879 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009880 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9881 desc->mEffect.clear();
9882 effect->setSuspended(false);
9883 }
9884}
9885
Mathias Agopian65ab4712010-07-14 17:59:35 -07009886#undef LOG_TAG
9887#define LOG_TAG "AudioFlinger"
9888
9889// ----------------------------------------------------------------------------
9890
9891status_t AudioFlinger::onTransact(
9892 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9893{
9894 return BnAudioFlinger::onTransact(code, data, reply, flags);
9895}
9896
Mathias Agopian65ab4712010-07-14 17:59:35 -07009897}; // namespace android