blob: 1a37f4fad76512498f332b5fa717786751612a14 [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.
172// FIXME It would be better for client to tell us whether it wants double-buffering or N-buffering,
173// so we could allocate the right amount of memory.
174// 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()) {
261 // closeInput() will remove first 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()) {
265 // closeOutput() will remove first 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 }
294 } else {
295 // check a match for the requested module handle
John Grossmanee578c02012-07-23 17:05:46 -0700296 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueFor(module);
297 if (audioHwDevice != NULL) {
298 return audioHwDevice;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700299 }
300 }
301 // then try to find a module supporting the requested device.
Dima Zavin799a70e2011-04-18 16:57:27 -0700302 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
John Grossmanee578c02012-07-23 17:05:46 -0700303 AudioHwDevice *audioHwDevice = mAudioHwDevs.valueAt(i);
304 audio_hw_device_t *dev = audioHwDevice->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700305 if ((dev->get_supported_devices(dev) & devices) == devices)
John Grossmanee578c02012-07-23 17:05:46 -0700306 return audioHwDevice;
Dima Zavin799a70e2011-04-18 16:57:27 -0700307 }
Eric Laurenta4c5a552012-03-29 10:12:40 -0700308
Dima Zavin799a70e2011-04-18 16:57:27 -0700309 return NULL;
310}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700311
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700312void AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700313{
314 const size_t SIZE = 256;
315 char buffer[SIZE];
316 String8 result;
317
318 result.append("Clients:\n");
319 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800320 sp<Client> client = mClients.valueAt(i).promote();
321 if (client != 0) {
322 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
323 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700324 }
325 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700326
327 result.append("Global session refs:\n");
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800328 result.append(" session pid count\n");
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700329 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
330 AudioSessionRef *r = mAudioSessionRefs[i];
Glenn Kasten012ca6b2012-03-06 11:22:01 -0800331 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->mSessionid, r->mPid, r->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700332 result.append(buffer);
333 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700334 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335}
336
337
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700338void AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700339{
340 const size_t SIZE = 256;
341 char buffer[SIZE];
342 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800343 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700344
John Grossman4ff14ba2012-02-08 16:37:41 -0800345 snprintf(buffer, SIZE, "Hardware status: %d\n"
346 "Standby Time mSec: %u\n",
347 hardwareStatus,
348 (uint32_t)(mStandbyTimeInNsecs / 1000000));
Mathias Agopian65ab4712010-07-14 17:59:35 -0700349 result.append(buffer);
350 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700351}
352
Glenn Kastenbe5f05e2012-07-18 15:24:02 -0700353void AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700354{
355 const size_t SIZE = 256;
356 char buffer[SIZE];
357 String8 result;
358 snprintf(buffer, SIZE, "Permission Denial: "
359 "can't dump AudioFlinger from pid=%d, uid=%d\n",
360 IPCThreadState::self()->getCallingPid(),
361 IPCThreadState::self()->getCallingUid());
362 result.append(buffer);
363 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700364}
365
366static bool tryLock(Mutex& mutex)
367{
368 bool locked = false;
369 for (int i = 0; i < kDumpLockRetries; ++i) {
370 if (mutex.tryLock() == NO_ERROR) {
371 locked = true;
372 break;
373 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800374 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700375 }
376 return locked;
377}
378
379status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
380{
Glenn Kasten44deb052012-02-05 18:09:08 -0800381 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700382 dumpPermissionDenial(fd, args);
383 } else {
384 // get state of hardware lock
385 bool hardwareLocked = tryLock(mHardwareLock);
386 if (!hardwareLocked) {
387 String8 result(kHardwareLockedString);
388 write(fd, result.string(), result.size());
389 } else {
390 mHardwareLock.unlock();
391 }
392
393 bool locked = tryLock(mLock);
394
395 // failed to lock - AudioFlinger is probably deadlocked
396 if (!locked) {
397 String8 result(kDeadlockedString);
398 write(fd, result.string(), result.size());
399 }
400
401 dumpClients(fd, args);
402 dumpInternals(fd, args);
403
404 // dump playback threads
405 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
406 mPlaybackThreads.valueAt(i)->dump(fd, args);
407 }
408
409 // dump record threads
410 for (size_t i = 0; i < mRecordThreads.size(); i++) {
411 mRecordThreads.valueAt(i)->dump(fd, args);
412 }
413
Dima Zavin799a70e2011-04-18 16:57:27 -0700414 // dump all hardware devs
415 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700416 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Dima Zavin799a70e2011-04-18 16:57:27 -0700417 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700418 }
419 if (locked) mLock.unlock();
420 }
421 return NO_ERROR;
422}
423
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800424sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
425{
426 // If pid is already in the mClients wp<> map, then use that entry
427 // (for which promote() is always != 0), otherwise create a new entry and Client.
428 sp<Client> client = mClients.valueFor(pid).promote();
429 if (client == 0) {
430 client = new Client(this, pid);
431 mClients.add(pid, client);
432 }
433
434 return client;
435}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436
437// IAudioFlinger interface
438
439
440sp<IAudioTrack> AudioFlinger::createTrack(
441 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800442 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700443 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800444 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -0700445 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700446 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -0800447 IAudioFlinger::track_flags_t flags,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700448 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800449 audio_io_handle_t output,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800450 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700451 int *sessionId,
452 status_t *status)
453{
454 sp<PlaybackThread::Track> track;
455 sp<TrackHandle> trackHandle;
456 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700457 status_t lStatus;
458 int lSessionId;
459
Glenn Kasten263709e2012-01-06 08:40:01 -0800460 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
461 // but if someone uses binder directly they could bypass that and cause us to crash
462 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000463 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700464 lStatus = BAD_VALUE;
465 goto Exit;
466 }
467
468 {
469 Mutex::Autolock _l(mLock);
470 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700471 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700472 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000473 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700474 lStatus = BAD_VALUE;
475 goto Exit;
476 }
477
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800478 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700479
Steve Block3856b092011-10-20 11:56:00 +0100480 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700481 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentf436fdc2012-05-24 11:07:14 -0700482 // check if an effect chain with the same session ID is present on another
483 // output thread and move it here.
Eric Laurentde070132010-07-13 04:45:46 -0700484 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700485 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
486 if (mPlaybackThreads.keyAt(i) != output) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700487 uint32_t sessions = t->hasAudioSession(*sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700488 if (sessions & PlaybackThread::EFFECT_SESSION) {
489 effectThread = t.get();
Eric Laurentf436fdc2012-05-24 11:07:14 -0700490 break;
Eric Laurent39e94f82010-07-28 01:32:47 -0700491 }
Eric Laurentde070132010-07-13 04:45:46 -0700492 }
493 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700494 lSessionId = *sessionId;
495 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700496 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700497 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700498 if (sessionId != NULL) {
499 *sessionId = lSessionId;
500 }
501 }
Steve Block3856b092011-10-20 11:56:00 +0100502 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700503
504 track = thread->createTrack_l(client, streamType, sampleRate, format,
Glenn Kasten3acbd052012-02-28 10:39:56 -0800505 channelMask, frameCount, sharedBuffer, lSessionId, flags, tid, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700506
507 // move effect chain to this output thread if an effect on same session was waiting
508 // for a track to be created
509 if (lStatus == NO_ERROR && effectThread != NULL) {
510 Mutex::Autolock _dl(thread->mLock);
511 Mutex::Autolock _sl(effectThread->mLock);
512 moveEffectChain_l(lSessionId, effectThread, thread, true);
513 }
Eric Laurenta011e352012-03-29 15:51:43 -0700514
515 // Look for sync events awaiting for a session to be used.
516 for (int i = 0; i < (int)mPendingSyncEvents.size(); i++) {
517 if (mPendingSyncEvents[i]->triggerSession() == lSessionId) {
518 if (thread->isValidSyncEvent(mPendingSyncEvents[i])) {
Eric Laurent29864602012-05-08 18:57:51 -0700519 if (lStatus == NO_ERROR) {
Glenn Kastend23eedc2012-08-02 13:35:47 -0700520 (void) track->setSyncEvent(mPendingSyncEvents[i]);
Eric Laurent29864602012-05-08 18:57:51 -0700521 } else {
522 mPendingSyncEvents[i]->cancel();
523 }
Eric Laurenta011e352012-03-29 15:51:43 -0700524 mPendingSyncEvents.removeAt(i);
525 i--;
526 }
527 }
528 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700529 }
530 if (lStatus == NO_ERROR) {
531 trackHandle = new TrackHandle(track);
532 } else {
533 // remove local strong reference to Client before deleting the Track so that the Client
534 // destructor is called by the TrackBase destructor with mLock held
535 client.clear();
536 track.clear();
537 }
538
539Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700540 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700541 *status = lStatus;
542 }
543 return trackHandle;
544}
545
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800546uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700547{
548 Mutex::Autolock _l(mLock);
549 PlaybackThread *thread = checkPlaybackThread_l(output);
550 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000551 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700552 return 0;
553 }
554 return thread->sampleRate();
555}
556
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800557int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558{
559 Mutex::Autolock _l(mLock);
560 PlaybackThread *thread = checkPlaybackThread_l(output);
561 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000562 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700563 return 0;
564 }
565 return thread->channelCount();
566}
567
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800568audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700569{
570 Mutex::Autolock _l(mLock);
571 PlaybackThread *thread = checkPlaybackThread_l(output);
572 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000573 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800574 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575 }
576 return thread->format();
577}
578
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800579size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700580{
581 Mutex::Autolock _l(mLock);
582 PlaybackThread *thread = checkPlaybackThread_l(output);
583 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000584 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700585 return 0;
586 }
Glenn Kasten58912562012-04-03 10:45:00 -0700587 // FIXME currently returns the normal mixer's frame count to avoid confusing legacy callers;
588 // should examine all callers and fix them to handle smaller counts
Mathias Agopian65ab4712010-07-14 17:59:35 -0700589 return thread->frameCount();
590}
591
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800592uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700593{
594 Mutex::Autolock _l(mLock);
595 PlaybackThread *thread = checkPlaybackThread_l(output);
596 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000597 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700598 return 0;
599 }
600 return thread->latency();
601}
602
603status_t AudioFlinger::setMasterVolume(float value)
604{
Eric Laurenta1884f92011-08-23 08:25:03 -0700605 status_t ret = initCheck();
606 if (ret != NO_ERROR) {
607 return ret;
608 }
609
Mathias Agopian65ab4712010-07-14 17:59:35 -0700610 // check calling permissions
611 if (!settingsAllowed()) {
612 return PERMISSION_DENIED;
613 }
614
Eric Laurenta4c5a552012-03-29 10:12:40 -0700615 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -0700616 mMasterVolume = value;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700617
John Grossmanee578c02012-07-23 17:05:46 -0700618 // Set master volume in the HALs which support it.
619 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
620 AutoMutex lock(mHardwareLock);
621 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossman4ff14ba2012-02-08 16:37:41 -0800622
John Grossmanee578c02012-07-23 17:05:46 -0700623 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
624 if (dev->canSetMasterVolume()) {
625 dev->hwDevice()->set_master_volume(dev->hwDevice(), value);
Eric Laurent93575202011-01-18 18:39:02 -0800626 }
John Grossmanee578c02012-07-23 17:05:46 -0700627 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700628 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700629
John Grossmanee578c02012-07-23 17:05:46 -0700630 // Now set the master volume in each playback thread. Playback threads
631 // assigned to HALs which do not have master volume support will apply
632 // master volume during the mix operation. Threads with HALs which do
633 // support master volume will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800634 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700635 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700636
637 return NO_ERROR;
638}
639
Glenn Kastenf78aee72012-01-04 11:00:47 -0800640status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700641{
Eric Laurenta1884f92011-08-23 08:25:03 -0700642 status_t ret = initCheck();
643 if (ret != NO_ERROR) {
644 return ret;
645 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700646
647 // check calling permissions
648 if (!settingsAllowed()) {
649 return PERMISSION_DENIED;
650 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800651 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000652 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700653 return BAD_VALUE;
654 }
655
656 { // scope for the lock
657 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700658 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700659 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -0700660 ret = dev->set_mode(dev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700661 mHardwareStatus = AUDIO_HW_IDLE;
662 }
663
664 if (NO_ERROR == ret) {
665 Mutex::Autolock _l(mLock);
666 mMode = mode;
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800667 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700668 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700669 }
670
671 return ret;
672}
673
674status_t AudioFlinger::setMicMute(bool state)
675{
Eric Laurenta1884f92011-08-23 08:25:03 -0700676 status_t ret = initCheck();
677 if (ret != NO_ERROR) {
678 return ret;
679 }
680
Mathias Agopian65ab4712010-07-14 17:59:35 -0700681 // check calling permissions
682 if (!settingsAllowed()) {
683 return PERMISSION_DENIED;
684 }
685
686 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700687 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700688 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700689 ret = dev->set_mic_mute(dev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700690 mHardwareStatus = AUDIO_HW_IDLE;
691 return ret;
692}
693
694bool AudioFlinger::getMicMute() const
695{
Eric Laurenta1884f92011-08-23 08:25:03 -0700696 status_t ret = initCheck();
697 if (ret != NO_ERROR) {
698 return false;
699 }
700
Dima Zavinfce7a472011-04-19 22:30:36 -0700701 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800702 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -0700703 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700704 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
John Grossmanee578c02012-07-23 17:05:46 -0700705 dev->get_mic_mute(dev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700706 mHardwareStatus = AUDIO_HW_IDLE;
707 return state;
708}
709
710status_t AudioFlinger::setMasterMute(bool muted)
711{
John Grossmand8f178d2012-07-20 14:51:35 -0700712 status_t ret = initCheck();
713 if (ret != NO_ERROR) {
714 return ret;
715 }
716
Mathias Agopian65ab4712010-07-14 17:59:35 -0700717 // check calling permissions
718 if (!settingsAllowed()) {
719 return PERMISSION_DENIED;
720 }
721
John Grossmanee578c02012-07-23 17:05:46 -0700722 Mutex::Autolock _l(mLock);
723 mMasterMute = muted;
John Grossmand8f178d2012-07-20 14:51:35 -0700724
John Grossmanee578c02012-07-23 17:05:46 -0700725 // Set master mute in the HALs which support it.
726 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
727 AutoMutex lock(mHardwareLock);
728 AudioHwDevice *dev = mAudioHwDevs.valueAt(i);
John Grossmand8f178d2012-07-20 14:51:35 -0700729
John Grossmanee578c02012-07-23 17:05:46 -0700730 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
731 if (dev->canSetMasterMute()) {
732 dev->hwDevice()->set_master_mute(dev->hwDevice(), muted);
John Grossmand8f178d2012-07-20 14:51:35 -0700733 }
John Grossmanee578c02012-07-23 17:05:46 -0700734 mHardwareStatus = AUDIO_HW_IDLE;
John Grossmand8f178d2012-07-20 14:51:35 -0700735 }
736
John Grossmanee578c02012-07-23 17:05:46 -0700737 // Now set the master mute in each playback thread. Playback threads
738 // assigned to HALs which do not have master mute support will apply master
739 // mute during the mix operation. Threads with HALs which do support master
740 // mute will simply ignore the setting.
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800741 for (size_t i = 0; i < mPlaybackThreads.size(); i++)
John Grossmanee578c02012-07-23 17:05:46 -0700742 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700743
744 return NO_ERROR;
745}
746
747float AudioFlinger::masterVolume() const
748{
Glenn Kasten98067102011-12-13 11:47:54 -0800749 Mutex::Autolock _l(mLock);
750 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700751}
752
753bool AudioFlinger::masterMute() const
754{
Glenn Kasten98067102011-12-13 11:47:54 -0800755 Mutex::Autolock _l(mLock);
756 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700757}
758
John Grossman4ff14ba2012-02-08 16:37:41 -0800759float AudioFlinger::masterVolume_l() const
760{
John Grossman4ff14ba2012-02-08 16:37:41 -0800761 return mMasterVolume;
762}
763
John Grossmand8f178d2012-07-20 14:51:35 -0700764bool AudioFlinger::masterMute_l() const
765{
John Grossmanee578c02012-07-23 17:05:46 -0700766 return mMasterMute;
John Grossmand8f178d2012-07-20 14:51:35 -0700767}
768
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800769status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
770 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700771{
772 // check calling permissions
773 if (!settingsAllowed()) {
774 return PERMISSION_DENIED;
775 }
776
Glenn Kasten263709e2012-01-06 08:40:01 -0800777 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000778 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700779 return BAD_VALUE;
780 }
781
782 AutoMutex lock(mLock);
783 PlaybackThread *thread = NULL;
784 if (output) {
785 thread = checkPlaybackThread_l(output);
786 if (thread == NULL) {
787 return BAD_VALUE;
788 }
789 }
790
791 mStreamTypes[stream].volume = value;
792
793 if (thread == NULL) {
Glenn Kasten8d6a2442012-02-08 14:04:28 -0800794 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700795 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796 }
797 } else {
798 thread->setStreamVolume(stream, value);
799 }
800
801 return NO_ERROR;
802}
803
Glenn Kastenfff6d712012-01-12 16:38:12 -0800804status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805{
806 // check calling permissions
807 if (!settingsAllowed()) {
808 return PERMISSION_DENIED;
809 }
810
Glenn Kasten263709e2012-01-06 08:40:01 -0800811 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700812 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000813 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814 return BAD_VALUE;
815 }
816
Eric Laurent93575202011-01-18 18:39:02 -0800817 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700818 mStreamTypes[stream].mute = muted;
819 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Glenn Kastene53b9ea2012-03-12 16:29:55 -0700820 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821
822 return NO_ERROR;
823}
824
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800825float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700826{
Glenn Kasten263709e2012-01-06 08:40:01 -0800827 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828 return 0.0f;
829 }
830
831 AutoMutex lock(mLock);
832 float volume;
833 if (output) {
834 PlaybackThread *thread = checkPlaybackThread_l(output);
835 if (thread == NULL) {
836 return 0.0f;
837 }
838 volume = thread->streamVolume(stream);
839 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800840 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700841 }
842
843 return volume;
844}
845
Glenn Kastenfff6d712012-01-12 16:38:12 -0800846bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700847{
Glenn Kasten263709e2012-01-06 08:40:01 -0800848 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700849 return true;
850 }
851
Glenn Kasten6637baa2012-01-09 09:40:36 -0800852 AutoMutex lock(mLock);
853 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700854}
855
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800856status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700857{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800858 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700859 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
860 // check calling permissions
861 if (!settingsAllowed()) {
862 return PERMISSION_DENIED;
863 }
864
Mathias Agopian65ab4712010-07-14 17:59:35 -0700865 // ioHandle == 0 means the parameters are global to the audio hardware interface
866 if (ioHandle == 0) {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700867 Mutex::Autolock _l(mLock);
Dima Zavin799a70e2011-04-18 16:57:27 -0700868 status_t final_result = NO_ERROR;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800869 {
Eric Laurenta4c5a552012-03-29 10:12:40 -0700870 AutoMutex lock(mHardwareLock);
871 mHardwareStatus = AUDIO_HW_SET_PARAMETER;
872 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
873 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
874 status_t result = dev->set_parameters(dev, keyValuePairs.string());
875 final_result = result ?: final_result;
876 }
877 mHardwareStatus = AUDIO_HW_IDLE;
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800878 }
Eric Laurent59bd0da2011-08-01 09:52:20 -0700879 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
880 AudioParameter param = AudioParameter(keyValuePairs);
881 String8 value;
882 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
Eric Laurentbee53372011-08-29 12:42:48 -0700883 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
884 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700885 for (size_t i = 0; i < mRecordThreads.size(); i++) {
886 sp<RecordThread> thread = mRecordThreads.valueAt(i);
Glenn Kasten510a3d62012-07-16 14:24:34 -0700887 audio_devices_t device = thread->device() & AUDIO_DEVICE_IN_ALL;
888 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
889 // collect all of the thread's session IDs
890 KeyedVector<int, bool> ids = thread->sessionIds();
891 // suspend effects associated with those session IDs
892 for (size_t j = 0; j < ids.size(); ++j) {
893 int sessionId = ids.keyAt(j);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700894 thread->setEffectSuspended(FX_IID_AEC,
895 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700896 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700897 thread->setEffectSuspended(FX_IID_NS,
898 suspend,
Glenn Kasten510a3d62012-07-16 14:24:34 -0700899 sessionId);
Eric Laurent59bd0da2011-08-01 09:52:20 -0700900 }
901 }
Eric Laurentbee53372011-08-29 12:42:48 -0700902 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700903 }
904 }
Glenn Kasten28ed2f92012-06-07 10:17:54 -0700905 String8 screenState;
906 if (param.get(String8(AudioParameter::keyScreenState), screenState) == NO_ERROR) {
907 bool isOff = screenState == "off";
908 if (isOff != (gScreenState & 1)) {
909 gScreenState = ((gScreenState & ~1) + 2) | isOff;
910 }
911 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700912 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700913 }
914
915 // hold a strong ref on thread in case closeOutput() or closeInput() is called
916 // and the thread is exited once the lock is released
917 sp<ThreadBase> thread;
918 {
919 Mutex::Autolock _l(mLock);
920 thread = checkPlaybackThread_l(ioHandle);
Glenn Kastend5903ec2012-03-18 10:33:27 -0700921 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800923 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700924 // indicate output device change to all input threads for pre processing
925 AudioParameter param = AudioParameter(keyValuePairs);
926 int value;
Eric Laurent89d94e72012-03-16 20:37:59 -0700927 if ((param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) &&
928 (value != 0)) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700929 for (size_t i = 0; i < mRecordThreads.size(); i++) {
930 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
931 }
932 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700933 }
934 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800935 if (thread != 0) {
936 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700937 }
938 return BAD_VALUE;
939}
940
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800941String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700942{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800943// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700944// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
945
Eric Laurenta4c5a552012-03-29 10:12:40 -0700946 Mutex::Autolock _l(mLock);
947
Mathias Agopian65ab4712010-07-14 17:59:35 -0700948 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700949 String8 out_s8;
950
Dima Zavin799a70e2011-04-18 16:57:27 -0700951 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800952 char *s;
953 {
954 AutoMutex lock(mHardwareLock);
955 mHardwareStatus = AUDIO_HW_GET_PARAMETER;
Eric Laurenta4c5a552012-03-29 10:12:40 -0700956 audio_hw_device_t *dev = mAudioHwDevs.valueAt(i)->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -0800957 s = dev->get_parameters(dev, keys.string());
958 mHardwareStatus = AUDIO_HW_IDLE;
959 }
John Grossmanef7740b2012-02-09 11:28:36 -0800960 out_s8 += String8(s ? s : "");
Dima Zavin799a70e2011-04-18 16:57:27 -0700961 free(s);
962 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700963 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700964 }
965
Mathias Agopian65ab4712010-07-14 17:59:35 -0700966 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
967 if (playbackThread != NULL) {
968 return playbackThread->getParameters(keys);
969 }
970 RecordThread *recordThread = checkRecordThread_l(ioHandle);
971 if (recordThread != NULL) {
972 return recordThread->getParameters(keys);
973 }
974 return String8("");
975}
976
Glenn Kastendd8104c2012-07-02 12:42:44 -0700977size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format,
978 audio_channel_mask_t channelMask) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700979{
Eric Laurenta1884f92011-08-23 08:25:03 -0700980 status_t ret = initCheck();
981 if (ret != NO_ERROR) {
982 return 0;
983 }
984
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800985 AutoMutex lock(mHardwareLock);
986 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700987 struct audio_config config = {
988 sample_rate: sampleRate,
Glenn Kastendd8104c2012-07-02 12:42:44 -0700989 channel_mask: channelMask,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -0700990 format: format,
991 };
John Grossmanee578c02012-07-23 17:05:46 -0700992 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
993 size_t size = dev->get_input_buffer_size(dev, &config);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800994 mHardwareStatus = AUDIO_HW_IDLE;
995 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700996}
997
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800998unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700999{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001000 Mutex::Autolock _l(mLock);
1001
1002 RecordThread *recordThread = checkRecordThread_l(ioHandle);
1003 if (recordThread != NULL) {
1004 return recordThread->getInputFramesLost();
1005 }
1006 return 0;
1007}
1008
1009status_t AudioFlinger::setVoiceVolume(float value)
1010{
Eric Laurenta1884f92011-08-23 08:25:03 -07001011 status_t ret = initCheck();
1012 if (ret != NO_ERROR) {
1013 return ret;
1014 }
1015
Mathias Agopian65ab4712010-07-14 17:59:35 -07001016 // check calling permissions
1017 if (!settingsAllowed()) {
1018 return PERMISSION_DENIED;
1019 }
1020
1021 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07001022 audio_hw_device_t *dev = mPrimaryHardwareDev->hwDevice();
Glenn Kasten8abf44d2012-02-02 14:16:03 -08001023 mHardwareStatus = AUDIO_HW_SET_VOICE_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07001024 ret = dev->set_voice_volume(dev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001025 mHardwareStatus = AUDIO_HW_IDLE;
1026
1027 return ret;
1028}
1029
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001030status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
1031 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001032{
1033 status_t status;
1034
1035 Mutex::Autolock _l(mLock);
1036
1037 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
1038 if (playbackThread != NULL) {
1039 return playbackThread->getRenderPosition(halFrames, dspFrames);
1040 }
1041
1042 return BAD_VALUE;
1043}
1044
1045void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
1046{
1047
1048 Mutex::Autolock _l(mLock);
1049
Glenn Kastenbb001922012-02-03 11:10:26 -08001050 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001051 if (mNotificationClients.indexOfKey(pid) < 0) {
1052 sp<NotificationClient> notificationClient = new NotificationClient(this,
1053 client,
1054 pid);
Steve Block3856b092011-10-20 11:56:00 +01001055 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001056
1057 mNotificationClients.add(pid, notificationClient);
1058
1059 sp<IBinder> binder = client->asBinder();
1060 binder->linkToDeath(notificationClient);
1061
1062 // the config change is always sent from playback or record threads to avoid deadlock
1063 // with AudioSystem::gLock
1064 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1065 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
1066 }
1067
1068 for (size_t i = 0; i < mRecordThreads.size(); i++) {
1069 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
1070 }
1071 }
1072}
1073
1074void AudioFlinger::removeNotificationClient(pid_t pid)
1075{
1076 Mutex::Autolock _l(mLock);
1077
Glenn Kastena3b09252012-01-20 09:19:01 -08001078 mNotificationClients.removeItem(pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001079
Steve Block3856b092011-10-20 11:56:00 +01001080 ALOGV("%d died, releasing its sessions", pid);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001081 size_t num = mAudioSessionRefs.size();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001082 bool removed = false;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001083 for (size_t i = 0; i< num; ) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001084 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08001085 ALOGV(" pid %d @ %d", ref->mPid, i);
1086 if (ref->mPid == pid) {
1087 ALOGV(" removing entry for pid %d session %d", pid, ref->mSessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001088 mAudioSessionRefs.removeAt(i);
1089 delete ref;
1090 removed = true;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001091 num--;
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001092 } else {
1093 i++;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001094 }
1095 }
1096 if (removed) {
1097 purgeStaleEffects_l();
1098 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001099}
1100
1101// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kastenb81cc8c2012-03-01 09:14:51 -08001102void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, const void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001103{
1104 size_t size = mNotificationClients.size();
1105 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001106 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
1107 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001108 }
1109}
1110
1111// removeClient_l() must be called with AudioFlinger::mLock held
1112void AudioFlinger::removeClient_l(pid_t pid)
1113{
Steve Block3856b092011-10-20 11:56:00 +01001114 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001115 mClients.removeItem(pid);
1116}
1117
Eric Laurent717e1282012-06-29 16:36:52 -07001118// getEffectThread_l() must be called with AudioFlinger::mLock held
1119sp<AudioFlinger::PlaybackThread> AudioFlinger::getEffectThread_l(int sessionId, int EffectId)
1120{
1121 sp<PlaybackThread> thread;
1122
1123 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
1124 if (mPlaybackThreads.valueAt(i)->getEffect(sessionId, EffectId) != 0) {
1125 ALOG_ASSERT(thread == 0);
1126 thread = mPlaybackThreads.valueAt(i);
1127 }
1128 }
1129
1130 return thread;
1131}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001132
1133// ----------------------------------------------------------------------------
1134
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001135AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001136 audio_devices_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001137 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001138 mType(type),
Glenn Kasten58912562012-04-03 10:45:00 -07001139 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mNormalFrameCount(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001140 // mChannelMask
1141 mChannelCount(0),
1142 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1143 mParamStatus(NO_ERROR),
Glenn Kasten5ad92f62012-07-19 10:02:15 -07001144 mStandby(false), mDevice(device), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001145 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001146{
1147}
1148
1149AudioFlinger::ThreadBase::~ThreadBase()
1150{
1151 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001152 // do not lock the mutex in destructor
1153 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001154 if (mPowerManager != 0) {
1155 sp<IBinder> binder = mPowerManager->asBinder();
1156 binder->unlinkToDeath(mDeathRecipient);
1157 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001158}
1159
1160void AudioFlinger::ThreadBase::exit()
1161{
Steve Block3856b092011-10-20 11:56:00 +01001162 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001163 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001164 // This lock prevents the following race in thread (uniprocessor for illustration):
1165 // if (!exitPending()) {
1166 // // context switch from here to exit()
1167 // // exit() calls requestExit(), what exitPending() observes
1168 // // exit() calls signal(), which is dropped since no waiters
1169 // // context switch back from exit() to here
1170 // mWaitWorkCV.wait(...);
1171 // // now thread is hung
1172 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001173 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001174 requestExit();
1175 mWaitWorkCV.signal();
1176 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001177 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1178 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001179 requestExitAndWait();
1180}
1181
Mathias Agopian65ab4712010-07-14 17:59:35 -07001182status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1183{
1184 status_t status;
1185
Steve Block3856b092011-10-20 11:56:00 +01001186 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001187 Mutex::Autolock _l(mLock);
1188
1189 mNewParameters.add(keyValuePairs);
1190 mWaitWorkCV.signal();
1191 // wait condition with timeout in case the thread loop has exited
1192 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001193 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001194 status = mParamStatus;
1195 mWaitWorkCV.signal();
1196 } else {
1197 status = TIMED_OUT;
1198 }
1199 return status;
1200}
1201
1202void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1203{
1204 Mutex::Autolock _l(mLock);
1205 sendConfigEvent_l(event, param);
1206}
1207
1208// sendConfigEvent_l() must be called with ThreadBase::mLock held
1209void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1210{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001211 ConfigEvent configEvent;
1212 configEvent.mEvent = event;
1213 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001214 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001215 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001216 mWaitWorkCV.signal();
1217}
1218
1219void AudioFlinger::ThreadBase::processConfigEvents()
1220{
1221 mLock.lock();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001222 while (!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001223 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001224 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001225 mConfigEvents.removeAt(0);
1226 // release mLock before locking AudioFlinger mLock: lock order is always
1227 // AudioFlinger then ThreadBase to avoid cross deadlock
1228 mLock.unlock();
1229 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001230 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001231 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001232 mLock.lock();
1233 }
1234 mLock.unlock();
1235}
1236
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001237void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001238{
1239 const size_t SIZE = 256;
1240 char buffer[SIZE];
1241 String8 result;
1242
1243 bool locked = tryLock(mLock);
1244 if (!locked) {
1245 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1246 write(fd, buffer, strlen(buffer));
1247 }
1248
Eric Laurent612bbb52012-03-14 15:03:26 -07001249 snprintf(buffer, SIZE, "io handle: %d\n", mId);
1250 result.append(buffer);
1251 snprintf(buffer, SIZE, "TID: %d\n", getTid());
1252 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001253 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1254 result.append(buffer);
1255 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1256 result.append(buffer);
Glenn Kasten58912562012-04-03 10:45:00 -07001257 snprintf(buffer, SIZE, "HAL frame count: %d\n", mFrameCount);
1258 result.append(buffer);
1259 snprintf(buffer, SIZE, "Normal frame count: %d\n", mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001260 result.append(buffer);
1261 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1262 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001263 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1264 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001265 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1266 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001267 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001268 result.append(buffer);
1269
1270 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1271 result.append(buffer);
1272 result.append(" Index Command");
1273 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1274 snprintf(buffer, SIZE, "\n %02d ", i);
1275 result.append(buffer);
1276 result.append(mNewParameters[i]);
1277 }
1278
1279 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1280 result.append(buffer);
1281 snprintf(buffer, SIZE, " Index event param\n");
1282 result.append(buffer);
1283 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001284 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001285 result.append(buffer);
1286 }
1287 result.append("\n");
1288
1289 write(fd, result.string(), result.size());
1290
1291 if (locked) {
1292 mLock.unlock();
1293 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001294}
1295
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001296void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
Eric Laurent1d2bff02011-07-24 17:49:51 -07001297{
1298 const size_t SIZE = 256;
1299 char buffer[SIZE];
1300 String8 result;
1301
1302 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1303 write(fd, buffer, strlen(buffer));
1304
1305 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1306 sp<EffectChain> chain = mEffectChains[i];
1307 if (chain != 0) {
1308 chain->dump(fd, args);
1309 }
1310 }
Eric Laurent1d2bff02011-07-24 17:49:51 -07001311}
1312
Eric Laurentfeb0db62011-07-22 09:04:31 -07001313void AudioFlinger::ThreadBase::acquireWakeLock()
1314{
1315 Mutex::Autolock _l(mLock);
1316 acquireWakeLock_l();
1317}
1318
1319void AudioFlinger::ThreadBase::acquireWakeLock_l()
1320{
1321 if (mPowerManager == 0) {
1322 // use checkService() to avoid blocking if power service is not up yet
1323 sp<IBinder> binder =
1324 defaultServiceManager()->checkService(String16("power"));
1325 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001326 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001327 } else {
1328 mPowerManager = interface_cast<IPowerManager>(binder);
1329 binder->linkToDeath(mDeathRecipient);
1330 }
1331 }
1332 if (mPowerManager != 0) {
1333 sp<IBinder> binder = new BBinder();
1334 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1335 binder,
1336 String16(mName));
1337 if (status == NO_ERROR) {
1338 mWakeLockToken = binder;
1339 }
Steve Block3856b092011-10-20 11:56:00 +01001340 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001341 }
1342}
1343
1344void AudioFlinger::ThreadBase::releaseWakeLock()
1345{
1346 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001347 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001348}
1349
1350void AudioFlinger::ThreadBase::releaseWakeLock_l()
1351{
1352 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001353 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001354 if (mPowerManager != 0) {
1355 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1356 }
1357 mWakeLockToken.clear();
1358 }
1359}
1360
1361void AudioFlinger::ThreadBase::clearPowerManager()
1362{
1363 Mutex::Autolock _l(mLock);
1364 releaseWakeLock_l();
1365 mPowerManager.clear();
1366}
1367
1368void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1369{
1370 sp<ThreadBase> thread = mThread.promote();
1371 if (thread != 0) {
1372 thread->clearPowerManager();
1373 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001374 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001375}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001376
Eric Laurent59255e42011-07-27 19:49:51 -07001377void AudioFlinger::ThreadBase::setEffectSuspended(
1378 const effect_uuid_t *type, bool suspend, int sessionId)
1379{
1380 Mutex::Autolock _l(mLock);
1381 setEffectSuspended_l(type, suspend, sessionId);
1382}
1383
1384void AudioFlinger::ThreadBase::setEffectSuspended_l(
1385 const effect_uuid_t *type, bool suspend, int sessionId)
1386{
Glenn Kasten090f0192012-01-30 13:00:02 -08001387 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001388 if (chain != 0) {
1389 if (type != NULL) {
1390 chain->setEffectSuspended_l(type, suspend);
1391 } else {
1392 chain->setEffectSuspendedAll_l(suspend);
1393 }
1394 }
1395
1396 updateSuspendedSessions_l(type, suspend, sessionId);
1397}
1398
1399void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1400{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001401 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
Eric Laurent59255e42011-07-27 19:49:51 -07001402 if (index < 0) {
1403 return;
1404 }
1405
Glenn Kasten0a7af182012-07-09 16:09:19 -07001406 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1407 mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001408
1409 for (size_t i = 0; i < sessionEffects.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001410 sp<SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
Eric Laurent59255e42011-07-27 19:49:51 -07001411 for (int j = 0; j < desc->mRefCount; j++) {
1412 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1413 chain->setEffectSuspendedAll_l(true);
1414 } else {
Steve Block3856b092011-10-20 11:56:00 +01001415 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001416 desc->mType.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07001417 chain->setEffectSuspended_l(&desc->mType, true);
1418 }
1419 }
1420 }
1421}
1422
Eric Laurent59255e42011-07-27 19:49:51 -07001423void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1424 bool suspend,
1425 int sessionId)
1426{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08001427 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001428
1429 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1430
1431 if (suspend) {
1432 if (index >= 0) {
Glenn Kasten0a7af182012-07-09 16:09:19 -07001433 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001434 } else {
1435 mSuspendedSessions.add(sessionId, sessionEffects);
1436 }
1437 } else {
1438 if (index < 0) {
1439 return;
1440 }
Glenn Kasten0a7af182012-07-09 16:09:19 -07001441 sessionEffects = mSuspendedSessions.valueAt(index);
Eric Laurent59255e42011-07-27 19:49:51 -07001442 }
1443
1444
1445 int key = EffectChain::kKeyForSuspendAll;
1446 if (type != NULL) {
1447 key = type->timeLow;
1448 }
1449 index = sessionEffects.indexOfKey(key);
1450
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001451 sp<SuspendedSessionDesc> desc;
Eric Laurent59255e42011-07-27 19:49:51 -07001452 if (suspend) {
1453 if (index >= 0) {
1454 desc = sessionEffects.valueAt(index);
1455 } else {
1456 desc = new SuspendedSessionDesc();
1457 if (type != NULL) {
Glenn Kastena189a682012-02-20 12:16:30 -08001458 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07001459 }
1460 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001461 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001462 }
1463 desc->mRefCount++;
1464 } else {
1465 if (index < 0) {
1466 return;
1467 }
1468 desc = sessionEffects.valueAt(index);
1469 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001470 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001471 sessionEffects.removeItemsAt(index);
1472 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001473 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001474 sessionId);
1475 mSuspendedSessions.removeItem(sessionId);
1476 }
1477 }
1478 }
1479 if (!sessionEffects.isEmpty()) {
1480 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1481 }
1482}
1483
1484void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1485 bool enabled,
1486 int sessionId)
1487{
1488 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001489 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1490}
Eric Laurent59255e42011-07-27 19:49:51 -07001491
Eric Laurenta85a74a2011-10-19 11:44:54 -07001492void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1493 bool enabled,
1494 int sessionId)
1495{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001496 if (mType != RECORD) {
1497 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1498 // another session. This gives the priority to well behaved effect control panels
1499 // and applications not using global effects.
Eric Laurent808e7d12012-05-11 19:44:09 -07001500 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1501 // global effects
1502 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07001503 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1504 }
1505 }
Eric Laurent59255e42011-07-27 19:49:51 -07001506
1507 sp<EffectChain> chain = getEffectChain_l(sessionId);
1508 if (chain != 0) {
1509 chain->checkSuspendOnEffectEnabled(effect, enabled);
1510 }
1511}
1512
Mathias Agopian65ab4712010-07-14 17:59:35 -07001513// ----------------------------------------------------------------------------
1514
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001515AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1516 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001517 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07001518 audio_devices_t device,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001519 type_t type)
1520 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001521 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001522 // mStreamTypes[] initialized in constructor body
1523 mOutput(output),
Glenn Kastenfec279f2012-03-08 07:47:15 -08001524 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Glenn Kastenaa4397f2012-03-12 18:13:59 -07001525 mMixerStatus(MIXER_IDLE),
Glenn Kasten81028042012-04-30 18:15:12 -07001526 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07001527 standbyDelay(AudioFlinger::mStandbyTimeInNsecs),
Glenn Kasten28ed2f92012-06-07 10:17:54 -07001528 mScreenState(gScreenState),
Glenn Kasten288ed212012-04-25 17:52:27 -07001529 // index 0 is reserved for normal mixer's submix
1530 mFastTrackAvailMask(((1 << FastMixerState::kMaxFastTracks) - 1) & ~1)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001531{
Glenn Kasten480b4682012-02-28 12:30:08 -08001532 snprintf(mName, kNameLength, "AudioOut_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001533
John Grossmanee578c02012-07-23 17:05:46 -07001534 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1535 // it would be safer to explicitly pass initial masterVolume/masterMute as
1536 // parameter.
1537 //
1538 // If the HAL we are using has support for master volume or master mute,
1539 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1540 // and the mute set to false).
1541 mMasterVolume = audioFlinger->masterVolume_l();
1542 mMasterMute = audioFlinger->masterMute_l();
1543 if (mOutput && mOutput->audioHwDev) {
1544 if (mOutput->audioHwDev->canSetMasterVolume()) {
1545 mMasterVolume = 1.0;
1546 }
1547
1548 if (mOutput->audioHwDev->canSetMasterMute()) {
1549 mMasterMute = false;
1550 }
1551 }
1552
Mathias Agopian65ab4712010-07-14 17:59:35 -07001553 readOutputParameters();
1554
Glenn Kasten263709e2012-01-06 08:40:01 -08001555 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001556 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1557 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1558 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001559 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1560 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001562 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1563 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001564}
1565
1566AudioFlinger::PlaybackThread::~PlaybackThread()
1567{
1568 delete [] mMixBuffer;
1569}
1570
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001571void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001572{
1573 dumpInternals(fd, args);
1574 dumpTracks(fd, args);
1575 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001576}
1577
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001578void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001579{
1580 const size_t SIZE = 256;
1581 char buffer[SIZE];
1582 String8 result;
1583
Glenn Kasten58912562012-04-03 10:45:00 -07001584 result.appendFormat("Output thread %p stream volumes in dB:\n ", this);
1585 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1586 const stream_type_t *st = &mStreamTypes[i];
1587 if (i > 0) {
1588 result.appendFormat(", ");
1589 }
1590 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1591 if (st->mute) {
1592 result.append("M");
1593 }
1594 }
1595 result.append("\n");
1596 write(fd, result.string(), result.length());
1597 result.clear();
1598
Mathias Agopian65ab4712010-07-14 17:59:35 -07001599 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1600 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001601 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001602 for (size_t i = 0; i < mTracks.size(); ++i) {
1603 sp<Track> track = mTracks[i];
1604 if (track != 0) {
1605 track->dump(buffer, SIZE);
1606 result.append(buffer);
1607 }
1608 }
1609
1610 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1611 result.append(buffer);
Glenn Kasten288ed212012-04-25 17:52:27 -07001612 Track::appendDumpHeader(result);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001613 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001614 sp<Track> track = mActiveTracks[i].promote();
1615 if (track != 0) {
1616 track->dump(buffer, SIZE);
1617 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001618 }
1619 }
1620 write(fd, result.string(), result.size());
Glenn Kasten88cbea82012-05-15 07:39:27 -07001621
1622 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1623 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
1624 fdprintf(fd, "Normal mixer raw underrun counters: partial=%u empty=%u\n",
1625 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001626}
1627
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07001628void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001629{
1630 const size_t SIZE = 256;
1631 char buffer[SIZE];
1632 String8 result;
1633
1634 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1635 result.append(buffer);
1636 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1637 result.append(buffer);
1638 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1639 result.append(buffer);
1640 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1641 result.append(buffer);
1642 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1643 result.append(buffer);
1644 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1645 result.append(buffer);
1646 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1647 result.append(buffer);
1648 write(fd, result.string(), result.size());
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07001649 fdprintf(fd, "Fast track availMask=%#x\n", mFastTrackAvailMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001650
1651 dumpBase(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001652}
1653
1654// Thread virtuals
1655status_t AudioFlinger::PlaybackThread::readyToRun()
1656{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001657 status_t status = initCheck();
1658 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001659 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001660 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001661 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001662 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001663 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664}
1665
1666void AudioFlinger::PlaybackThread::onFirstRef()
1667{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001668 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001669}
1670
1671// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastenea7939a2012-03-14 12:56:26 -07001672sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07001673 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001674 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001675 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001676 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07001677 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001678 int frameCount,
1679 const sp<IMemory>& sharedBuffer,
1680 int sessionId,
Glenn Kasten73d22752012-03-19 13:38:30 -07001681 IAudioFlinger::track_flags_t flags,
Glenn Kasten3acbd052012-02-28 10:39:56 -08001682 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001683 status_t *status)
1684{
1685 sp<Track> track;
1686 status_t lStatus;
1687
Glenn Kasten73d22752012-03-19 13:38:30 -07001688 bool isTimed = (flags & IAudioFlinger::TRACK_TIMED) != 0;
1689
1690 // client expresses a preference for FAST, but we get the final say
Glenn Kastene0fa4672012-04-24 14:35:14 -07001691 if (flags & IAudioFlinger::TRACK_FAST) {
1692 if (
Glenn Kasten73d22752012-03-19 13:38:30 -07001693 // not timed
1694 (!isTimed) &&
1695 // either of these use cases:
1696 (
1697 // use case 1: shared buffer with any frame count
1698 (
1699 (sharedBuffer != 0)
1700 ) ||
Glenn Kastene0fa4672012-04-24 14:35:14 -07001701 // use case 2: callback handler and frame count is default or at least as large as HAL
Glenn Kasten73d22752012-03-19 13:38:30 -07001702 (
Glenn Kasten3acbd052012-02-28 10:39:56 -08001703 (tid != -1) &&
Glenn Kastene0fa4672012-04-24 14:35:14 -07001704 ((frameCount == 0) ||
Glenn Kasten3ed29202012-08-07 15:24:44 -07001705 (frameCount >= (int) (mFrameCount * kFastTrackMultiplier)))
Glenn Kasten73d22752012-03-19 13:38:30 -07001706 )
1707 ) &&
1708 // PCM data
1709 audio_is_linear_pcm(format) &&
1710 // mono or stereo
1711 ( (channelMask == AUDIO_CHANNEL_OUT_MONO) ||
1712 (channelMask == AUDIO_CHANNEL_OUT_STEREO) ) &&
Glenn Kasten58912562012-04-03 10:45:00 -07001713#ifndef FAST_TRACKS_AT_NON_NATIVE_SAMPLE_RATE
Glenn Kasten73d22752012-03-19 13:38:30 -07001714 // hardware sample rate
Glenn Kasten58912562012-04-03 10:45:00 -07001715 (sampleRate == mSampleRate) &&
1716#endif
1717 // normal mixer has an associated fast mixer
1718 hasFastMixer() &&
1719 // there are sufficient fast track slots available
1720 (mFastTrackAvailMask != 0)
Glenn Kasten73d22752012-03-19 13:38:30 -07001721 // FIXME test that MixerThread for this fast track has a capable output HAL
1722 // FIXME add a permission test also?
Glenn Kastene0fa4672012-04-24 14:35:14 -07001723 ) {
Glenn Kastene0fa4672012-04-24 14:35:14 -07001724 // if frameCount not specified, then it defaults to fast mixer (HAL) frame count
1725 if (frameCount == 0) {
Glenn Kasten3ed29202012-08-07 15:24:44 -07001726 frameCount = mFrameCount * kFastTrackMultiplier;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001727 }
Glenn Kasten31dfd1d2012-05-01 11:07:08 -07001728 ALOGV("AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%d mFrameCount=%d",
Glenn Kasten300a2ee2012-04-25 13:47:36 -07001729 frameCount, mFrameCount);
Glenn Kastene0fa4672012-04-24 14:35:14 -07001730 } else {
Glenn Kasten852fca92012-05-24 08:44:00 -07001731 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: isTimed=%d sharedBuffer=%p frameCount=%d "
Glenn Kasten254af182012-07-03 14:59:05 -07001732 "mFrameCount=%d format=%d isLinear=%d channelMask=%#x sampleRate=%d mSampleRate=%d "
Glenn Kasten58912562012-04-03 10:45:00 -07001733 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
1734 isTimed, sharedBuffer.get(), frameCount, mFrameCount, format,
1735 audio_is_linear_pcm(format),
1736 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Glenn Kasten73d22752012-03-19 13:38:30 -07001737 flags &= ~IAudioFlinger::TRACK_FAST;
Glenn Kastene0fa4672012-04-24 14:35:14 -07001738 // For compatibility with AudioTrack calculation, buffer depth is forced
1739 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1740 // This is probably too conservative, but legacy application code may depend on it.
1741 // If you change this calculation, also review the start threshold which is related.
1742 uint32_t latencyMs = mOutput->stream->get_latency(mOutput->stream);
1743 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1744 if (minBufCount < 2) {
1745 minBufCount = 2;
Glenn Kasten58912562012-04-03 10:45:00 -07001746 }
Glenn Kastene0fa4672012-04-24 14:35:14 -07001747 int minFrameCount = mNormalFrameCount * minBufCount;
1748 if (frameCount < minFrameCount) {
1749 frameCount = minFrameCount;
1750 }
1751 }
Glenn Kasten73d22752012-03-19 13:38:30 -07001752 }
1753
Mathias Agopian65ab4712010-07-14 17:59:35 -07001754 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001755 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1756 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001757 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001758 "for output %p with format %d",
1759 sampleRate, format, channelMask, mOutput, mFormat);
1760 lStatus = BAD_VALUE;
1761 goto Exit;
1762 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001763 }
1764 } else {
1765 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1766 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001767 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001768 lStatus = BAD_VALUE;
1769 goto Exit;
1770 }
1771 }
1772
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001773 lStatus = initCheck();
1774 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001775 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776 goto Exit;
1777 }
1778
1779 { // scope for mLock
1780 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001781
1782 // all tracks in same audio session must share the same routing strategy otherwise
1783 // conflicts will happen when tracks are moved from one output to another by audio policy
1784 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001785 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001786 for (size_t i = 0; i < mTracks.size(); ++i) {
1787 sp<Track> t = mTracks[i];
Glenn Kasten639dbee2012-03-07 12:26:34 -08001788 if (t != 0 && !t->isOutputTrack()) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001789 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001790 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001791 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001792 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001793 lStatus = BAD_VALUE;
1794 goto Exit;
1795 }
1796 }
1797 }
1798
John Grossman4ff14ba2012-02-08 16:37:41 -08001799 if (!isTimed) {
1800 track = new Track(this, client, streamType, sampleRate, format,
Glenn Kasten73d22752012-03-19 13:38:30 -07001801 channelMask, frameCount, sharedBuffer, sessionId, flags);
John Grossman4ff14ba2012-02-08 16:37:41 -08001802 } else {
1803 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1804 channelMask, frameCount, sharedBuffer, sessionId);
1805 }
Glenn Kastend5903ec2012-03-18 10:33:27 -07001806 if (track == 0 || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001807 lStatus = NO_MEMORY;
1808 goto Exit;
1809 }
1810 mTracks.add(track);
1811
1812 sp<EffectChain> chain = getEffectChain_l(sessionId);
1813 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001814 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001815 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001816 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001817 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001818 }
1819 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001820
Glenn Kasten3acbd052012-02-28 10:39:56 -08001821 if ((flags & IAudioFlinger::TRACK_FAST) && (tid != -1)) {
1822 pid_t callingPid = IPCThreadState::self()->getCallingPid();
1823 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
1824 // so ask activity manager to do this on our behalf
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07001825 int err = requestPriority(callingPid, tid, kPriorityAudioApp);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001826 if (err != 0) {
1827 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07001828 kPriorityAudioApp, callingPid, tid, err);
Glenn Kasten3acbd052012-02-28 10:39:56 -08001829 }
1830 }
Glenn Kasten3acbd052012-02-28 10:39:56 -08001831
Mathias Agopian65ab4712010-07-14 17:59:35 -07001832 lStatus = NO_ERROR;
1833
1834Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07001835 if (status) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001836 *status = lStatus;
1837 }
1838 return track;
1839}
1840
Eric Laurente737cda2012-05-22 18:55:44 -07001841uint32_t AudioFlinger::MixerThread::correctLatency(uint32_t latency) const
1842{
1843 if (mFastMixer != NULL) {
1844 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
1845 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
1846 }
1847 return latency;
1848}
1849
1850uint32_t AudioFlinger::PlaybackThread::correctLatency(uint32_t latency) const
1851{
1852 return latency;
1853}
1854
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855uint32_t AudioFlinger::PlaybackThread::latency() const
1856{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001857 Mutex::Autolock _l(mLock);
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07001858 return latency_l();
1859}
1860uint32_t AudioFlinger::PlaybackThread::latency_l() const
1861{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001862 if (initCheck() == NO_ERROR) {
Eric Laurente737cda2012-05-22 18:55:44 -07001863 return correctLatency(mOutput->stream->get_latency(mOutput->stream));
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001864 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001865 return 0;
1866 }
1867}
1868
Glenn Kasten6637baa2012-01-09 09:40:36 -08001869void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001870{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001871 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001872 // Don't apply master volume in SW if our HAL can do it for us.
1873 if (mOutput && mOutput->audioHwDev &&
1874 mOutput->audioHwDev->canSetMasterVolume()) {
1875 mMasterVolume = 1.0;
1876 } else {
1877 mMasterVolume = value;
1878 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001879}
1880
Glenn Kasten6637baa2012-01-09 09:40:36 -08001881void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001882{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001883 Mutex::Autolock _l(mLock);
John Grossmanee578c02012-07-23 17:05:46 -07001884 // Don't apply master mute in SW if our HAL can do it for us.
1885 if (mOutput && mOutput->audioHwDev &&
1886 mOutput->audioHwDev->canSetMasterMute()) {
1887 mMasterMute = false;
1888 } else {
1889 mMasterMute = muted;
1890 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001891}
1892
Glenn Kasten6637baa2012-01-09 09:40:36 -08001893void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001894{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001895 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001896 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001897}
1898
Glenn Kasten6637baa2012-01-09 09:40:36 -08001899void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001900{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001901 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001902 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001903}
1904
Glenn Kastenfff6d712012-01-12 16:38:12 -08001905float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001906{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001907 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001908 return mStreamTypes[stream].volume;
1909}
1910
Mathias Agopian65ab4712010-07-14 17:59:35 -07001911// addTrack_l() must be called with ThreadBase::mLock held
1912status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1913{
1914 status_t status = ALREADY_EXISTS;
1915
1916 // set retry count for buffer fill
1917 track->mRetryCount = kMaxTrackStartupRetries;
1918 if (mActiveTracks.indexOf(track) < 0) {
1919 // the track is newly added, make sure it fills up all its
1920 // buffers before playing. This is to ensure the client will
1921 // effectively get the latency it requested.
1922 track->mFillingUpStatus = Track::FS_FILLING;
1923 track->mResetDone = false;
Eric Laurent29864602012-05-08 18:57:51 -07001924 track->mPresentationCompleteFrames = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001925 mActiveTracks.add(track);
1926 if (track->mainBuffer() != mMixBuffer) {
1927 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1928 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001929 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001930 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001931 }
1932 }
1933
1934 status = NO_ERROR;
1935 }
1936
Steve Block3856b092011-10-20 11:56:00 +01001937 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001938 mWaitWorkCV.broadcast();
1939
1940 return status;
1941}
1942
1943// destroyTrack_l() must be called with ThreadBase::mLock held
1944void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1945{
1946 track->mState = TrackBase::TERMINATED;
Glenn Kasten288ed212012-04-25 17:52:27 -07001947 // active tracks are removed by threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07001948 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001949 removeTrack_l(track);
1950 }
1951}
1952
1953void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1954{
Eric Laurent29864602012-05-08 18:57:51 -07001955 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurentb469b942011-05-09 12:09:06 -07001956 mTracks.remove(track);
1957 deleteTrackName_l(track->name());
Glenn Kasten288ed212012-04-25 17:52:27 -07001958 // redundant as track is about to be destroyed, for dumpsys only
1959 track->mName = -1;
1960 if (track->isFastTrack()) {
1961 int index = track->mFastIndex;
Eric Laurent29864602012-05-08 18:57:51 -07001962 ALOG_ASSERT(0 < index && index < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07001963 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
1964 mFastTrackAvailMask |= 1 << index;
1965 // redundant as track is about to be destroyed, for dumpsys only
1966 track->mFastIndex = -1;
1967 }
Eric Laurentb469b942011-05-09 12:09:06 -07001968 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1969 if (chain != 0) {
1970 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001971 }
1972}
1973
1974String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1975{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001976 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001977 char *s;
1978
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001979 Mutex::Autolock _l(mLock);
1980 if (initCheck() != NO_ERROR) {
1981 return out_s8;
1982 }
1983
Dima Zavin799a70e2011-04-18 16:57:27 -07001984 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001985 out_s8 = String8(s);
1986 free(s);
1987 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988}
1989
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001990// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001991void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1992 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001993 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001994
Steve Block3856b092011-10-20 11:56:00 +01001995 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001996
1997 switch (event) {
1998 case AudioSystem::OUTPUT_OPENED:
1999 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002000 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002001 desc.samplingRate = mSampleRate;
2002 desc.format = mFormat;
Glenn Kasten58912562012-04-03 10:45:00 -07002003 desc.frameCount = mNormalFrameCount; // FIXME see AudioFlinger::frameCount(audio_io_handle_t)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002004 desc.latency = latency();
2005 param2 = &desc;
2006 break;
2007
2008 case AudioSystem::STREAM_CONFIG_CHANGED:
2009 param2 = &param;
2010 case AudioSystem::OUTPUT_CLOSED:
2011 default:
2012 break;
2013 }
2014 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
2015}
2016
2017void AudioFlinger::PlaybackThread::readOutputParameters()
2018{
Dima Zavin799a70e2011-04-18 16:57:27 -07002019 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002020 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
2021 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07002022 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08002023 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07002024 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07002025 if (mFrameCount & 15) {
2026 ALOGW("HAL output buffer size is %u frames but AudioMixer requires multiples of 16 frames",
2027 mFrameCount);
2028 }
2029
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002030 // Calculate size of normal mix buffer relative to the HAL output buffer size
Glenn Kasten4adcede2012-05-14 12:26:02 -07002031 double multiplier = 1.0;
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002032 if (mType == MIXER && (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002033 size_t minNormalFrameCount = (kMinNormalMixBufferSizeMs * mSampleRate) / 1000;
Glenn Kasten4adcede2012-05-14 12:26:02 -07002034 size_t maxNormalFrameCount = (kMaxNormalMixBufferSizeMs * mSampleRate) / 1000;
2035 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2036 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2037 maxNormalFrameCount = maxNormalFrameCount & ~15;
2038 if (maxNormalFrameCount < minNormalFrameCount) {
2039 maxNormalFrameCount = minNormalFrameCount;
2040 }
2041 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2042 if (multiplier <= 1.0) {
2043 multiplier = 1.0;
2044 } else if (multiplier <= 2.0) {
2045 if (2 * mFrameCount <= maxNormalFrameCount) {
2046 multiplier = 2.0;
2047 } else {
2048 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2049 }
2050 } else {
2051 // prefer an even multiplier, for compatibility with doubling of fast tracks due to HAL SRC
2052 // (it would be unusual for the normal mix buffer size to not be a multiple of fast
2053 // track, but we sometimes have to do this to satisfy the maximum frame count constraint)
2054 // FIXME this rounding up should not be done if no HAL SRC
2055 uint32_t truncMult = (uint32_t) multiplier;
2056 if ((truncMult & 1)) {
2057 if ((truncMult + 1) * mFrameCount <= maxNormalFrameCount) {
2058 ++truncMult;
2059 }
2060 }
2061 multiplier = (double) truncMult;
Glenn Kasten58912562012-04-03 10:45:00 -07002062 }
Glenn Kasten58912562012-04-03 10:45:00 -07002063 }
Glenn Kasten4adcede2012-05-14 12:26:02 -07002064 mNormalFrameCount = multiplier * mFrameCount;
2065 // round up to nearest 16 frames to satisfy AudioMixer
2066 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
Glenn Kasten58912562012-04-03 10:45:00 -07002067 ALOGI("HAL output buffer size %u frames, normal mix buffer size %u frames", mFrameCount, mNormalFrameCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002068
Glenn Kastene9dd0172012-01-27 18:08:45 -08002069 delete[] mMixBuffer;
Eric Laurent67c0a582012-05-01 19:31:12 -07002070 mMixBuffer = new int16_t[mNormalFrameCount * mChannelCount];
2071 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002072
Eric Laurentde070132010-07-13 04:45:46 -07002073 // force reconfiguration of effect chains and engines to take new buffer size and audio
2074 // parameters into account
2075 // Note that mLock is not held when readOutputParameters() is called from the constructor
2076 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2077 // matter.
2078 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2079 Vector< sp<EffectChain> > effectChains = mEffectChains;
2080 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002081 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07002082 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002083}
2084
Eric Laurente737cda2012-05-22 18:55:44 -07002085
Mathias Agopian65ab4712010-07-14 17:59:35 -07002086status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
2087{
Glenn Kastena0d68332012-01-27 16:47:15 -08002088 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002089 return BAD_VALUE;
2090 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002091 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002092 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002093 return INVALID_OPERATION;
2094 }
Dima Zavin799a70e2011-04-18 16:57:27 -07002095 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002096
Dima Zavin799a70e2011-04-18 16:57:27 -07002097 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002098}
2099
Glenn Kasten106e8a42012-08-02 13:37:12 -07002100uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07002101{
2102 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07002103 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002104 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002105 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002106 }
2107
2108 for (size_t i = 0; i < mTracks.size(); ++i) {
2109 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07002110 if (sessionId == track->sessionId() &&
2111 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07002112 result |= TRACK_SESSION;
2113 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002114 }
2115 }
2116
Eric Laurent39e94f82010-07-28 01:32:47 -07002117 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002118}
2119
Eric Laurentde070132010-07-13 04:45:46 -07002120uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
2121{
Dima Zavinfce7a472011-04-19 22:30:36 -07002122 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07002123 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07002124 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2125 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002126 }
2127 for (size_t i = 0; i < mTracks.size(); i++) {
2128 sp<Track> track = mTracks[i];
2129 if (sessionId == track->sessionId() &&
2130 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002131 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07002132 }
2133 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002134 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07002135}
2136
Mathias Agopian65ab4712010-07-14 17:59:35 -07002137
Glenn Kastenaed850d2012-01-26 09:46:34 -08002138AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002139{
2140 Mutex::Autolock _l(mLock);
2141 return mOutput;
2142}
2143
2144AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
2145{
2146 Mutex::Autolock _l(mLock);
2147 AudioStreamOut *output = mOutput;
2148 mOutput = NULL;
Glenn Kasten58912562012-04-03 10:45:00 -07002149 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2150 // must push a NULL and wait for ack
2151 mOutputSink.clear();
2152 mPipeSink.clear();
2153 mNormalSink.clear();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002154 return output;
2155}
2156
2157// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002158audio_stream_t* AudioFlinger::PlaybackThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07002159{
2160 if (mOutput == NULL) {
2161 return NULL;
2162 }
2163 return &mOutput->stream->common;
2164}
2165
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08002166uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
Eric Laurent162b40b2011-12-05 09:47:19 -08002167{
Eric Laurentab9071b2012-06-04 13:45:29 -07002168 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent162b40b2011-12-05 09:47:19 -08002169}
2170
Eric Laurenta011e352012-03-29 15:51:43 -07002171status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2172{
2173 if (!isValidSyncEvent(event)) {
2174 return BAD_VALUE;
2175 }
2176
2177 Mutex::Autolock _l(mLock);
2178
2179 for (size_t i = 0; i < mTracks.size(); ++i) {
2180 sp<Track> track = mTracks[i];
2181 if (event->triggerSession() == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07002182 (void) track->setSyncEvent(event);
Eric Laurenta011e352012-03-29 15:51:43 -07002183 return NO_ERROR;
2184 }
2185 }
2186
2187 return NAME_NOT_FOUND;
2188}
2189
Glenn Kasten106e8a42012-08-02 13:37:12 -07002190bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07002191{
Glenn Kasten0dbb3562012-08-02 16:36:50 -07002192 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
Eric Laurenta011e352012-03-29 15:51:43 -07002193}
2194
Eric Laurent44a957f2012-05-15 15:26:05 -07002195void AudioFlinger::PlaybackThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2196{
2197 size_t count = tracksToRemove.size();
2198 if (CC_UNLIKELY(count)) {
2199 for (size_t i = 0 ; i < count ; i++) {
2200 const sp<Track>& track = tracksToRemove.itemAt(i);
2201 if ((track->sharedBuffer() != 0) &&
2202 (track->mState == TrackBase::ACTIVE || track->mState == TrackBase::RESUMING)) {
2203 AudioSystem::stopOutput(mId, track->streamType(), track->sessionId());
2204 }
2205 }
2206 }
2207
2208}
2209
Mathias Agopian65ab4712010-07-14 17:59:35 -07002210// ----------------------------------------------------------------------------
2211
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002212AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002213 audio_io_handle_t id, audio_devices_t device, type_t type)
Glenn Kasten58912562012-04-03 10:45:00 -07002214 : PlaybackThread(audioFlinger, output, id, device, type),
2215 // mAudioMixer below
Glenn Kasten58912562012-04-03 10:45:00 -07002216 // mFastMixer below
2217 mFastMixerFutex(0)
2218 // mOutputSink below
2219 // mPipeSink below
2220 // mNormalSink below
Mathias Agopian65ab4712010-07-14 17:59:35 -07002221{
Glenn Kastenbb4350d2012-07-03 15:56:38 -07002222 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten254af182012-07-03 14:59:05 -07002223 ALOGV("mSampleRate=%d, mChannelMask=%#x, mChannelCount=%d, mFormat=%d, mFrameSize=%d, "
Glenn Kasten58912562012-04-03 10:45:00 -07002224 "mFrameCount=%d, mNormalFrameCount=%d",
2225 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
2226 mNormalFrameCount);
2227 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
2228
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229 // FIXME - Current mixer implementation only supports stereo output
Glenn Kasten4fe1ec42012-02-27 16:33:15 -08002230 if (mChannelCount != FCC_2) {
2231 ALOGE("Invalid audio hardware channel count %d", mChannelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002232 }
Glenn Kasten58912562012-04-03 10:45:00 -07002233
2234 // create an NBAIO sink for the HAL output stream, and negotiate
2235 mOutputSink = new AudioStreamOutSink(output->stream);
2236 size_t numCounterOffers = 0;
2237 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount)};
2238 ssize_t index = mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
2239 ALOG_ASSERT(index == 0);
2240
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002241 // initialize fast mixer depending on configuration
2242 bool initFastMixer;
2243 switch (kUseFastMixer) {
2244 case FastMixer_Never:
2245 initFastMixer = false;
2246 break;
2247 case FastMixer_Always:
2248 initFastMixer = true;
2249 break;
2250 case FastMixer_Static:
2251 case FastMixer_Dynamic:
2252 initFastMixer = mFrameCount < mNormalFrameCount;
2253 break;
2254 }
2255 if (initFastMixer) {
Glenn Kasten58912562012-04-03 10:45:00 -07002256
2257 // create a MonoPipe to connect our submix to FastMixer
2258 NBAIO_Format format = mOutputSink->format();
Glenn Kasten9017e5e2012-05-15 07:39:52 -07002259 // This pipe depth compensates for scheduling latency of the normal mixer thread.
2260 // When it wakes up after a maximum latency, it runs a few cycles quickly before
2261 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
2262 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Glenn Kasten58912562012-04-03 10:45:00 -07002263 const NBAIO_Format offers[1] = {format};
2264 size_t numCounterOffers = 0;
2265 ssize_t index = monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
2266 ALOG_ASSERT(index == 0);
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002267 monoPipe->setAvgFrames((mScreenState & 1) ?
2268 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
Glenn Kasten58912562012-04-03 10:45:00 -07002269 mPipeSink = monoPipe;
2270
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002271#ifdef TEE_SINK_FRAMES
2272 // create a Pipe to archive a copy of FastMixer's output for dumpsys
2273 Pipe *teeSink = new Pipe(TEE_SINK_FRAMES, format);
2274 numCounterOffers = 0;
2275 index = teeSink->negotiate(offers, 1, NULL, numCounterOffers);
2276 ALOG_ASSERT(index == 0);
2277 mTeeSink = teeSink;
2278 PipeReader *teeSource = new PipeReader(*teeSink);
2279 numCounterOffers = 0;
2280 index = teeSource->negotiate(offers, 1, NULL, numCounterOffers);
2281 ALOG_ASSERT(index == 0);
2282 mTeeSource = teeSource;
2283#endif
2284
Glenn Kasten58912562012-04-03 10:45:00 -07002285 // create fast mixer and configure it initially with just one fast track for our submix
2286 mFastMixer = new FastMixer();
2287 FastMixerStateQueue *sq = mFastMixer->sq();
Glenn Kasten39993082012-05-31 13:40:27 -07002288#ifdef STATE_QUEUE_DUMP
2289 sq->setObserverDump(&mStateQueueObserverDump);
2290 sq->setMutatorDump(&mStateQueueMutatorDump);
2291#endif
Glenn Kasten58912562012-04-03 10:45:00 -07002292 FastMixerState *state = sq->begin();
2293 FastTrack *fastTrack = &state->mFastTracks[0];
2294 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
2295 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
2296 fastTrack->mVolumeProvider = NULL;
2297 fastTrack->mGeneration++;
2298 state->mFastTracksGen++;
2299 state->mTrackMask = 1;
2300 // fast mixer will use the HAL output sink
2301 state->mOutputSink = mOutputSink.get();
2302 state->mOutputSinkGen++;
2303 state->mFrameCount = mFrameCount;
2304 state->mCommand = FastMixerState::COLD_IDLE;
2305 // already done in constructor initialization list
2306 //mFastMixerFutex = 0;
2307 state->mColdFutexAddr = &mFastMixerFutex;
2308 state->mColdGen++;
2309 state->mDumpState = &mFastMixerDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -07002310 state->mTeeSink = mTeeSink.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002311 sq->end();
2312 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2313
2314 // start the fast mixer
2315 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
Glenn Kasten58912562012-04-03 10:45:00 -07002316 pid_t tid = mFastMixer->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002317 int err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kasten58912562012-04-03 10:45:00 -07002318 if (err != 0) {
2319 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002320 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kasten58912562012-04-03 10:45:00 -07002321 }
Glenn Kasten58912562012-04-03 10:45:00 -07002322
Glenn Kastenc15d6652012-05-30 14:52:57 -07002323#ifdef AUDIO_WATCHDOG
2324 // create and start the watchdog
2325 mAudioWatchdog = new AudioWatchdog();
2326 mAudioWatchdog->setDump(&mAudioWatchdogDump);
2327 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
2328 tid = mAudioWatchdog->getTid();
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002329 err = requestPriority(getpid_cached, tid, kPriorityFastMixer);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002330 if (err != 0) {
2331 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Glenn Kastenfd4e20c2012-06-04 11:51:12 -07002332 kPriorityFastMixer, getpid_cached, tid, err);
Glenn Kastenc15d6652012-05-30 14:52:57 -07002333 }
2334#endif
2335
Glenn Kasten58912562012-04-03 10:45:00 -07002336 } else {
2337 mFastMixer = NULL;
2338 }
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002339
2340 switch (kUseFastMixer) {
2341 case FastMixer_Never:
2342 case FastMixer_Dynamic:
2343 mNormalSink = mOutputSink;
2344 break;
2345 case FastMixer_Always:
2346 mNormalSink = mPipeSink;
2347 break;
2348 case FastMixer_Static:
2349 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
2350 break;
2351 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002352}
2353
2354AudioFlinger::MixerThread::~MixerThread()
2355{
Glenn Kasten58912562012-04-03 10:45:00 -07002356 if (mFastMixer != NULL) {
2357 FastMixerStateQueue *sq = mFastMixer->sq();
2358 FastMixerState *state = sq->begin();
2359 if (state->mCommand == FastMixerState::COLD_IDLE) {
2360 int32_t old = android_atomic_inc(&mFastMixerFutex);
2361 if (old == -1) {
2362 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2363 }
2364 }
2365 state->mCommand = FastMixerState::EXIT;
2366 sq->end();
2367 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
2368 mFastMixer->join();
2369 // Though the fast mixer thread has exited, it's state queue is still valid.
2370 // We'll use that extract the final state which contains one remaining fast track
2371 // corresponding to our sub-mix.
2372 state = sq->begin();
2373 ALOG_ASSERT(state->mTrackMask == 1);
2374 FastTrack *fastTrack = &state->mFastTracks[0];
2375 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
2376 delete fastTrack->mBufferProvider;
2377 sq->end(false /*didModify*/);
2378 delete mFastMixer;
Glenn Kastenc15d6652012-05-30 14:52:57 -07002379 if (mAudioWatchdog != 0) {
2380 mAudioWatchdog->requestExit();
2381 mAudioWatchdog->requestExitAndWait();
2382 mAudioWatchdog.clear();
2383 }
Glenn Kasten58912562012-04-03 10:45:00 -07002384 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002385 delete mAudioMixer;
2386}
2387
Glenn Kasten83efdd02012-02-24 07:21:32 -08002388class CpuStats {
2389public:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002390 CpuStats();
2391 void sample(const String8 &title);
Glenn Kasten83efdd02012-02-24 07:21:32 -08002392#ifdef DEBUG_CPU_USAGE
2393private:
Glenn Kasten190a46f2012-03-06 11:27:10 -08002394 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
2395 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
2396
2397 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
2398
2399 int mCpuNum; // thread's current CPU number
2400 int mCpukHz; // frequency of thread's current CPU in kHz
Glenn Kasten83efdd02012-02-24 07:21:32 -08002401#endif
2402};
2403
Glenn Kasten190a46f2012-03-06 11:27:10 -08002404CpuStats::CpuStats()
Glenn Kasten83efdd02012-02-24 07:21:32 -08002405#ifdef DEBUG_CPU_USAGE
Glenn Kasten190a46f2012-03-06 11:27:10 -08002406 : mCpuNum(-1), mCpukHz(-1)
2407#endif
2408{
2409}
2410
2411void CpuStats::sample(const String8 &title) {
2412#ifdef DEBUG_CPU_USAGE
2413 // get current thread's delta CPU time in wall clock ns
2414 double wcNs;
2415 bool valid = mCpuUsage.sampleAndEnable(wcNs);
2416
2417 // record sample for wall clock statistics
2418 if (valid) {
2419 mWcStats.sample(wcNs);
2420 }
2421
2422 // get the current CPU number
2423 int cpuNum = sched_getcpu();
2424
2425 // get the current CPU frequency in kHz
2426 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
2427
2428 // check if either CPU number or frequency changed
2429 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
2430 mCpuNum = cpuNum;
2431 mCpukHz = cpukHz;
2432 // ignore sample for purposes of cycles
2433 valid = false;
2434 }
2435
2436 // if no change in CPU number or frequency, then record sample for cycle statistics
2437 if (valid && mCpukHz > 0) {
2438 double cycles = wcNs * cpukHz * 0.000001;
2439 mHzStats.sample(cycles);
2440 }
2441
2442 unsigned n = mWcStats.n();
2443 // mCpuUsage.elapsed() is expensive, so don't call it every loop
Glenn Kasten83efdd02012-02-24 07:21:32 -08002444 if ((n & 127) == 1) {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002445 long long elapsed = mCpuUsage.elapsed();
Glenn Kasten83efdd02012-02-24 07:21:32 -08002446 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
2447 double perLoop = elapsed / (double) n;
2448 double perLoop100 = perLoop * 0.01;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002449 double perLoop1k = perLoop * 0.001;
2450 double mean = mWcStats.mean();
2451 double stddev = mWcStats.stddev();
2452 double minimum = mWcStats.minimum();
2453 double maximum = mWcStats.maximum();
2454 double meanCycles = mHzStats.mean();
2455 double stddevCycles = mHzStats.stddev();
2456 double minCycles = mHzStats.minimum();
2457 double maxCycles = mHzStats.maximum();
2458 mCpuUsage.resetElapsed();
2459 mWcStats.reset();
2460 mHzStats.reset();
2461 ALOGD("CPU usage for %s over past %.1f secs\n"
2462 " (%u mixer loops at %.1f mean ms per loop):\n"
2463 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
2464 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
2465 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
2466 title.string(),
Glenn Kasten83efdd02012-02-24 07:21:32 -08002467 elapsed * .000000001, n, perLoop * .000001,
2468 mean * .001,
2469 stddev * .001,
2470 minimum * .001,
2471 maximum * .001,
2472 mean / perLoop100,
2473 stddev / perLoop100,
2474 minimum / perLoop100,
Glenn Kasten190a46f2012-03-06 11:27:10 -08002475 maximum / perLoop100,
2476 meanCycles / perLoop1k,
2477 stddevCycles / perLoop1k,
2478 minCycles / perLoop1k,
2479 maxCycles / perLoop1k);
2480
Glenn Kasten83efdd02012-02-24 07:21:32 -08002481 }
2482 }
2483#endif
2484};
2485
Glenn Kasten37d825e2012-02-24 07:21:48 -08002486void AudioFlinger::PlaybackThread::checkSilentMode_l()
2487{
2488 if (!mMasterMute) {
2489 char value[PROPERTY_VALUE_MAX];
2490 if (property_get("ro.audio.silent", value, "0") > 0) {
2491 char *endptr;
2492 unsigned long ul = strtoul(value, &endptr, 0);
2493 if (*endptr == '\0' && ul != 0) {
2494 ALOGD("Silence is golden");
2495 // The setprop command will not allow a property to be changed after
2496 // the first time it is set, so we don't have to worry about un-muting.
2497 setMasterMute_l(true);
2498 }
2499 }
2500 }
2501}
2502
Glenn Kasten000f0e32012-03-01 17:10:56 -08002503bool AudioFlinger::PlaybackThread::threadLoop()
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504{
2505 Vector< sp<Track> > tracksToRemove;
Glenn Kasten688a6402012-02-29 07:57:06 -08002506
Glenn Kasten000f0e32012-03-01 17:10:56 -08002507 standbyTime = systemTime();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002508
2509 // MIXER
Mathias Agopian65ab4712010-07-14 17:59:35 -07002510 nsecs_t lastWarning = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002511
Glenn Kasten000f0e32012-03-01 17:10:56 -08002512 // DUPLICATING
2513 // FIXME could this be made local to while loop?
2514 writeFrames = 0;
Glenn Kasten688a6402012-02-29 07:57:06 -08002515
Glenn Kasten66fcab92012-02-24 14:59:21 -08002516 cacheParameters_l();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002517 sleepTime = idleSleepTime;
2518
Glenn Kasten9f34a362012-03-20 16:46:41 -07002519 if (mType == MIXER) {
2520 sleepTimeShift = 0;
2521 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002522
Glenn Kasten83efdd02012-02-24 07:21:32 -08002523 CpuStats cpuStats;
Glenn Kasten190a46f2012-03-06 11:27:10 -08002524 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07002525
Eric Laurentfeb0db62011-07-22 09:04:31 -07002526 acquireWakeLock();
2527
Mathias Agopian65ab4712010-07-14 17:59:35 -07002528 while (!exitPending())
2529 {
Glenn Kasten190a46f2012-03-06 11:27:10 -08002530 cpuStats.sample(myName);
Glenn Kasten688a6402012-02-29 07:57:06 -08002531
Glenn Kasten73ca0f52012-02-29 07:56:15 -08002532 Vector< sp<EffectChain> > effectChains;
2533
Mathias Agopian65ab4712010-07-14 17:59:35 -07002534 processConfigEvents();
2535
Mathias Agopian65ab4712010-07-14 17:59:35 -07002536 { // scope for mLock
2537
2538 Mutex::Autolock _l(mLock);
2539
2540 if (checkForNewParameters_l()) {
Glenn Kasten66fcab92012-02-24 14:59:21 -08002541 cacheParameters_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002542 }
2543
Glenn Kastenfa26a852012-03-06 11:28:04 -08002544 saveOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002545
Mathias Agopian65ab4712010-07-14 17:59:35 -07002546 // put audio hardware into standby after short delay
Glenn Kasten3e074702012-02-28 18:40:35 -08002547 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002548 isSuspended())) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002549 if (!mStandby) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002550
2551 threadLoop_standby();
2552
Mathias Agopian65ab4712010-07-14 17:59:35 -07002553 mStandby = true;
2554 mBytesWritten = 0;
2555 }
2556
Glenn Kasten3e074702012-02-28 18:40:35 -08002557 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002558 // we're about to wait, flush the binder command buffer
2559 IPCThreadState::self()->flushCommands();
2560
Glenn Kastenfa26a852012-03-06 11:28:04 -08002561 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002562
Mathias Agopian65ab4712010-07-14 17:59:35 -07002563 if (exitPending()) break;
2564
Eric Laurentfeb0db62011-07-22 09:04:31 -07002565 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002566 // wait until we have something to do...
Glenn Kasten190a46f2012-03-06 11:27:10 -08002567 ALOGV("%s going to sleep", myName.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002568 mWaitWorkCV.wait(mLock);
Glenn Kasten190a46f2012-03-06 11:27:10 -08002569 ALOGV("%s waking up", myName.string());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002570 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002571
Eric Laurentda747442012-04-25 18:53:13 -07002572 mMixerStatus = MIXER_IDLE;
Glenn Kasten81028042012-04-30 18:15:12 -07002573 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002574
Glenn Kasten37d825e2012-02-24 07:21:48 -08002575 checkSilentMode_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002576
Glenn Kasten000f0e32012-03-01 17:10:56 -08002577 standbyTime = systemTime() + standbyDelay;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002578 sleepTime = idleSleepTime;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002579 if (mType == MIXER) {
2580 sleepTimeShift = 0;
2581 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002582
Mathias Agopian65ab4712010-07-14 17:59:35 -07002583 continue;
2584 }
2585 }
2586
Glenn Kasten81028042012-04-30 18:15:12 -07002587 // mMixerStatusIgnoringFastTracks is also updated internally
Eric Laurentda747442012-04-25 18:53:13 -07002588 mMixerStatus = prepareTracks_l(&tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002589
2590 // prevent any changes in effect chain list and in each effect chain
2591 // during mixing and effect process as the audio buffers could be deleted
2592 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002593 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002594 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002595
Glenn Kastenfec279f2012-03-08 07:47:15 -08002596 if (CC_LIKELY(mMixerStatus == MIXER_TRACKS_READY)) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002597 threadLoop_mix();
2598 } else {
2599 threadLoop_sleepTime();
2600 }
2601
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002602 if (isSuspended()) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002603 sleepTime = suspendSleepTimeUs();
2604 }
2605
2606 // only process effects if we're going to write
2607 if (sleepTime == 0) {
Glenn Kasten000f0e32012-03-01 17:10:56 -08002608 for (size_t i = 0; i < effectChains.size(); i ++) {
2609 effectChains[i]->process_l();
2610 }
2611 }
2612
2613 // enable changes in effect chain
2614 unlockEffectChains(effectChains);
2615
2616 // sleepTime == 0 means we must write to audio hardware
2617 if (sleepTime == 0) {
2618
2619 threadLoop_write();
2620
2621if (mType == MIXER) {
2622 // write blocked detection
2623 nsecs_t now = systemTime();
2624 nsecs_t delta = now - mLastWriteTime;
2625 if (!mStandby && delta > maxPeriod) {
2626 mNumDelayedWrites++;
2627 if ((now - lastWarning) > kWarningThrottleNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -07002628#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -07002629 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002630#endif
Glenn Kasten000f0e32012-03-01 17:10:56 -08002631 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2632 ns2ms(delta), mNumDelayedWrites, this);
2633 lastWarning = now;
2634 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002635 }
2636}
2637
2638 mStandby = false;
2639 } else {
2640 usleep(sleepTime);
2641 }
2642
Glenn Kasten58912562012-04-03 10:45:00 -07002643 // Finally let go of removed track(s), without the lock held
Glenn Kasten000f0e32012-03-01 17:10:56 -08002644 // since we can't guarantee the destructors won't acquire that
Glenn Kasten58912562012-04-03 10:45:00 -07002645 // same lock. This will also mutate and push a new fast mixer state.
2646 threadLoop_removeTracks(tracksToRemove);
Glenn Kasten1465f0c2012-03-06 11:23:32 -08002647 tracksToRemove.clear();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002648
Glenn Kastenfa26a852012-03-06 11:28:04 -08002649 // FIXME I don't understand the need for this here;
2650 // it was in the original code but maybe the
2651 // assignment in saveOutputTracks() makes this unnecessary?
2652 clearOutputTracks();
Glenn Kasten000f0e32012-03-01 17:10:56 -08002653
2654 // Effect chains will be actually deleted here if they were removed from
2655 // mEffectChains list during mixing or effects processing
2656 effectChains.clear();
2657
2658 // FIXME Note that the above .clear() is no longer necessary since effectChains
2659 // is now local to this block, but will keep it for now (at least until merge done).
2660 }
2661
Glenn Kasten9f34a362012-03-20 16:46:41 -07002662 // for DuplicatingThread, standby mode is handled by the outputTracks, otherwise ...
2663 if (mType == MIXER || mType == DIRECT) {
2664 // put output stream into standby mode
2665 if (!mStandby) {
2666 mOutput->stream->common.standby(&mOutput->stream->common);
2667 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002668 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08002669
2670 releaseWakeLock();
2671
2672 ALOGV("Thread %p type %d exiting", this, mType);
2673 return false;
2674}
2675
Glenn Kasten58912562012-04-03 10:45:00 -07002676void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
2677{
Glenn Kasten58912562012-04-03 10:45:00 -07002678 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
2679}
2680
2681void AudioFlinger::MixerThread::threadLoop_write()
2682{
2683 // FIXME we should only do one push per cycle; confirm this is true
2684 // Start the fast mixer if it's not already running
2685 if (mFastMixer != NULL) {
2686 FastMixerStateQueue *sq = mFastMixer->sq();
2687 FastMixerState *state = sq->begin();
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002688 if (state->mCommand != FastMixerState::MIX_WRITE &&
2689 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
Glenn Kasten58912562012-04-03 10:45:00 -07002690 if (state->mCommand == FastMixerState::COLD_IDLE) {
2691 int32_t old = android_atomic_inc(&mFastMixerFutex);
2692 if (old == -1) {
2693 __futex_syscall3(&mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
2694 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002695 if (mAudioWatchdog != 0) {
2696 mAudioWatchdog->resume();
2697 }
Glenn Kasten58912562012-04-03 10:45:00 -07002698 }
2699 state->mCommand = FastMixerState::MIX_WRITE;
2700 sq->end();
2701 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002702 if (kUseFastMixer == FastMixer_Dynamic) {
2703 mNormalSink = mPipeSink;
2704 }
Glenn Kasten58912562012-04-03 10:45:00 -07002705 } else {
2706 sq->end(false /*didModify*/);
2707 }
2708 }
2709 PlaybackThread::threadLoop_write();
2710}
2711
Glenn Kasten000f0e32012-03-01 17:10:56 -08002712// shared by MIXER and DIRECT, overridden by DUPLICATING
2713void AudioFlinger::PlaybackThread::threadLoop_write()
2714{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002715 // FIXME rewrite to reduce number of system calls
2716 mLastWriteTime = systemTime();
2717 mInWrite = true;
Eric Laurent67c0a582012-05-01 19:31:12 -07002718 int bytesWritten;
Glenn Kasten58912562012-04-03 10:45:00 -07002719
Eric Laurent67c0a582012-05-01 19:31:12 -07002720 // If an NBAIO sink is present, use it to write the normal mixer's submix
2721 if (mNormalSink != 0) {
Glenn Kasten58912562012-04-03 10:45:00 -07002722#define mBitShift 2 // FIXME
Eric Laurent67c0a582012-05-01 19:31:12 -07002723 size_t count = mixBufferSize >> mBitShift;
Glenn Kasten99c99d02012-05-14 16:37:13 -07002724#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002725 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -07002726#endif
Glenn Kasten28ed2f92012-06-07 10:17:54 -07002727 // update the setpoint when gScreenState changes
2728 uint32_t screenState = gScreenState;
2729 if (screenState != mScreenState) {
2730 mScreenState = screenState;
2731 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2732 if (pipe != NULL) {
2733 pipe->setAvgFrames((mScreenState & 1) ?
2734 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2735 }
2736 }
Eric Laurent67c0a582012-05-01 19:31:12 -07002737 ssize_t framesWritten = mNormalSink->write(mMixBuffer, count);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002738#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Eric Laurent67c0a582012-05-01 19:31:12 -07002739 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -07002740#endif
Eric Laurent67c0a582012-05-01 19:31:12 -07002741 if (framesWritten > 0) {
2742 bytesWritten = framesWritten << mBitShift;
2743 } else {
2744 bytesWritten = framesWritten;
2745 }
2746 // otherwise use the HAL / AudioStreamOut directly
2747 } else {
2748 // Direct output thread.
2749 bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Glenn Kasten58912562012-04-03 10:45:00 -07002750 }
2751
Eric Laurent67c0a582012-05-01 19:31:12 -07002752 if (bytesWritten > 0) mBytesWritten += mixBufferSize;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002753 mNumWrites++;
2754 mInWrite = false;
Glenn Kasten000f0e32012-03-01 17:10:56 -08002755}
2756
Glenn Kasten58912562012-04-03 10:45:00 -07002757void AudioFlinger::MixerThread::threadLoop_standby()
2758{
2759 // Idle the fast mixer if it's currently running
2760 if (mFastMixer != NULL) {
2761 FastMixerStateQueue *sq = mFastMixer->sq();
2762 FastMixerState *state = sq->begin();
2763 if (!(state->mCommand & FastMixerState::IDLE)) {
2764 state->mCommand = FastMixerState::COLD_IDLE;
2765 state->mColdFutexAddr = &mFastMixerFutex;
2766 state->mColdGen++;
2767 mFastMixerFutex = 0;
2768 sq->end();
2769 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
2770 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
Glenn Kasten300a2ee2012-04-25 13:47:36 -07002771 if (kUseFastMixer == FastMixer_Dynamic) {
2772 mNormalSink = mOutputSink;
2773 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07002774 if (mAudioWatchdog != 0) {
2775 mAudioWatchdog->pause();
2776 }
Glenn Kasten58912562012-04-03 10:45:00 -07002777 } else {
2778 sq->end(false /*didModify*/);
2779 }
2780 }
2781 PlaybackThread::threadLoop_standby();
2782}
2783
Glenn Kasten000f0e32012-03-01 17:10:56 -08002784// shared by MIXER and DIRECT, overridden by DUPLICATING
2785void AudioFlinger::PlaybackThread::threadLoop_standby()
2786{
Glenn Kasten1ea6d232012-07-09 14:31:33 -07002787 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002788 mOutput->stream->common.standby(&mOutput->stream->common);
Glenn Kasten000f0e32012-03-01 17:10:56 -08002789}
2790
2791void AudioFlinger::MixerThread::threadLoop_mix()
2792{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002793 // obtain the presentation timestamp of the next output buffer
2794 int64_t pts;
2795 status_t status = INVALID_OPERATION;
John Grossman4ff14ba2012-02-08 16:37:41 -08002796
John Grossman2c3b2da2012-08-02 17:08:54 -07002797 if (mNormalSink != 0) {
2798 status = mNormalSink->getNextWriteTimestamp(&pts);
2799 } else {
2800 status = mOutputSink->getNextWriteTimestamp(&pts);
Glenn Kasten952eeb22012-03-06 11:30:57 -08002801 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002802
Glenn Kasten952eeb22012-03-06 11:30:57 -08002803 if (status != NO_ERROR) {
2804 pts = AudioBufferProvider::kInvalidPTS;
2805 }
John Grossman4ff14ba2012-02-08 16:37:41 -08002806
Glenn Kasten952eeb22012-03-06 11:30:57 -08002807 // mix buffers...
2808 mAudioMixer->process(pts);
2809 // increase sleep time progressively when application underrun condition clears.
2810 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
2811 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2812 // such that we would underrun the audio HAL.
2813 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
2814 sleepTimeShift--;
2815 }
2816 sleepTime = 0;
Glenn Kasten66fcab92012-02-24 14:59:21 -08002817 standbyTime = systemTime() + standbyDelay;
Glenn Kasten952eeb22012-03-06 11:30:57 -08002818 //TODO: delay standby when effects have a tail
Glenn Kasten000f0e32012-03-01 17:10:56 -08002819}
2820
2821void AudioFlinger::MixerThread::threadLoop_sleepTime()
2822{
Glenn Kasten952eeb22012-03-06 11:30:57 -08002823 // If no tracks are ready, sleep once for the duration of an output
2824 // buffer size, then write 0s to the output
2825 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08002826 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002827 sleepTime = activeSleepTime >> sleepTimeShift;
2828 if (sleepTime < kMinThreadSleepTimeUs) {
2829 sleepTime = kMinThreadSleepTimeUs;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002830 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08002831 // reduce sleep time in case of consecutive application underruns to avoid
2832 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2833 // duration we would end up writing less data than needed by the audio HAL if
2834 // the condition persists.
2835 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2836 sleepTimeShift++;
2837 }
2838 } else {
2839 sleepTime = idleSleepTime;
2840 }
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002841 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08002842 memset (mMixBuffer, 0, mixBufferSize);
2843 sleepTime = 0;
Glenn Kastenf1da96d2012-07-02 16:10:16 -07002844 ALOGV_IF((mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED)), "anticipated start");
Glenn Kasten952eeb22012-03-06 11:30:57 -08002845 }
2846 // TODO add standby time extension fct of effect tail
Mathias Agopian65ab4712010-07-14 17:59:35 -07002847}
2848
2849// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002850AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
Glenn Kasten3e074702012-02-28 18:40:35 -08002851 Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002852{
2853
Glenn Kasten29c23c32012-01-26 13:37:52 -08002854 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002855 // find out which tracks need to be processed
Glenn Kasten3e074702012-02-28 18:40:35 -08002856 size_t count = mActiveTracks.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002857 size_t mixedTracks = 0;
2858 size_t tracksWithEffect = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002859 // counts only _active_ fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002860 size_t fastTracks = 0;
Glenn Kasten288ed212012-04-25 17:52:27 -07002861 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
Mathias Agopian65ab4712010-07-14 17:59:35 -07002862
2863 float masterVolume = mMasterVolume;
Glenn Kastenea7939a2012-03-14 12:56:26 -07002864 bool masterMute = mMasterMute;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002865
Eric Laurent571d49c2010-08-11 05:20:11 -07002866 if (masterMute) {
2867 masterVolume = 0;
2868 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002869 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002870 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002871 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002872 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002873 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002874 masterVolume = (float)((v + (1 << 23)) >> 24);
2875 chain.clear();
2876 }
2877
Glenn Kasten288ed212012-04-25 17:52:27 -07002878 // prepare a new state to push
2879 FastMixerStateQueue *sq = NULL;
2880 FastMixerState *state = NULL;
2881 bool didModify = false;
2882 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
2883 if (mFastMixer != NULL) {
2884 sq = mFastMixer->sq();
2885 state = sq->begin();
2886 }
2887
Mathias Agopian65ab4712010-07-14 17:59:35 -07002888 for (size_t i=0 ; i<count ; i++) {
Glenn Kasten3e074702012-02-28 18:40:35 -08002889 sp<Track> t = mActiveTracks[i].promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002890 if (t == 0) continue;
2891
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002892 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002893 Track* const track = t.get();
Glenn Kasten58912562012-04-03 10:45:00 -07002894
Glenn Kasten288ed212012-04-25 17:52:27 -07002895 // process fast tracks
Glenn Kasten58912562012-04-03 10:45:00 -07002896 if (track->isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002897
2898 // It's theoretically possible (though unlikely) for a fast track to be created
2899 // and then removed within the same normal mix cycle. This is not a problem, as
2900 // the track never becomes active so it's fast mixer slot is never touched.
2901 // The converse, of removing an (active) track and then creating a new track
2902 // at the identical fast mixer slot within the same normal mix cycle,
2903 // is impossible because the slot isn't marked available until the end of each cycle.
2904 int j = track->mFastIndex;
Glenn Kasten893a0542012-05-30 10:32:06 -07002905 ALOG_ASSERT(0 < j && j < (int)FastMixerState::kMaxFastTracks);
2906 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
Glenn Kasten288ed212012-04-25 17:52:27 -07002907 FastTrack *fastTrack = &state->mFastTracks[j];
2908
2909 // Determine whether the track is currently in underrun condition,
2910 // and whether it had a recent underrun.
Glenn Kasten1295bb4d2012-05-31 07:43:43 -07002911 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
2912 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten09474df2012-05-10 14:48:07 -07002913 uint32_t recentFull = (underruns.mBitFields.mFull -
2914 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
2915 uint32_t recentPartial = (underruns.mBitFields.mPartial -
2916 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
2917 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
2918 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
2919 uint32_t recentUnderruns = recentPartial + recentEmpty;
2920 track->mObservedUnderruns = underruns;
Glenn Kasten288ed212012-04-25 17:52:27 -07002921 // don't count underruns that occur while stopping or pausing
Glenn Kastend08f48c2012-05-01 18:14:02 -07002922 // or stopped which can occur when flush() is called while active
2923 if (!(track->isStopping() || track->isPausing() || track->isStopped())) {
Glenn Kasten288ed212012-04-25 17:52:27 -07002924 track->mUnderrunCount += recentUnderruns;
2925 }
Glenn Kasten288ed212012-04-25 17:52:27 -07002926
Glenn Kastend08f48c2012-05-01 18:14:02 -07002927 // This is similar to the state machine for normal tracks,
Glenn Kasten288ed212012-04-25 17:52:27 -07002928 // with a few modifications for fast tracks.
Glenn Kastend08f48c2012-05-01 18:14:02 -07002929 bool isActive = true;
2930 switch (track->mState) {
2931 case TrackBase::STOPPING_1:
2932 // track stays active in STOPPING_1 state until first underrun
2933 if (recentUnderruns > 0) {
2934 track->mState = TrackBase::STOPPING_2;
2935 }
2936 break;
2937 case TrackBase::PAUSING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002938 // ramp down is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002939 track->setPaused();
Glenn Kastend08f48c2012-05-01 18:14:02 -07002940 break;
2941 case TrackBase::RESUMING:
Glenn Kasten288ed212012-04-25 17:52:27 -07002942 // ramp up is not yet implemented
Glenn Kasten288ed212012-04-25 17:52:27 -07002943 track->mState = TrackBase::ACTIVE;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002944 break;
2945 case TrackBase::ACTIVE:
Glenn Kasten09474df2012-05-10 14:48:07 -07002946 if (recentFull > 0 || recentPartial > 0) {
2947 // track has provided at least some frames recently: reset retry count
2948 track->mRetryCount = kMaxTrackRetries;
2949 }
2950 if (recentUnderruns == 0) {
2951 // no recent underruns: stay active
2952 break;
2953 }
2954 // there has recently been an underrun of some kind
2955 if (track->sharedBuffer() == 0) {
2956 // were any of the recent underruns "empty" (no frames available)?
2957 if (recentEmpty == 0) {
2958 // no, then ignore the partial underruns as they are allowed indefinitely
2959 break;
2960 }
2961 // there has recently been an "empty" underrun: decrement the retry counter
2962 if (--(track->mRetryCount) > 0) {
2963 break;
2964 }
2965 // indicate to client process that the track was disabled because of underrun;
2966 // it will then automatically call start() when data is available
2967 android_atomic_or(CBLK_DISABLED_ON, &track->mCblk->flags);
2968 // remove from active list, but state remains ACTIVE [confusing but true]
2969 isActive = false;
Glenn Kastend08f48c2012-05-01 18:14:02 -07002970 break;
2971 }
2972 // fall through
2973 case TrackBase::STOPPING_2:
2974 case TrackBase::PAUSED:
2975 case TrackBase::TERMINATED:
Eric Laurent29864602012-05-08 18:57:51 -07002976 case TrackBase::STOPPED:
2977 case TrackBase::FLUSHED: // flush() while active
Glenn Kastend08f48c2012-05-01 18:14:02 -07002978 // Check for presentation complete if track is inactive
2979 // We have consumed all the buffers of this track.
2980 // This would be incomplete if we auto-paused on underrun
2981 {
2982 size_t audioHALFrames =
2983 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
2984 size_t framesWritten =
2985 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
2986 if (!track->presentationComplete(framesWritten, audioHALFrames)) {
2987 // track stays in active list until presentation is complete
2988 break;
2989 }
2990 }
2991 if (track->isStopping_2()) {
2992 track->mState = TrackBase::STOPPED;
2993 }
2994 if (track->isStopped()) {
2995 // Can't reset directly, as fast mixer is still polling this track
2996 // track->reset();
2997 // So instead mark this track as needing to be reset after push with ack
2998 resetMask |= 1 << i;
2999 }
3000 isActive = false;
3001 break;
3002 case TrackBase::IDLE:
3003 default:
3004 LOG_FATAL("unexpected track state %d", track->mState);
Glenn Kasten288ed212012-04-25 17:52:27 -07003005 }
3006
3007 if (isActive) {
3008 // was it previously inactive?
3009 if (!(state->mTrackMask & (1 << j))) {
3010 ExtendedAudioBufferProvider *eabp = track;
3011 VolumeProvider *vp = track;
3012 fastTrack->mBufferProvider = eabp;
3013 fastTrack->mVolumeProvider = vp;
3014 fastTrack->mSampleRate = track->mSampleRate;
3015 fastTrack->mChannelMask = track->mChannelMask;
3016 fastTrack->mGeneration++;
3017 state->mTrackMask |= 1 << j;
3018 didModify = true;
3019 // no acknowledgement required for newly active tracks
3020 }
3021 // cache the combined master volume and stream type volume for fast mixer; this
3022 // lacks any synchronization or barrier so VolumeProvider may read a stale value
3023 track->mCachedVolume = track->isMuted() ?
3024 0 : masterVolume * mStreamTypes[track->streamType()].volume;
3025 ++fastTracks;
3026 } else {
3027 // was it previously active?
3028 if (state->mTrackMask & (1 << j)) {
3029 fastTrack->mBufferProvider = NULL;
3030 fastTrack->mGeneration++;
3031 state->mTrackMask &= ~(1 << j);
3032 didModify = true;
3033 // If any fast tracks were removed, we must wait for acknowledgement
3034 // because we're about to decrement the last sp<> on those tracks.
3035 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastend08f48c2012-05-01 18:14:02 -07003036 } else {
3037 LOG_FATAL("fast track %d should have been active", j);
Glenn Kasten288ed212012-04-25 17:52:27 -07003038 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07003039 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003040 // Avoids a misleading display in dumpsys
Glenn Kasten09474df2012-05-10 14:48:07 -07003041 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten58912562012-04-03 10:45:00 -07003042 }
3043 continue;
3044 }
3045
3046 { // local variable scope to avoid goto warning
3047
Mathias Agopian65ab4712010-07-14 17:59:35 -07003048 audio_track_cblk_t* cblk = track->cblk();
3049
3050 // The first time a track is added we wait
3051 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003052 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08003053 // make sure that we have enough frames to mix one full buffer.
3054 // enforce this condition only once to enable draining the buffer in case the client
3055 // app does not call stop() and relies on underrun to stop:
Eric Laurentda747442012-04-25 18:53:13 -07003056 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08003057 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07003058 uint32_t minFrames = 1;
Eric Laurent83faee02012-04-27 18:24:29 -07003059 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
Glenn Kasten81028042012-04-30 18:15:12 -07003060 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07003061 if (t->sampleRate() == (int)mSampleRate) {
Glenn Kasten58912562012-04-03 10:45:00 -07003062 minFrames = mNormalFrameCount;
Eric Laurent3dbe3202011-11-03 12:16:05 -07003063 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08003064 // +1 for rounding and +1 for additional sample needed for interpolation
Glenn Kasten58912562012-04-03 10:45:00 -07003065 minFrames = (mNormalFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
Eric Laurent071ccd52011-12-22 16:08:41 -08003066 // add frames already consumed but not yet released by the resampler
Glenn Kastenea7939a2012-03-14 12:56:26 -07003067 // because cblk->framesReady() will include these frames
Eric Laurent071ccd52011-12-22 16:08:41 -08003068 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
3069 // the minimum track buffer size is normally twice the number of frames necessary
3070 // to fill one buffer and the resampler should not leave more than one buffer worth
3071 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00003072 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07003073 }
3074 }
John Grossman4ff14ba2012-02-08 16:37:41 -08003075 if ((track->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07003076 !track->isPaused() && !track->isTerminated())
3077 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003078 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003079
3080 mixedTracks++;
3081
3082 // track->mainBuffer() != mMixBuffer means there is an effect chain
3083 // connected to the track
3084 chain.clear();
3085 if (track->mainBuffer() != mMixBuffer) {
3086 chain = getEffectChain_l(track->sessionId());
3087 // Delegate volume control to effect in track effect chain if needed
3088 if (chain != 0) {
3089 tracksWithEffect++;
3090 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003091 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003092 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003093 }
3094 }
3095
3096
3097 int param = AudioMixer::VOLUME;
3098 if (track->mFillingUpStatus == Track::FS_FILLED) {
3099 // no ramp for the first volume setting
3100 track->mFillingUpStatus = Track::FS_ACTIVE;
3101 if (track->mState == TrackBase::RESUMING) {
3102 track->mState = TrackBase::ACTIVE;
3103 param = AudioMixer::RAMP_VOLUME;
3104 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003105 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003106 } else if (cblk->server != 0) {
3107 // If the track is stopped before the first frame was mixed,
3108 // do not apply ramp
3109 param = AudioMixer::RAMP_VOLUME;
3110 }
3111
3112 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07003113 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07003114 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08003115 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003116 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003117 if (track->isPausing()) {
3118 track->setPaused();
3119 }
3120 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07003121
Mathias Agopian65ab4712010-07-14 17:59:35 -07003122 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08003123 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003124 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08003125 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003126 vl = vlr & 0xFFFF;
3127 vr = vlr >> 16;
3128 // track volumes come from shared memory, so can't be trusted and must be clamped
3129 if (vl > MAX_GAIN_INT) {
3130 ALOGV("Track left volume out of range: %04X", vl);
3131 vl = MAX_GAIN_INT;
3132 }
3133 if (vr > MAX_GAIN_INT) {
3134 ALOGV("Track right volume out of range: %04X", vr);
3135 vr = MAX_GAIN_INT;
3136 }
3137 // now apply the master volume and stream type volume
3138 vl = (uint32_t)(v * vl) << 12;
3139 vr = (uint32_t)(v * vr) << 12;
3140 // assuming master volume and stream type volume each go up to 1.0,
3141 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07003142
Glenn Kasten05632a52012-01-03 14:22:33 -08003143 uint16_t sendLevel = cblk->getSendLevel_U4_12();
3144 // send level comes from shared memory and so may be corrupt
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003145 if (sendLevel > MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08003146 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003147 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08003148 }
3149 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003150 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07003151 // Delegate volume control to effect in track effect chain if needed
3152 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
3153 // Do not ramp volume if volume is controlled by effect
3154 param = AudioMixer::VOLUME;
3155 track->mHasVolumeController = true;
3156 } else {
3157 // force no volume ramp when volume controller was just disabled or removed
3158 // from effect chain to avoid volume spike
3159 if (track->mHasVolumeController) {
3160 param = AudioMixer::VOLUME;
3161 }
3162 track->mHasVolumeController = false;
3163 }
3164
3165 // Convert volumes from 8.24 to 4.12 format
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003166 // This additional clamping is needed in case chain->setVolume_l() overshot
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003167 vl = (vl + (1 << 11)) >> 12;
3168 if (vl > MAX_GAIN_INT) vl = MAX_GAIN_INT;
3169 vr = (vr + (1 << 11)) >> 12;
3170 if (vr > MAX_GAIN_INT) vr = MAX_GAIN_INT;
Eric Laurente0aed6d2010-09-10 17:44:44 -07003171
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003172 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 -07003173
Mathias Agopian65ab4712010-07-14 17:59:35 -07003174 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003175 mAudioMixer->setBufferProvider(name, track);
3176 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003177
Glenn Kasten3b81aca2012-01-27 15:26:23 -08003178 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)vl);
3179 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)vr);
3180 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003181 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003182 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003183 AudioMixer::TRACK,
3184 AudioMixer::FORMAT, (void *)track->format());
3185 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003186 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003187 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003188 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003189 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003190 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003191 AudioMixer::RESAMPLE,
3192 AudioMixer::SAMPLE_RATE,
3193 (void *)(cblk->sampleRate));
3194 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003195 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003196 AudioMixer::TRACK,
3197 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
3198 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003199 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003200 AudioMixer::TRACK,
3201 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
3202
3203 // reset retry count
3204 track->mRetryCount = kMaxTrackRetries;
Glenn Kastenea7939a2012-03-14 12:56:26 -07003205
Eric Laurent27741442012-01-17 19:20:12 -08003206 // If one track is ready, set the mixer ready if:
3207 // - the mixer was not ready during previous round OR
3208 // - no other track is not ready
Glenn Kasten81028042012-04-30 18:15:12 -07003209 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003210 mixerStatus != MIXER_TRACKS_ENABLED) {
3211 mixerStatus = MIXER_TRACKS_READY;
3212 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003213 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003214 // clear effect chain input buffer if an active track underruns to avoid sending
3215 // previous audio buffer again to effects
3216 chain = getEffectChain_l(track->sessionId());
3217 if (chain != 0) {
3218 chain->clearInputBuffer();
3219 }
3220
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003221 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003222 if ((track->sharedBuffer() != 0) ||
Eric Laurent83faee02012-04-27 18:24:29 -07003223 track->isStopped() || track->isPaused()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003224 // We have consumed all the buffers of this track.
3225 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003226 // TODO: use actual buffer filling status instead of latency when available from
3227 // audio HAL
3228 size_t audioHALFrames =
3229 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3230 size_t framesWritten =
3231 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3232 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003233 if (track->isStopped()) {
3234 track->reset();
3235 }
Eric Laurenta011e352012-03-29 15:51:43 -07003236 tracksToRemove->add(track);
3237 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003238 } else {
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07003239 track->mUnderrunCount++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003240 // No buffers for this track. Give it a few chances to
3241 // fill a buffer, then remove it from active list.
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003242 if (--(track->mRetryCount) <= 0 || track->isTerminated()) {
3243 ALOGV_IF(track->mRetryCount <= 0, "BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003244 tracksToRemove->add(track);
Glenn Kasten288ed212012-04-25 17:52:27 -07003245 // indicate to client process that the track was disabled because of underrun;
3246 // it will then automatically call start() when data is available
Eric Laurent38ccae22011-03-28 18:37:07 -07003247 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08003248 // If one track is not ready, mark the mixer also not ready if:
3249 // - the mixer was ready during previous round OR
3250 // - no other track is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003251 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
Eric Laurent27741442012-01-17 19:20:12 -08003252 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003253 mixerStatus = MIXER_TRACKS_ENABLED;
3254 }
3255 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08003256 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003257 }
Glenn Kasten58912562012-04-03 10:45:00 -07003258
3259 } // local variable scope to avoid goto warning
3260track_is_ready: ;
3261
Mathias Agopian65ab4712010-07-14 17:59:35 -07003262 }
3263
Glenn Kasten288ed212012-04-25 17:52:27 -07003264 // Push the new FastMixer state if necessary
Glenn Kastenc15d6652012-05-30 14:52:57 -07003265 bool pauseAudioWatchdog = false;
Glenn Kasten288ed212012-04-25 17:52:27 -07003266 if (didModify) {
3267 state->mFastTracksGen++;
3268 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
3269 if (kUseFastMixer == FastMixer_Dynamic &&
3270 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
3271 state->mCommand = FastMixerState::COLD_IDLE;
3272 state->mColdFutexAddr = &mFastMixerFutex;
3273 state->mColdGen++;
3274 mFastMixerFutex = 0;
3275 if (kUseFastMixer == FastMixer_Dynamic) {
3276 mNormalSink = mOutputSink;
3277 }
3278 // If we go into cold idle, need to wait for acknowledgement
3279 // so that fast mixer stops doing I/O.
3280 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
Glenn Kastenc15d6652012-05-30 14:52:57 -07003281 pauseAudioWatchdog = true;
Glenn Kasten288ed212012-04-25 17:52:27 -07003282 }
3283 sq->end();
3284 }
3285 if (sq != NULL) {
3286 sq->end(didModify);
3287 sq->push(block);
3288 }
Glenn Kastenc15d6652012-05-30 14:52:57 -07003289 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
3290 mAudioWatchdog->pause();
3291 }
Glenn Kasten288ed212012-04-25 17:52:27 -07003292
3293 // Now perform the deferred reset on fast tracks that have stopped
3294 while (resetMask != 0) {
3295 size_t i = __builtin_ctz(resetMask);
3296 ALOG_ASSERT(i < count);
3297 resetMask &= ~(1 << i);
3298 sp<Track> t = mActiveTracks[i].promote();
3299 if (t == 0) continue;
3300 Track* track = t.get();
3301 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
3302 track->reset();
3303 }
Glenn Kasten58912562012-04-03 10:45:00 -07003304
Mathias Agopian65ab4712010-07-14 17:59:35 -07003305 // remove all the tracks that need to be...
3306 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08003307 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003308 for (size_t i=0 ; i<count ; i++) {
3309 const sp<Track>& track = tracksToRemove->itemAt(i);
3310 mActiveTracks.remove(track);
3311 if (track->mainBuffer() != mMixBuffer) {
3312 chain = getEffectChain_l(track->sessionId());
3313 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01003314 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07003315 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003316 }
3317 }
3318 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07003319 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003320 }
3321 }
3322 }
3323
3324 // mix buffer must be cleared if all tracks are connected to an
3325 // effect chain as in this case the mixer will not write to
3326 // mix buffer and track effects will accumulate into it
Glenn Kasten58912562012-04-03 10:45:00 -07003327 if ((mixedTracks != 0 && mixedTracks == tracksWithEffect) || (mixedTracks == 0 && fastTracks > 0)) {
3328 // FIXME as a performance optimization, should remember previous zero status
3329 memset(mMixBuffer, 0, mNormalFrameCount * mChannelCount * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003330 }
3331
Glenn Kasten58912562012-04-03 10:45:00 -07003332 // if any fast tracks, then status is ready
Glenn Kasten81028042012-04-30 18:15:12 -07003333 mMixerStatusIgnoringFastTracks = mixerStatus;
Glenn Kasten58912562012-04-03 10:45:00 -07003334 if (fastTracks > 0) {
3335 mixerStatus = MIXER_TRACKS_READY;
3336 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003337 return mixerStatus;
3338}
3339
Glenn Kasten66fcab92012-02-24 14:59:21 -08003340/*
3341The derived values that are cached:
3342 - mixBufferSize from frame count * frame size
3343 - activeSleepTime from activeSleepTimeUs()
3344 - idleSleepTime from idleSleepTimeUs()
3345 - standbyDelay from mActiveSleepTimeUs (DIRECT only)
3346 - maxPeriod from frame count and sample rate (MIXER only)
3347
3348The parameters that affect these derived values are:
3349 - frame count
3350 - frame size
3351 - sample rate
3352 - device type: A2DP or not
3353 - device latency
3354 - format: PCM or not
3355 - active sleep time
3356 - idle sleep time
3357*/
3358
3359void AudioFlinger::PlaybackThread::cacheParameters_l()
3360{
Glenn Kasten58912562012-04-03 10:45:00 -07003361 mixBufferSize = mNormalFrameCount * mFrameSize;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003362 activeSleepTime = activeSleepTimeUs();
3363 idleSleepTime = idleSleepTimeUs();
3364}
3365
Eric Laurent22167852012-06-20 12:26:32 -07003366void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003367{
Steve Block3856b092011-10-20 11:56:00 +01003368 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07003369 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003370 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07003371
Mathias Agopian65ab4712010-07-14 17:59:35 -07003372 size_t size = mTracks.size();
3373 for (size_t i = 0; i < size; i++) {
3374 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08003375 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07003376 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003377 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003378 }
3379 }
3380}
3381
Mathias Agopian65ab4712010-07-14 17:59:35 -07003382// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003383int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003384{
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -07003385 return mAudioMixer->getTrackName(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003386}
3387
3388// deleteTrackName_l() must be called with ThreadBase::mLock held
3389void AudioFlinger::MixerThread::deleteTrackName_l(int name)
3390{
Steve Block3856b092011-10-20 11:56:00 +01003391 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003392 mAudioMixer->deleteTrackName(name);
3393}
3394
3395// checkForNewParameters_l() must be called with ThreadBase::mLock held
3396bool AudioFlinger::MixerThread::checkForNewParameters_l()
3397{
Glenn Kasten58912562012-04-03 10:45:00 -07003398 // if !&IDLE, holds the FastMixer state to restore after new parameters processed
3399 FastMixerState::Command previousCommand = FastMixerState::HOT_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003400 bool reconfig = false;
3401
3402 while (!mNewParameters.isEmpty()) {
Glenn Kasten58912562012-04-03 10:45:00 -07003403
3404 if (mFastMixer != NULL) {
3405 FastMixerStateQueue *sq = mFastMixer->sq();
3406 FastMixerState *state = sq->begin();
3407 if (!(state->mCommand & FastMixerState::IDLE)) {
3408 previousCommand = state->mCommand;
3409 state->mCommand = FastMixerState::HOT_IDLE;
3410 sq->end();
3411 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3412 } else {
3413 sq->end(false /*didModify*/);
3414 }
3415 }
3416
Mathias Agopian65ab4712010-07-14 17:59:35 -07003417 status_t status = NO_ERROR;
3418 String8 keyValuePair = mNewParameters[0];
3419 AudioParameter param = AudioParameter(keyValuePair);
3420 int value;
3421
3422 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3423 reconfig = true;
3424 }
3425 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08003426 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003427 status = BAD_VALUE;
3428 } else {
3429 reconfig = true;
3430 }
3431 }
3432 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003433 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003434 status = BAD_VALUE;
3435 } else {
3436 reconfig = true;
3437 }
3438 }
3439 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3440 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08003441 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07003442 // if frame count is changed after track creation
3443 if (!mTracks.isEmpty()) {
3444 status = INVALID_OPERATION;
3445 } else {
3446 reconfig = true;
3447 }
3448 }
3449 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003450#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08003451 // when changing the audio output device, call addBatteryData to notify
3452 // the change
Glenn Kasten5ad92f62012-07-19 10:02:15 -07003453 if (mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003454 uint32_t params = 0;
3455 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07003456 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08003457 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
3458 }
3459
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003460 audio_devices_t deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07003461 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08003462 // check if any other device (except speaker) is on
3463 if (value & deviceWithoutSpeaker ) {
3464 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3465 }
3466
3467 if (params != 0) {
3468 addBatteryData(params);
3469 }
3470 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07003471#endif
Gloria Wang9ee159b2011-02-24 14:51:45 -08003472
Mathias Agopian65ab4712010-07-14 17:59:35 -07003473 // forward device change to effects that have requested to be
3474 // aware of attached audio device.
Glenn Kasten5ad92f62012-07-19 10:02:15 -07003475 mDevice = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003476 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07003477 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003478 }
3479 }
3480
3481 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003482 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003483 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003484 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003485 mOutput->stream->common.standby(&mOutput->stream->common);
3486 mStandby = true;
3487 mBytesWritten = 0;
3488 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003489 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003490 }
3491 if (status == NO_ERROR && reconfig) {
3492 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08003493 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
3494 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003495 readOutputParameters();
Glenn Kasten58912562012-04-03 10:45:00 -07003496 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003497 for (size_t i = 0; i < mTracks.size() ; i++) {
Glenn Kasten254af182012-07-03 14:59:05 -07003498 int name = getTrackName_l(mTracks[i]->mChannelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003499 if (name < 0) break;
3500 mTracks[i]->mName = name;
3501 // limit track sample rate to 2 x new output sample rate
3502 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
3503 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
3504 }
3505 }
3506 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3507 }
3508 }
3509
3510 mNewParameters.removeAt(0);
3511
3512 mParamStatus = status;
3513 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003514 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3515 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003516 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003517 }
Glenn Kasten58912562012-04-03 10:45:00 -07003518
3519 if (!(previousCommand & FastMixerState::IDLE)) {
3520 ALOG_ASSERT(mFastMixer != NULL);
3521 FastMixerStateQueue *sq = mFastMixer->sq();
3522 FastMixerState *state = sq->begin();
3523 ALOG_ASSERT(state->mCommand == FastMixerState::HOT_IDLE);
3524 state->mCommand = previousCommand;
3525 sq->end();
3526 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3527 }
3528
Mathias Agopian65ab4712010-07-14 17:59:35 -07003529 return reconfig;
3530}
3531
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07003532void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003533{
3534 const size_t SIZE = 256;
3535 char buffer[SIZE];
3536 String8 result;
3537
3538 PlaybackThread::dumpInternals(fd, args);
3539
3540 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
3541 result.append(buffer);
3542 write(fd, result.string(), result.size());
Glenn Kasten58912562012-04-03 10:45:00 -07003543
3544 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
3545 FastMixerDumpState copy = mFastMixerDumpState;
3546 copy.dump(fd);
3547
Glenn Kasten39993082012-05-31 13:40:27 -07003548#ifdef STATE_QUEUE_DUMP
3549 // Similar for state queue
3550 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
3551 observerCopy.dump(fd);
3552 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
3553 mutatorCopy.dump(fd);
3554#endif
3555
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003556 // Write the tee output to a .wav file
3557 NBAIO_Source *teeSource = mTeeSource.get();
3558 if (teeSource != NULL) {
3559 char teePath[64];
3560 struct timeval tv;
3561 gettimeofday(&tv, NULL);
3562 struct tm tm;
3563 localtime_r(&tv.tv_sec, &tm);
3564 strftime(teePath, sizeof(teePath), "/data/misc/media/%T.wav", &tm);
3565 int teeFd = open(teePath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
3566 if (teeFd >= 0) {
3567 char wavHeader[44];
3568 memcpy(wavHeader,
3569 "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",
3570 sizeof(wavHeader));
3571 NBAIO_Format format = teeSource->format();
3572 unsigned channelCount = Format_channelCount(format);
3573 ALOG_ASSERT(channelCount <= FCC_2);
3574 unsigned sampleRate = Format_sampleRate(format);
3575 wavHeader[22] = channelCount; // number of channels
3576 wavHeader[24] = sampleRate; // sample rate
3577 wavHeader[25] = sampleRate >> 8;
3578 wavHeader[32] = channelCount * 2; // block alignment
3579 write(teeFd, wavHeader, sizeof(wavHeader));
3580 size_t total = 0;
3581 bool firstRead = true;
3582 for (;;) {
3583#define TEE_SINK_READ 1024
3584 short buffer[TEE_SINK_READ * FCC_2];
3585 size_t count = TEE_SINK_READ;
John Grossman2c3b2da2012-08-02 17:08:54 -07003586 ssize_t actual = teeSource->read(buffer, count,
3587 AudioBufferProvider::kInvalidPTS);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003588 bool wasFirstRead = firstRead;
3589 firstRead = false;
3590 if (actual <= 0) {
3591 if (actual == (ssize_t) OVERRUN && wasFirstRead) {
3592 continue;
3593 }
3594 break;
3595 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07003596 ALOG_ASSERT(actual <= (ssize_t)count);
Glenn Kastenfbae5da2012-05-21 09:17:20 -07003597 write(teeFd, buffer, actual * channelCount * sizeof(short));
3598 total += actual;
3599 }
3600 lseek(teeFd, (off_t) 4, SEEK_SET);
3601 uint32_t temp = 44 + total * channelCount * sizeof(short) - 8;
3602 write(teeFd, &temp, sizeof(temp));
3603 lseek(teeFd, (off_t) 40, SEEK_SET);
3604 temp = total * channelCount * sizeof(short);
3605 write(teeFd, &temp, sizeof(temp));
3606 close(teeFd);
3607 fdprintf(fd, "FastMixer tee copied to %s\n", teePath);
3608 } else {
3609 fdprintf(fd, "FastMixer unable to create tee %s: \n", strerror(errno));
3610 }
3611 }
3612
Glenn Kastenc15d6652012-05-30 14:52:57 -07003613 if (mAudioWatchdog != 0) {
3614 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
3615 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
3616 wdCopy.dump(fd);
3617 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618}
3619
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003620uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003621{
Glenn Kasten58912562012-04-03 10:45:00 -07003622 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003623}
3624
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003625uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003626{
Glenn Kasten58912562012-04-03 10:45:00 -07003627 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003628}
3629
Glenn Kasten66fcab92012-02-24 14:59:21 -08003630void AudioFlinger::MixerThread::cacheParameters_l()
3631{
3632 PlaybackThread::cacheParameters_l();
3633
3634 // FIXME: Relaxed timing because of a certain device that can't meet latency
3635 // Should be reduced to 2x after the vendor fixes the driver issue
3636 // increase threshold again due to low power audio mode. The way this warning
3637 // threshold is calculated and its usefulness should be reconsidered anyway.
Glenn Kasten58912562012-04-03 10:45:00 -07003638 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
Glenn Kasten66fcab92012-02-24 14:59:21 -08003639}
3640
Mathias Agopian65ab4712010-07-14 17:59:35 -07003641// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003642AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07003643 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003644 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003645 // mLeftVolFloat, mRightVolFloat
Mathias Agopian65ab4712010-07-14 17:59:35 -07003646{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003647}
3648
3649AudioFlinger::DirectOutputThread::~DirectOutputThread()
3650{
3651}
3652
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003653AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
3654 Vector< sp<Track> > *tracksToRemove
Glenn Kasten000f0e32012-03-01 17:10:56 -08003655)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003656{
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003657 sp<Track> trackToRemove;
3658
Glenn Kastenfec279f2012-03-08 07:47:15 -08003659 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003660
Glenn Kasten952eeb22012-03-06 11:30:57 -08003661 // find out which tracks need to be processed
3662 if (mActiveTracks.size() != 0) {
3663 sp<Track> t = mActiveTracks[0].promote();
Glenn Kastenfec279f2012-03-08 07:47:15 -08003664 // The track died recently
3665 if (t == 0) return MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003666
Glenn Kasten952eeb22012-03-06 11:30:57 -08003667 Track* const track = t.get();
3668 audio_track_cblk_t* cblk = track->cblk();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003669
Glenn Kasten952eeb22012-03-06 11:30:57 -08003670 // The first time a track is added we wait
3671 // for all its buffers to be filled before processing it
Eric Laurent67c0a582012-05-01 19:31:12 -07003672 uint32_t minFrames;
3673 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing()) {
3674 minFrames = mNormalFrameCount;
3675 } else {
3676 minFrames = 1;
3677 }
3678 if ((track->framesReady() >= minFrames) && track->isReady() &&
Glenn Kasten952eeb22012-03-06 11:30:57 -08003679 !track->isPaused() && !track->isTerminated())
3680 {
3681 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003682
Glenn Kasten952eeb22012-03-06 11:30:57 -08003683 if (track->mFillingUpStatus == Track::FS_FILLED) {
3684 track->mFillingUpStatus = Track::FS_ACTIVE;
3685 mLeftVolFloat = mRightVolFloat = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003686 if (track->mState == TrackBase::RESUMING) {
3687 track->mState = TrackBase::ACTIVE;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003688 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003689 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003690
Glenn Kasten952eeb22012-03-06 11:30:57 -08003691 // compute volume for this track
3692 float left, right;
3693 if (track->isMuted() || mMasterMute || track->isPausing() ||
3694 mStreamTypes[track->streamType()].mute) {
3695 left = right = 0;
3696 if (track->isPausing()) {
3697 track->setPaused();
3698 }
3699 } else {
3700 float typeVolume = mStreamTypes[track->streamType()].volume;
3701 float v = mMasterVolume * typeVolume;
3702 uint32_t vlr = cblk->getVolumeLR();
3703 float v_clamped = v * (vlr & 0xFFFF);
3704 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3705 left = v_clamped/MAX_GAIN;
3706 v_clamped = v * (vlr >> 16);
3707 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
3708 right = v_clamped/MAX_GAIN;
3709 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003710
Glenn Kasten952eeb22012-03-06 11:30:57 -08003711 if (left != mLeftVolFloat || right != mRightVolFloat) {
3712 mLeftVolFloat = left;
3713 mRightVolFloat = right;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003714
Glenn Kasten952eeb22012-03-06 11:30:57 -08003715 // Convert volumes from float to 8.24
3716 uint32_t vl = (uint32_t)(left * (1 << 24));
3717 uint32_t vr = (uint32_t)(right * (1 << 24));
Mathias Agopian65ab4712010-07-14 17:59:35 -07003718
Glenn Kasten952eeb22012-03-06 11:30:57 -08003719 // Delegate volume control to effect in track effect chain if needed
3720 // only one effect chain can be present on DirectOutputThread, so if
3721 // there is one, the track is connected to it
3722 if (!mEffectChains.isEmpty()) {
3723 // Do not ramp volume if volume is controlled by effect
Eric Laurent67c0a582012-05-01 19:31:12 -07003724 mEffectChains[0]->setVolume_l(&vl, &vr);
3725 left = (float)vl / (1 << 24);
3726 right = (float)vr / (1 << 24);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003727 }
Eric Laurent67c0a582012-05-01 19:31:12 -07003728 mOutput->stream->set_volume(mOutput->stream, left, right);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003729 }
3730
3731 // reset retry count
3732 track->mRetryCount = kMaxTrackRetriesDirect;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003733 mActiveTrack = t;
Glenn Kastenfec279f2012-03-08 07:47:15 -08003734 mixerStatus = MIXER_TRACKS_READY;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003735 } else {
Eric Laurent91b14c42012-05-30 12:30:29 -07003736 // clear effect chain input buffer if an active track underruns to avoid sending
3737 // previous audio buffer again to effects
3738 if (!mEffectChains.isEmpty()) {
3739 mEffectChains[0]->clearInputBuffer();
3740 }
3741
Glenn Kasten952eeb22012-03-06 11:30:57 -08003742 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003743 if ((track->sharedBuffer() != 0) ||
Eric Laurent67c0a582012-05-01 19:31:12 -07003744 track->isStopped() || track->isPaused()) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003745 // We have consumed all the buffers of this track.
3746 // Remove it from the list of active tracks.
Eric Laurenta011e352012-03-29 15:51:43 -07003747 // TODO: implement behavior for compressed audio
3748 size_t audioHALFrames =
3749 (mOutput->stream->get_latency(mOutput->stream)*mSampleRate) / 1000;
3750 size_t framesWritten =
3751 mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
3752 if (track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurent29864602012-05-08 18:57:51 -07003753 if (track->isStopped()) {
3754 track->reset();
3755 }
Eric Laurenta011e352012-03-29 15:51:43 -07003756 trackToRemove = track;
3757 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003758 } else {
3759 // No buffers for this track. Give it a few chances to
3760 // fill a buffer, then remove it from active list.
Glenn Kasten44cda3a2012-08-01 09:40:18 -07003761 if (--(track->mRetryCount) <= 0 || track->isTerminated()) {
3762 ALOGV_IF(track->mRetryCount <= 0, "BUFFER TIMEOUT: remove(%d) from active list", track->name());
Glenn Kasten952eeb22012-03-06 11:30:57 -08003763 trackToRemove = track;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003764 } else {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003765 mixerStatus = MIXER_TRACKS_ENABLED;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003766 }
3767 }
Glenn Kasten952eeb22012-03-06 11:30:57 -08003768 }
3769 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003770
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003771 // FIXME merge this with similar code for removing multiple tracks
Glenn Kasten952eeb22012-03-06 11:30:57 -08003772 // remove all the tracks that need to be...
3773 if (CC_UNLIKELY(trackToRemove != 0)) {
Glenn Kasten1465f0c2012-03-06 11:23:32 -08003774 tracksToRemove->add(trackToRemove);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003775 mActiveTracks.remove(trackToRemove);
3776 if (!mEffectChains.isEmpty()) {
Glenn Kasten5798d4e2012-03-08 12:18:35 -08003777 ALOGV("stopping track on chain %p for session Id: %d", mEffectChains[0].get(),
Glenn Kasten952eeb22012-03-06 11:30:57 -08003778 trackToRemove->sessionId());
3779 mEffectChains[0]->decActiveTrackCnt();
3780 }
3781 if (trackToRemove->isTerminated()) {
3782 removeTrack_l(trackToRemove);
3783 }
3784 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003785
Glenn Kastenfec279f2012-03-08 07:47:15 -08003786 return mixerStatus;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003787}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003788
Glenn Kasten000f0e32012-03-01 17:10:56 -08003789void AudioFlinger::DirectOutputThread::threadLoop_mix()
3790{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003791 AudioBufferProvider::Buffer buffer;
3792 size_t frameCount = mFrameCount;
3793 int8_t *curBuf = (int8_t *)mMixBuffer;
3794 // output audio to hardware
3795 while (frameCount) {
3796 buffer.frameCount = frameCount;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003797 mActiveTrack->getNextBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003798 if (CC_UNLIKELY(buffer.raw == NULL)) {
3799 memset(curBuf, 0, frameCount * mFrameSize);
3800 break;
3801 }
3802 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
3803 frameCount -= buffer.frameCount;
3804 curBuf += buffer.frameCount * mFrameSize;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003805 mActiveTrack->releaseBuffer(&buffer);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003806 }
3807 sleepTime = 0;
3808 standbyTime = systemTime() + standbyDelay;
Glenn Kastenb071e9b2012-03-07 17:05:59 -08003809 mActiveTrack.clear();
Glenn Kasten73f4bc32012-03-09 12:08:48 -08003810
Glenn Kasten000f0e32012-03-01 17:10:56 -08003811}
3812
3813void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
3814{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003815 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003816 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003817 sleepTime = activeSleepTime;
3818 } else {
3819 sleepTime = idleSleepTime;
3820 }
3821 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Glenn Kasten58912562012-04-03 10:45:00 -07003822 memset(mMixBuffer, 0, mFrameCount * mFrameSize);
Glenn Kasten952eeb22012-03-06 11:30:57 -08003823 sleepTime = 0;
3824 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003825}
3826
3827// getTrackName_l() must be called with ThreadBase::mLock held
Jean-Michel Trivi7d5b2622012-04-04 18:54:36 -07003828int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003829{
3830 return 0;
3831}
3832
3833// deleteTrackName_l() must be called with ThreadBase::mLock held
3834void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
3835{
3836}
3837
3838// checkForNewParameters_l() must be called with ThreadBase::mLock held
3839bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
3840{
3841 bool reconfig = false;
3842
3843 while (!mNewParameters.isEmpty()) {
3844 status_t status = NO_ERROR;
3845 String8 keyValuePair = mNewParameters[0];
3846 AudioParameter param = AudioParameter(keyValuePair);
3847 int value;
3848
3849 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3850 // do not accept frame count changes if tracks are open as the track buffer
3851 // size depends on frame count and correct behavior would not be garantied
3852 // if frame count is changed after track creation
3853 if (!mTracks.isEmpty()) {
3854 status = INVALID_OPERATION;
3855 } else {
3856 reconfig = true;
3857 }
3858 }
3859 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003860 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003861 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003862 if (!mStandby && status == INVALID_OPERATION) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07003863 mOutput->stream->common.standby(&mOutput->stream->common);
3864 mStandby = true;
3865 mBytesWritten = 0;
3866 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07003867 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003868 }
3869 if (status == NO_ERROR && reconfig) {
3870 readOutputParameters();
3871 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
3872 }
3873 }
3874
3875 mNewParameters.removeAt(0);
3876
3877 mParamStatus = status;
3878 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07003879 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
3880 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08003881 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003882 }
3883 return reconfig;
3884}
3885
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003886uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003887{
3888 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003889 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08003890 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003891 } else {
3892 time = 10000;
3893 }
3894 return time;
3895}
3896
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003897uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07003898{
3899 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003900 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07003901 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003902 } else {
3903 time = 10000;
3904 }
3905 return time;
3906}
3907
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08003908uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003909{
3910 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07003911 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003912 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
3913 } else {
3914 time = 10000;
3915 }
3916 return time;
3917}
3918
Glenn Kasten66fcab92012-02-24 14:59:21 -08003919void AudioFlinger::DirectOutputThread::cacheParameters_l()
3920{
3921 PlaybackThread::cacheParameters_l();
3922
3923 // use shorter standby delay as on normal output to release
3924 // hardware resources as soon as possible
3925 standbyDelay = microseconds(activeSleepTime*2);
3926}
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003927
Mathias Agopian65ab4712010-07-14 17:59:35 -07003928// ----------------------------------------------------------------------------
3929
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003930AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08003931 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003932 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3933 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003934{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003935 addOutputTrack(mainThread);
3936}
3937
3938AudioFlinger::DuplicatingThread::~DuplicatingThread()
3939{
3940 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3941 mOutputTracks[i]->destroy();
3942 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003943}
3944
Glenn Kasten000f0e32012-03-01 17:10:56 -08003945void AudioFlinger::DuplicatingThread::threadLoop_mix()
Mathias Agopian65ab4712010-07-14 17:59:35 -07003946{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003947 // mix buffers...
3948 if (outputsReady(outputTracks)) {
3949 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
3950 } else {
3951 memset(mMixBuffer, 0, mixBufferSize);
3952 }
3953 sleepTime = 0;
Glenn Kasten58912562012-04-03 10:45:00 -07003954 writeFrames = mNormalFrameCount;
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003955 standbyTime = systemTime() + standbyDelay;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003956}
3957
3958void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
3959{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003960 if (sleepTime == 0) {
Glenn Kastenfec279f2012-03-08 07:47:15 -08003961 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Glenn Kasten952eeb22012-03-06 11:30:57 -08003962 sleepTime = activeSleepTime;
3963 } else {
3964 sleepTime = idleSleepTime;
3965 }
3966 } else if (mBytesWritten != 0) {
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003967 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
3968 writeFrames = mNormalFrameCount;
3969 memset(mMixBuffer, 0, mixBufferSize);
3970 } else {
3971 // flush remaining overflow buffers in output tracks
3972 writeFrames = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003973 }
Eric Laurenta4f7e0e2012-06-07 17:16:09 -07003974 sleepTime = 0;
Glenn Kasten952eeb22012-03-06 11:30:57 -08003975 }
Glenn Kasten000f0e32012-03-01 17:10:56 -08003976}
Mathias Agopian65ab4712010-07-14 17:59:35 -07003977
Glenn Kasten000f0e32012-03-01 17:10:56 -08003978void AudioFlinger::DuplicatingThread::threadLoop_write()
3979{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003980 for (size_t i = 0; i < outputTracks.size(); i++) {
3981 outputTracks[i]->write(mMixBuffer, writeFrames);
3982 }
3983 mBytesWritten += mixBufferSize;
Glenn Kasten000f0e32012-03-01 17:10:56 -08003984}
Glenn Kasten688a6402012-02-29 07:57:06 -08003985
Glenn Kasten000f0e32012-03-01 17:10:56 -08003986void AudioFlinger::DuplicatingThread::threadLoop_standby()
3987{
Glenn Kasten952eeb22012-03-06 11:30:57 -08003988 // DuplicatingThread implements standby by stopping all tracks
3989 for (size_t i = 0; i < outputTracks.size(); i++) {
3990 outputTracks[i]->stop();
3991 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003992}
3993
Glenn Kastenfa26a852012-03-06 11:28:04 -08003994void AudioFlinger::DuplicatingThread::saveOutputTracks()
3995{
3996 outputTracks = mOutputTracks;
3997}
3998
3999void AudioFlinger::DuplicatingThread::clearOutputTracks()
4000{
4001 outputTracks.clear();
4002}
4003
Mathias Agopian65ab4712010-07-14 17:59:35 -07004004void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
4005{
Glenn Kastenb6b74062012-02-24 14:12:20 -08004006 Mutex::Autolock _l(mLock);
Glenn Kasten99e53b82012-01-19 08:59:58 -08004007 // FIXME explain this formula
Glenn Kasten58912562012-04-03 10:45:00 -07004008 int frameCount = (3 * mNormalFrameCount * mSampleRate) / thread->sampleRate();
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004009 OutputTrack *outputTrack = new OutputTrack(thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004010 this,
4011 mSampleRate,
4012 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004013 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004014 frameCount);
4015 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004016 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004017 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01004018 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Glenn Kasten438b0362012-03-06 11:24:48 -08004019 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004020 }
4021}
4022
4023void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
4024{
4025 Mutex::Autolock _l(mLock);
4026 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08004027 if (mOutputTracks[i]->thread() == thread) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004028 mOutputTracks[i]->destroy();
4029 mOutputTracks.removeAt(i);
Glenn Kasten438b0362012-03-06 11:24:48 -08004030 updateWaitTime_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004031 return;
4032 }
4033 }
Steve Block3856b092011-10-20 11:56:00 +01004034 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004035}
4036
Glenn Kasten438b0362012-03-06 11:24:48 -08004037// caller must hold mLock
4038void AudioFlinger::DuplicatingThread::updateWaitTime_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004039{
4040 mWaitTimeMs = UINT_MAX;
4041 for (size_t i = 0; i < mOutputTracks.size(); i++) {
4042 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08004043 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004044 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
4045 if (waitTimeMs < mWaitTimeMs) {
4046 mWaitTimeMs = waitTimeMs;
4047 }
4048 }
4049 }
4050}
4051
4052
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08004053bool AudioFlinger::DuplicatingThread::outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004054{
4055 for (size_t i = 0; i < outputTracks.size(); i++) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004056 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004057 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004058 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004059 return false;
4060 }
4061 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Glenn Kasten01542f22012-07-02 12:46:15 -07004062 // see note at standby() declaration
Mathias Agopian65ab4712010-07-14 17:59:35 -07004063 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01004064 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004065 return false;
4066 }
4067 }
4068 return true;
4069}
4070
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08004071uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004072{
4073 return (mWaitTimeMs * 1000) / 2;
4074}
4075
Glenn Kasten66fcab92012-02-24 14:59:21 -08004076void AudioFlinger::DuplicatingThread::cacheParameters_l()
4077{
4078 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
4079 updateWaitTime_l();
4080
4081 MixerThread::cacheParameters_l();
4082}
4083
Mathias Agopian65ab4712010-07-14 17:59:35 -07004084// ----------------------------------------------------------------------------
4085
4086// TrackBase constructor must be called with AudioFlinger::mLock held
4087AudioFlinger::ThreadBase::TrackBase::TrackBase(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004088 ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004089 const sp<Client>& client,
4090 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004091 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004092 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004093 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004094 const sp<IMemory>& sharedBuffer,
4095 int sessionId)
4096 : RefBase(),
4097 mThread(thread),
4098 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004099 mCblk(NULL),
4100 // mBuffer
4101 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07004102 mFrameCount(0),
4103 mState(IDLE),
Glenn Kasten58912562012-04-03 10:45:00 -07004104 mSampleRate(sampleRate),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004105 mFormat(format),
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004106 mStepServerFailed(false),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004107 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004108 // mChannelCount
4109 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07004110{
Steve Block3856b092011-10-20 11:56:00 +01004111 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004112
Steve Blockb8a80522011-12-20 16:23:08 +00004113 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004114 size_t size = sizeof(audio_track_cblk_t);
4115 uint8_t channelCount = popcount(channelMask);
4116 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
4117 if (sharedBuffer == 0) {
4118 size += bufferSize;
4119 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004120
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004121 if (client != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004122 mCblkMemory = client->heap()->allocate(size);
4123 if (mCblkMemory != 0) {
4124 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08004125 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004126 new(mCblk) audio_track_cblk_t();
4127 // clear all buffers
4128 mCblk->frameCount = frameCount;
4129 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004130// uncomment the following lines to quickly test 32-bit wraparound
4131// mCblk->user = 0xffff0000;
4132// mCblk->server = 0xffff0000;
4133// mCblk->userBase = 0xffff0000;
4134// mCblk->serverBase = 0xffff0000;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004135 mChannelCount = channelCount;
4136 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004137 if (sharedBuffer == 0) {
4138 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4139 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4140 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07004141 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004142 mCblk->flags = CBLK_UNDERRUN_ON;
4143 } else {
4144 mBuffer = sharedBuffer->pointer();
4145 }
4146 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
4147 }
4148 } else {
Steve Block29357bc2012-01-06 19:20:56 +00004149 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004150 client->heap()->dump("AudioTrack");
4151 return;
4152 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004153 } else {
4154 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kastenea7939a2012-03-14 12:56:26 -07004155 // construct the shared structure in-place.
4156 new(mCblk) audio_track_cblk_t();
4157 // clear all buffers
4158 mCblk->frameCount = frameCount;
4159 mCblk->sampleRate = sampleRate;
Marco Nelissena1472d92012-03-30 14:36:54 -07004160// uncomment the following lines to quickly test 32-bit wraparound
4161// mCblk->user = 0xffff0000;
4162// mCblk->server = 0xffff0000;
4163// mCblk->userBase = 0xffff0000;
4164// mCblk->serverBase = 0xffff0000;
Glenn Kastenea7939a2012-03-14 12:56:26 -07004165 mChannelCount = channelCount;
4166 mChannelMask = channelMask;
4167 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
4168 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
4169 // Force underrun condition to avoid false underrun callback until first data is
4170 // written to buffer (other flags are cleared)
4171 mCblk->flags = CBLK_UNDERRUN_ON;
4172 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004173 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004174}
4175
4176AudioFlinger::ThreadBase::TrackBase::~TrackBase()
4177{
Glenn Kastena0d68332012-01-27 16:47:15 -08004178 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004179 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004180 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08004181 } else {
4182 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004183 }
4184 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08004185 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08004186 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004187 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07004188 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08004189 // If the client's reference count drops to zero, the associated destructor
4190 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
4191 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004192 mClient.clear();
4193 }
4194}
4195
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004196// AudioBufferProvider interface
4197// getNextBuffer() = 0;
4198// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
Mathias Agopian65ab4712010-07-14 17:59:35 -07004199void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4200{
Glenn Kastene0feee32011-12-13 11:53:26 -08004201 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004202 mFrameCount = buffer->frameCount;
Glenn Kasten288ed212012-04-25 17:52:27 -07004203 // FIXME See note at getNextBuffer()
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004204 (void) step(); // ignore return value of step()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004205 buffer->frameCount = 0;
4206}
4207
4208bool AudioFlinger::ThreadBase::TrackBase::step() {
4209 bool result;
4210 audio_track_cblk_t* cblk = this->cblk();
4211
4212 result = cblk->stepServer(mFrameCount);
4213 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01004214 ALOGV("stepServer failed acquiring cblk mutex");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004215 mStepServerFailed = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004216 }
4217 return result;
4218}
4219
4220void AudioFlinger::ThreadBase::TrackBase::reset() {
4221 audio_track_cblk_t* cblk = this->cblk();
4222
4223 cblk->user = 0;
4224 cblk->server = 0;
4225 cblk->userBase = 0;
4226 cblk->serverBase = 0;
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004227 mStepServerFailed = false;
Steve Block3856b092011-10-20 11:56:00 +01004228 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004229}
4230
Mathias Agopian65ab4712010-07-14 17:59:35 -07004231int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
4232 return (int)mCblk->sampleRate;
4233}
4234
Mathias Agopian65ab4712010-07-14 17:59:35 -07004235void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
4236 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08004237 size_t frameSize = cblk->frameSize;
4238 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
4239 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004240
4241 // Check validity of returned pointer in case the track control block would have been corrupted.
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004242 ALOG_ASSERT(!(bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd),
4243 "TrackBase::getBuffer buffer out of range:\n"
4244 " start: %p, end %p , mBuffer %p mBufferEnd %p\n"
4245 " server %u, serverBase %u, user %u, userBase %u, frameSize %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004246 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Triviacb86cc2012-04-16 12:43:57 -07004247 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, frameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004248
4249 return bufferStart;
4250}
4251
Eric Laurenta011e352012-03-29 15:51:43 -07004252status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
4253{
4254 mSyncEvents.add(event);
4255 return NO_ERROR;
4256}
4257
Mathias Agopian65ab4712010-07-14 17:59:35 -07004258// ----------------------------------------------------------------------------
4259
4260// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
4261AudioFlinger::PlaybackThread::Track::Track(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004262 PlaybackThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004263 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08004264 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004265 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004266 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004267 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004268 int frameCount,
4269 const sp<IMemory>& sharedBuffer,
Glenn Kasten73d22752012-03-19 13:38:30 -07004270 int sessionId,
4271 IAudioFlinger::track_flags_t flags)
Glenn Kasten5cf034d2012-02-21 10:35:56 -08004272 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, sessionId),
Glenn Kastenf9959012012-03-19 11:14:37 -07004273 mMute(false),
Glenn Kasten58912562012-04-03 10:45:00 -07004274 mFillingUpStatus(FS_INVALID),
Glenn Kastenf9959012012-03-19 11:14:37 -07004275 // mRetryCount initialized later when needed
4276 mSharedBuffer(sharedBuffer),
4277 mStreamType(streamType),
4278 mName(-1), // see note below
4279 mMainBuffer(thread->mixBuffer()),
4280 mAuxBuffer(NULL),
Eric Laurenta011e352012-03-29 15:51:43 -07004281 mAuxEffectId(0), mHasVolumeController(false),
Glenn Kasten73d22752012-03-19 13:38:30 -07004282 mPresentationCompleteFrames(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004283 mFlags(flags),
4284 mFastIndex(-1),
Glenn Kasten288ed212012-04-25 17:52:27 -07004285 mUnderrunCount(0),
Glenn Kasten58912562012-04-03 10:45:00 -07004286 mCachedVolume(1.0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004287{
4288 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004289 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
4290 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07004291 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Glenn Kasten893a0542012-05-30 10:32:06 -07004292 // to avoid leaking a track name, do not allocate one unless there is an mCblk
Glenn Kasten254af182012-07-03 14:59:05 -07004293 mName = thread->getTrackName_l(channelMask);
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004294 mCblk->mName = mName;
Glenn Kasten893a0542012-05-30 10:32:06 -07004295 if (mName < 0) {
4296 ALOGE("no more track names available");
4297 return;
4298 }
4299 // only allocate a fast track index if we were able to allocate a normal track name
Glenn Kasten58912562012-04-03 10:45:00 -07004300 if (flags & IAudioFlinger::TRACK_FAST) {
4301 mCblk->flags |= CBLK_FAST; // atomic op not needed yet
4302 ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
4303 int i = __builtin_ctz(thread->mFastTrackAvailMask);
Eric Laurent29864602012-05-08 18:57:51 -07004304 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
Glenn Kasten288ed212012-04-25 17:52:27 -07004305 // FIXME This is too eager. We allocate a fast track index before the
4306 // fast track becomes active. Since fast tracks are a scarce resource,
4307 // this means we are potentially denying other more important fast tracks from
4308 // being created. It would be better to allocate the index dynamically.
Glenn Kasten58912562012-04-03 10:45:00 -07004309 mFastIndex = i;
Glenn Kasten0c9d26d2012-05-31 14:35:01 -07004310 mCblk->mName = i;
Glenn Kasten288ed212012-04-25 17:52:27 -07004311 // Read the initial underruns because this field is never cleared by the fast mixer
Glenn Kasten09474df2012-05-10 14:48:07 -07004312 mObservedUnderruns = thread->getFastTrackUnderruns(i);
Glenn Kasten58912562012-04-03 10:45:00 -07004313 thread->mFastTrackAvailMask &= ~(1 << i);
Glenn Kasten58912562012-04-03 10:45:00 -07004314 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004315 }
Glenn Kastenf9959012012-03-19 11:14:37 -07004316 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004317}
4318
4319AudioFlinger::PlaybackThread::Track::~Track()
4320{
Steve Block3856b092011-10-20 11:56:00 +01004321 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004322}
4323
4324void AudioFlinger::PlaybackThread::Track::destroy()
4325{
4326 // NOTE: destroyTrack_l() can remove a strong reference to this Track
4327 // by removing it from mTracks vector, so there is a risk that this Tracks's
Glenn Kasten99e53b82012-01-19 08:59:58 -08004328 // destructor is called. As the destructor needs to lock mLock,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004329 // we must acquire a strong reference on this Track before locking mLock
4330 // here so that the destructor is called only when exiting this function.
4331 // On the other hand, as long as Track::destroy() is only called by
4332 // TrackHandle destructor, the TrackHandle still holds a strong ref on
4333 // this Track with its member mTrack.
4334 sp<Track> keep(this);
4335 { // scope for mLock
4336 sp<ThreadBase> thread = mThread.promote();
4337 if (thread != 0) {
4338 if (!isOutputTrack()) {
4339 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08004340 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08004341
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004342#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004343 // to track the speaker usage
4344 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004345#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004346 }
4347 AudioSystem::releaseOutput(thread->id());
4348 }
4349 Mutex::Autolock _l(thread->mLock);
4350 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4351 playbackThread->destroyTrack_l(this);
4352 }
4353 }
4354}
4355
Glenn Kasten288ed212012-04-25 17:52:27 -07004356/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
4357{
Glenn Kastene213c862012-04-25 13:46:15 -07004358 result.append(" Name Client Type Fmt Chn mask Session mFrCnt fCount S M F SRate L dB R dB "
Glenn Kastenbf0d21f2012-05-31 14:59:29 -07004359 " Server User Main buf Aux Buf Flags Underruns\n");
Glenn Kasten288ed212012-04-25 17:52:27 -07004360}
4361
Mathias Agopian65ab4712010-07-14 17:59:35 -07004362void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
4363{
Glenn Kasten83d86532012-01-17 14:39:34 -08004364 uint32_t vlr = mCblk->getVolumeLR();
Glenn Kasten58912562012-04-03 10:45:00 -07004365 if (isFastTrack()) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004366 sprintf(buffer, " F %2d", mFastIndex);
Glenn Kasten58912562012-04-03 10:45:00 -07004367 } else {
4368 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0);
4369 }
Glenn Kasten288ed212012-04-25 17:52:27 -07004370 track_state state = mState;
4371 char stateChar;
4372 switch (state) {
4373 case IDLE:
4374 stateChar = 'I';
4375 break;
4376 case TERMINATED:
4377 stateChar = 'T';
4378 break;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004379 case STOPPING_1:
4380 stateChar = 's';
4381 break;
4382 case STOPPING_2:
4383 stateChar = '5';
4384 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004385 case STOPPED:
4386 stateChar = 'S';
4387 break;
4388 case RESUMING:
4389 stateChar = 'R';
4390 break;
4391 case ACTIVE:
4392 stateChar = 'A';
4393 break;
4394 case PAUSING:
4395 stateChar = 'p';
4396 break;
4397 case PAUSED:
4398 stateChar = 'P';
4399 break;
Eric Laurent29864602012-05-08 18:57:51 -07004400 case FLUSHED:
4401 stateChar = 'F';
4402 break;
Glenn Kasten288ed212012-04-25 17:52:27 -07004403 default:
4404 stateChar = '?';
4405 break;
4406 }
Glenn Kasten09474df2012-05-10 14:48:07 -07004407 char nowInUnderrun;
4408 switch (mObservedUnderruns.mBitFields.mMostRecent) {
4409 case UNDERRUN_FULL:
4410 nowInUnderrun = ' ';
4411 break;
4412 case UNDERRUN_PARTIAL:
4413 nowInUnderrun = '<';
4414 break;
4415 case UNDERRUN_EMPTY:
4416 nowInUnderrun = '*';
4417 break;
4418 default:
4419 nowInUnderrun = '?';
4420 break;
4421 }
Glenn Kastene213c862012-04-25 13:46:15 -07004422 snprintf(&buffer[7], size-7, " %6d %4u %3u 0x%08x %7u %6u %6u %1c %1d %1d %5u %5.2g %5.2g "
4423 "0x%08x 0x%08x 0x%08x 0x%08x %#5x %9u%c\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08004424 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004425 mStreamType,
4426 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004427 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004428 mSessionId,
4429 mFrameCount,
Glenn Kastene213c862012-04-25 13:46:15 -07004430 mCblk->frameCount,
Glenn Kasten288ed212012-04-25 17:52:27 -07004431 stateChar,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004432 mMute,
4433 mFillingUpStatus,
4434 mCblk->sampleRate,
Glenn Kasten58912562012-04-03 10:45:00 -07004435 20.0 * log10((vlr & 0xFFFF) / 4096.0),
4436 20.0 * log10((vlr >> 16) / 4096.0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004437 mCblk->server,
4438 mCblk->user,
4439 (int)mMainBuffer,
Glenn Kasten288ed212012-04-25 17:52:27 -07004440 (int)mAuxBuffer,
Glenn Kastene213c862012-04-25 13:46:15 -07004441 mCblk->flags,
Glenn Kasten288ed212012-04-25 17:52:27 -07004442 mUnderrunCount,
Glenn Kasten09474df2012-05-10 14:48:07 -07004443 nowInUnderrun);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004444}
4445
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08004446// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08004447status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004448 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004449{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004450 audio_track_cblk_t* cblk = this->cblk();
4451 uint32_t framesReady;
4452 uint32_t framesReq = buffer->frameCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004453
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004454 // Check if last stepServer failed, try to step now
4455 if (mStepServerFailed) {
Glenn Kasten288ed212012-04-25 17:52:27 -07004456 // FIXME When called by fast mixer, this takes a mutex with tryLock().
4457 // Since the fast mixer is higher priority than client callback thread,
4458 // it does not result in priority inversion for client.
4459 // But a non-blocking solution would be preferable to avoid
4460 // fast mixer being unable to tryLock(), and
4461 // to avoid the extra context switches if the client wakes up,
4462 // discovers the mutex is locked, then has to wait for fast mixer to unlock.
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004463 if (!step()) goto getNextBuffer_exit;
4464 ALOGV("stepServer recovered");
4465 mStepServerFailed = false;
4466 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004467
Glenn Kasten288ed212012-04-25 17:52:27 -07004468 // FIXME Same as above
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004469 framesReady = cblk->framesReady();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004470
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004471 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004472 uint32_t s = cblk->server;
4473 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4474
4475 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
4476 if (framesReq > framesReady) {
4477 framesReq = framesReady;
4478 }
Marco Nelissena1472d92012-03-30 14:36:54 -07004479 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004480 framesReq = bufferEnd - s;
4481 }
4482
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004483 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004484 buffer->frameCount = framesReq;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004485 return NO_ERROR;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004486 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004487
4488getNextBuffer_exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004489 buffer->raw = NULL;
4490 buffer->frameCount = 0;
4491 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
4492 return NOT_ENOUGH_DATA;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004493}
4494
Glenn Kasten288ed212012-04-25 17:52:27 -07004495// Note that framesReady() takes a mutex on the control block using tryLock().
4496// This could result in priority inversion if framesReady() is called by the normal mixer,
4497// as the normal mixer thread runs at lower
4498// priority than the client's callback thread: there is a short window within framesReady()
4499// during which the normal mixer could be preempted, and the client callback would block.
4500// Another problem can occur if framesReady() is called by the fast mixer:
4501// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer.
4502// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue.
4503size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08004504 return mCblk->framesReady();
4505}
4506
Glenn Kasten288ed212012-04-25 17:52:27 -07004507// Don't call for fast tracks; the framesReady() could result in priority inversion
Mathias Agopian65ab4712010-07-14 17:59:35 -07004508bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07004509 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004510
John Grossman4ff14ba2012-02-08 16:37:41 -08004511 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004512 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
4513 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004514 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004515 return true;
4516 }
4517 return false;
4518}
4519
Glenn Kasten3acbd052012-02-28 10:39:56 -08004520status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07004521 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004522{
4523 status_t status = NO_ERROR;
Glenn Kasten58912562012-04-03 10:45:00 -07004524 ALOGV("start(%d), calling pid %d session %d",
4525 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Glenn Kasten3acbd052012-02-28 10:39:56 -08004526
Mathias Agopian65ab4712010-07-14 17:59:35 -07004527 sp<ThreadBase> thread = mThread.promote();
4528 if (thread != 0) {
4529 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004530 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004531 // here the track could be either new, or restarted
4532 // in both cases "unstop" the track
4533 if (mState == PAUSED) {
4534 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01004535 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004536 } else {
4537 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01004538 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004539 }
4540
4541 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
4542 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004543 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004544 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004545
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004546#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004547 // to track the speaker usage
4548 if (status == NO_ERROR) {
4549 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
4550 }
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004551#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004552 }
4553 if (status == NO_ERROR) {
4554 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4555 playbackThread->addTrack_l(this);
4556 } else {
4557 mState = state;
Eric Laurent29864602012-05-08 18:57:51 -07004558 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004559 }
4560 } else {
4561 status = BAD_VALUE;
4562 }
4563 return status;
4564}
4565
4566void AudioFlinger::PlaybackThread::Track::stop()
4567{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004568 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004569 sp<ThreadBase> thread = mThread.promote();
4570 if (thread != 0) {
4571 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08004572 track_state state = mState;
Glenn Kastend08f48c2012-05-01 18:14:02 -07004573 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004574 // If the track is not active (PAUSED and buffers full), flush buffers
4575 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4576 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4577 reset();
Glenn Kastend08f48c2012-05-01 18:14:02 -07004578 mState = STOPPED;
4579 } else if (!isFastTrack()) {
4580 mState = STOPPED;
4581 } else {
4582 // prepareTracks_l() will set state to STOPPING_2 after next underrun,
4583 // and then to STOPPED and reset() when presentation is complete
4584 mState = STOPPING_1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004585 }
Glenn Kastend08f48c2012-05-01 18:14:02 -07004586 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004587 }
4588 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
4589 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004590 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004591 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004592
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004593#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004594 // to track the speaker usage
4595 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004596#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004597 }
4598 }
4599}
4600
4601void AudioFlinger::PlaybackThread::Track::pause()
4602{
Glenn Kasten23d82a92012-02-03 11:10:00 -08004603 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004604 sp<ThreadBase> thread = mThread.promote();
4605 if (thread != 0) {
4606 Mutex::Autolock _l(thread->mLock);
4607 if (mState == ACTIVE || mState == RESUMING) {
4608 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01004609 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004610 if (!isOutputTrack()) {
4611 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08004612 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004613 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08004614
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004615#ifdef ADD_BATTERY_DATA
Gloria Wang9ee159b2011-02-24 14:51:45 -08004616 // to track the speaker usage
4617 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Glenn Kastend3cee2f2012-03-13 17:55:35 -07004618#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07004619 }
4620 }
4621 }
4622}
4623
4624void AudioFlinger::PlaybackThread::Track::flush()
4625{
Steve Block3856b092011-10-20 11:56:00 +01004626 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004627 sp<ThreadBase> thread = mThread.promote();
4628 if (thread != 0) {
4629 Mutex::Autolock _l(thread->mLock);
Glenn Kastend08f48c2012-05-01 18:14:02 -07004630 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && mState != PAUSED &&
4631 mState != PAUSING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004632 return;
4633 }
4634 // No point remaining in PAUSED state after a flush => go to
Eric Laurent29864602012-05-08 18:57:51 -07004635 // FLUSHED state
4636 mState = FLUSHED;
Eric Laurent38ccae22011-03-28 18:37:07 -07004637 // do not reset the track if it is still in the process of being stopped or paused.
4638 // this will be done by prepareTracks_l() when the track is stopped.
Eric Laurent29864602012-05-08 18:57:51 -07004639 // prepareTracks_l() will see mState == FLUSHED, then
Glenn Kastend08f48c2012-05-01 18:14:02 -07004640 // remove from active track list, reset(), and trigger presentation complete
Eric Laurent38ccae22011-03-28 18:37:07 -07004641 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4642 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
4643 reset();
4644 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004645 }
4646}
4647
4648void AudioFlinger::PlaybackThread::Track::reset()
4649{
4650 // Do not reset twice to avoid discarding data written just after a flush and before
4651 // the audioflinger thread detects the track is stopped.
4652 if (!mResetDone) {
4653 TrackBase::reset();
4654 // Force underrun condition to avoid false underrun callback until first data is
4655 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07004656 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
4657 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004658 mFillingUpStatus = FS_FILLING;
4659 mResetDone = true;
Eric Laurent29864602012-05-08 18:57:51 -07004660 if (mState == FLUSHED) {
4661 mState = IDLE;
4662 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004663 }
4664}
4665
4666void AudioFlinger::PlaybackThread::Track::mute(bool muted)
4667{
4668 mMute = muted;
4669}
4670
Mathias Agopian65ab4712010-07-14 17:59:35 -07004671status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
4672{
4673 status_t status = DEAD_OBJECT;
4674 sp<ThreadBase> thread = mThread.promote();
4675 if (thread != 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004676 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Eric Laurent717e1282012-06-29 16:36:52 -07004677 sp<AudioFlinger> af = mClient->audioFlinger();
4678
4679 Mutex::Autolock _l(af->mLock);
4680
4681 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent717e1282012-06-29 16:36:52 -07004682
Eric Laurent109347d2012-07-02 12:31:03 -07004683 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
Eric Laurent717e1282012-06-29 16:36:52 -07004684 Mutex::Autolock _dl(playbackThread->mLock);
4685 Mutex::Autolock _sl(srcThread->mLock);
4686 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4687 if (chain == 0) {
4688 return INVALID_OPERATION;
4689 }
4690
4691 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
4692 if (effect == 0) {
4693 return INVALID_OPERATION;
4694 }
4695 srcThread->removeEffect_l(effect);
4696 playbackThread->addEffect_l(effect);
4697 // removeEffect_l() has stopped the effect if it was active so it must be restarted
4698 if (effect->state() == EffectModule::ACTIVE ||
4699 effect->state() == EffectModule::STOPPING) {
4700 effect->start();
4701 }
4702
4703 sp<EffectChain> dstChain = effect->chain().promote();
4704 if (dstChain == 0) {
4705 srcThread->addEffect_l(effect);
4706 return INVALID_OPERATION;
4707 }
4708 AudioSystem::unregisterEffect(effect->id());
4709 AudioSystem::registerEffect(&effect->desc(),
4710 srcThread->id(),
4711 dstChain->strategy(),
4712 AUDIO_SESSION_OUTPUT_MIX,
4713 effect->id());
4714 }
Glenn Kastene53b9ea2012-03-12 16:29:55 -07004715 status = playbackThread->attachAuxEffect(this, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004716 }
4717 return status;
4718}
4719
4720void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
4721{
4722 mAuxEffectId = EffectId;
4723 mAuxBuffer = buffer;
4724}
4725
Eric Laurenta011e352012-03-29 15:51:43 -07004726bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
4727 size_t audioHalFrames)
4728{
4729 // a track is considered presented when the total number of frames written to audio HAL
4730 // corresponds to the number of frames written when presentationComplete() is called for the
4731 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
4732 if (mPresentationCompleteFrames == 0) {
4733 mPresentationCompleteFrames = framesWritten + audioHalFrames;
4734 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
4735 mPresentationCompleteFrames, audioHalFrames);
4736 }
4737 if (framesWritten >= mPresentationCompleteFrames) {
4738 ALOGV("presentationComplete() session %d complete: framesWritten %d",
4739 mSessionId, framesWritten);
4740 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Eric Laurenta011e352012-03-29 15:51:43 -07004741 return true;
4742 }
4743 return false;
4744}
4745
4746void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
4747{
4748 for (int i = 0; i < (int)mSyncEvents.size(); i++) {
4749 if (mSyncEvents[i]->type() == type) {
4750 mSyncEvents[i]->trigger();
4751 mSyncEvents.removeAt(i);
4752 i--;
4753 }
4754 }
4755}
4756
Glenn Kasten58912562012-04-03 10:45:00 -07004757// implement VolumeBufferProvider interface
4758
4759uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
4760{
4761 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
4762 ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
4763 uint32_t vlr = mCblk->getVolumeLR();
4764 uint32_t vl = vlr & 0xFFFF;
4765 uint32_t vr = vlr >> 16;
4766 // track volumes come from shared memory, so can't be trusted and must be clamped
4767 if (vl > MAX_GAIN_INT) {
4768 vl = MAX_GAIN_INT;
4769 }
4770 if (vr > MAX_GAIN_INT) {
4771 vr = MAX_GAIN_INT;
4772 }
4773 // now apply the cached master volume and stream type volume;
4774 // this is trusted but lacks any synchronization or barrier so may be stale
4775 float v = mCachedVolume;
4776 vl *= v;
4777 vr *= v;
4778 // re-combine into U4.16
4779 vlr = (vr << 16) | (vl & 0xFFFF);
4780 // FIXME look at mute, pause, and stop flags
4781 return vlr;
4782}
Eric Laurenta011e352012-03-29 15:51:43 -07004783
Eric Laurent29864602012-05-08 18:57:51 -07004784status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
4785{
4786 if (mState == TERMINATED || mState == PAUSED ||
4787 ((framesReady() == 0) && ((mSharedBuffer != 0) ||
4788 (mState == STOPPED)))) {
4789 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
4790 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
4791 event->cancel();
4792 return INVALID_OPERATION;
4793 }
Glenn Kastend23eedc2012-08-02 13:35:47 -07004794 (void) TrackBase::setSyncEvent(event);
Eric Laurent29864602012-05-08 18:57:51 -07004795 return NO_ERROR;
4796}
4797
John Grossman4ff14ba2012-02-08 16:37:41 -08004798// timed audio tracks
4799
4800sp<AudioFlinger::PlaybackThread::TimedTrack>
4801AudioFlinger::PlaybackThread::TimedTrack::create(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004802 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004803 const sp<Client>& client,
4804 audio_stream_type_t streamType,
4805 uint32_t sampleRate,
4806 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004807 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004808 int frameCount,
4809 const sp<IMemory>& sharedBuffer,
4810 int sessionId) {
4811 if (!client->reserveTimedTrack())
Glenn Kastend5903ec2012-03-18 10:33:27 -07004812 return 0;
John Grossman4ff14ba2012-02-08 16:37:41 -08004813
Glenn Kastena0356762012-03-19 10:38:51 -07004814 return new TimedTrack(
John Grossman4ff14ba2012-02-08 16:37:41 -08004815 thread, client, streamType, sampleRate, format, channelMask, frameCount,
4816 sharedBuffer, sessionId);
John Grossman4ff14ba2012-02-08 16:37:41 -08004817}
4818
4819AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08004820 PlaybackThread *thread,
John Grossman4ff14ba2012-02-08 16:37:41 -08004821 const sp<Client>& client,
4822 audio_stream_type_t streamType,
4823 uint32_t sampleRate,
4824 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07004825 audio_channel_mask_t channelMask,
John Grossman4ff14ba2012-02-08 16:37:41 -08004826 int frameCount,
4827 const sp<IMemory>& sharedBuffer,
4828 int sessionId)
4829 : Track(thread, client, streamType, sampleRate, format, channelMask,
Glenn Kasten73d22752012-03-19 13:38:30 -07004830 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
John Grossman9fbdee12012-03-26 17:51:46 -07004831 mQueueHeadInFlight(false),
4832 mTrimQueueHeadOnRelease(false),
John Grossman1c345192012-03-27 14:00:17 -07004833 mFramesPendingInQueue(0),
John Grossman4ff14ba2012-02-08 16:37:41 -08004834 mTimedSilenceBuffer(NULL),
4835 mTimedSilenceBufferSize(0),
4836 mTimedAudioOutputOnTime(false),
4837 mMediaTimeTransformValid(false)
4838{
4839 LocalClock lc;
4840 mLocalTimeFreq = lc.getLocalFreq();
4841
4842 mLocalTimeToSampleTransform.a_zero = 0;
4843 mLocalTimeToSampleTransform.b_zero = 0;
4844 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
4845 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
4846 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
4847 &mLocalTimeToSampleTransform.a_to_b_denom);
John Grossman9fbdee12012-03-26 17:51:46 -07004848
4849 mMediaTimeToSampleTransform.a_zero = 0;
4850 mMediaTimeToSampleTransform.b_zero = 0;
4851 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
4852 mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
4853 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
4854 &mMediaTimeToSampleTransform.a_to_b_denom);
John Grossman4ff14ba2012-02-08 16:37:41 -08004855}
4856
4857AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
4858 mClient->releaseTimedTrack();
4859 delete [] mTimedSilenceBuffer;
4860}
4861
4862status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
4863 size_t size, sp<IMemory>* buffer) {
4864
4865 Mutex::Autolock _l(mTimedBufferQueueLock);
4866
4867 trimTimedBufferQueue_l();
4868
4869 // lazily initialize the shared memory heap for timed buffers
4870 if (mTimedMemoryDealer == NULL) {
4871 const int kTimedBufferHeapSize = 512 << 10;
4872
4873 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
4874 "AudioFlingerTimed");
4875 if (mTimedMemoryDealer == NULL)
4876 return NO_MEMORY;
4877 }
4878
4879 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
4880 if (newBuffer == NULL) {
4881 newBuffer = mTimedMemoryDealer->allocate(size);
4882 if (newBuffer == NULL)
4883 return NO_MEMORY;
4884 }
4885
4886 *buffer = newBuffer;
4887 return NO_ERROR;
4888}
4889
4890// caller must hold mTimedBufferQueueLock
4891void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
4892 int64_t mediaTimeNow;
4893 {
4894 Mutex::Autolock mttLock(mMediaTimeTransformLock);
4895 if (!mMediaTimeTransformValid)
4896 return;
4897
4898 int64_t targetTimeNow;
4899 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
4900 ? mCCHelper.getCommonTime(&targetTimeNow)
4901 : mCCHelper.getLocalTime(&targetTimeNow);
4902
4903 if (OK != res)
4904 return;
4905
4906 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
4907 &mediaTimeNow)) {
4908 return;
4909 }
4910 }
4911
John Grossman1c345192012-03-27 14:00:17 -07004912 size_t trimEnd;
4913 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
John Grossman9fbdee12012-03-26 17:51:46 -07004914 int64_t bufEnd;
4915
John Grossmanc95cfbb2012-04-12 11:53:11 -07004916 if ((trimEnd + 1) < mTimedBufferQueue.size()) {
4917 // We have a next buffer. Just use its PTS as the PTS of the frame
4918 // following the last frame in this buffer. If the stream is sparse
4919 // (ie, there are deliberate gaps left in the stream which should be
4920 // filled with silence by the TimedAudioTrack), then this can result
4921 // in one extra buffer being left un-trimmed when it could have
4922 // been. In general, this is not typical, and we would rather
4923 // optimized away the TS calculation below for the more common case
4924 // where PTSes are contiguous.
4925 bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
4926 } else {
4927 // We have no next buffer. Compute the PTS of the frame following
4928 // the last frame in this buffer by computing the duration of of
4929 // this frame in media time units and adding it to the PTS of the
4930 // buffer.
4931 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
4932 / mCblk->frameSize;
4933
4934 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
4935 &bufEnd)) {
4936 ALOGE("Failed to convert frame count of %lld to media time"
4937 " duration" " (scale factor %d/%u) in %s",
4938 frameCount,
4939 mMediaTimeToSampleTransform.a_to_b_numer,
4940 mMediaTimeToSampleTransform.a_to_b_denom,
4941 __PRETTY_FUNCTION__);
4942 break;
4943 }
4944 bufEnd += mTimedBufferQueue[trimEnd].pts();
John Grossman9fbdee12012-03-26 17:51:46 -07004945 }
John Grossman9fbdee12012-03-26 17:51:46 -07004946
4947 if (bufEnd > mediaTimeNow)
4948 break;
4949
4950 // Is the buffer we want to use in the middle of a mix operation right
4951 // now? If so, don't actually trim it. Just wait for the releaseBuffer
4952 // from the mixer which should be coming back shortly.
John Grossman1c345192012-03-27 14:00:17 -07004953 if (!trimEnd && mQueueHeadInFlight) {
John Grossman9fbdee12012-03-26 17:51:46 -07004954 mTrimQueueHeadOnRelease = true;
4955 }
John Grossman4ff14ba2012-02-08 16:37:41 -08004956 }
4957
John Grossman9fbdee12012-03-26 17:51:46 -07004958 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
John Grossman1c345192012-03-27 14:00:17 -07004959 if (trimStart < trimEnd) {
4960 // Update the bookkeeping for framesReady()
4961 for (size_t i = trimStart; i < trimEnd; ++i) {
4962 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
4963 }
4964
4965 // Now actually remove the buffers from the queue.
4966 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
John Grossman4ff14ba2012-02-08 16:37:41 -08004967 }
4968}
4969
John Grossman1c345192012-03-27 14:00:17 -07004970void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
4971 const char* logTag) {
John Grossmand3030da2012-04-12 11:56:36 -07004972 ALOG_ASSERT(mTimedBufferQueue.size() > 0,
4973 "%s called (reason \"%s\"), but timed buffer queue has no"
4974 " elements to trim.", __FUNCTION__, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004975
4976 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
4977 mTimedBufferQueue.removeAt(0);
4978}
4979
4980void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
4981 const TimedBuffer& buf,
4982 const char* logTag) {
4983 uint32_t bufBytes = buf.buffer()->size();
4984 uint32_t consumedAlready = buf.position();
4985
Eric Laurentb388e532012-04-14 13:32:48 -07004986 ALOG_ASSERT(consumedAlready <= bufBytes,
John Grossmand3030da2012-04-12 11:56:36 -07004987 "Bad bookkeeping while updating frames pending. Timed buffer is"
4988 " only %u bytes long, but claims to have consumed %u"
4989 " bytes. (update reason: \"%s\")",
Eric Laurentb388e532012-04-14 13:32:48 -07004990 bufBytes, consumedAlready, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004991
4992 uint32_t bufFrames = (bufBytes - consumedAlready) / mCblk->frameSize;
John Grossmand3030da2012-04-12 11:56:36 -07004993 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
4994 "Bad bookkeeping while updating frames pending. Should have at"
4995 " least %u queued frames, but we think we have only %u. (update"
4996 " reason: \"%s\")",
4997 bufFrames, mFramesPendingInQueue, logTag);
John Grossman1c345192012-03-27 14:00:17 -07004998
4999 mFramesPendingInQueue -= bufFrames;
5000}
5001
John Grossman4ff14ba2012-02-08 16:37:41 -08005002status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
5003 const sp<IMemory>& buffer, int64_t pts) {
5004
5005 {
5006 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5007 if (!mMediaTimeTransformValid)
5008 return INVALID_OPERATION;
5009 }
5010
5011 Mutex::Autolock _l(mTimedBufferQueueLock);
5012
John Grossman1c345192012-03-27 14:00:17 -07005013 uint32_t bufFrames = buffer->size() / mCblk->frameSize;
5014 mFramesPendingInQueue += bufFrames;
John Grossman4ff14ba2012-02-08 16:37:41 -08005015 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
5016
5017 return NO_ERROR;
5018}
5019
5020status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
5021 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
5022
John Grossman1c345192012-03-27 14:00:17 -07005023 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
5024 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
5025 target);
John Grossman4ff14ba2012-02-08 16:37:41 -08005026
5027 if (!(target == TimedAudioTrack::LOCAL_TIME ||
5028 target == TimedAudioTrack::COMMON_TIME)) {
5029 return BAD_VALUE;
5030 }
5031
5032 Mutex::Autolock lock(mMediaTimeTransformLock);
5033 mMediaTimeTransform = xform;
5034 mMediaTimeTransformTarget = target;
5035 mMediaTimeTransformValid = true;
5036
5037 return NO_ERROR;
5038}
5039
5040#define min(a, b) ((a) < (b) ? (a) : (b))
5041
5042// implementation of getNextBuffer for tracks whose buffers have timestamps
5043status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
5044 AudioBufferProvider::Buffer* buffer, int64_t pts)
5045{
5046 if (pts == AudioBufferProvider::kInvalidPTS) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005047 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005048 buffer->frameCount = 0;
John Grossman8d314b72012-04-19 12:08:17 -07005049 mTimedAudioOutputOnTime = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005050 return INVALID_OPERATION;
5051 }
5052
John Grossman4ff14ba2012-02-08 16:37:41 -08005053 Mutex::Autolock _l(mTimedBufferQueueLock);
5054
John Grossman9fbdee12012-03-26 17:51:46 -07005055 ALOG_ASSERT(!mQueueHeadInFlight,
5056 "getNextBuffer called without releaseBuffer!");
5057
John Grossman4ff14ba2012-02-08 16:37:41 -08005058 while (true) {
5059
5060 // if we have no timed buffers, then fail
5061 if (mTimedBufferQueue.isEmpty()) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005062 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005063 buffer->frameCount = 0;
5064 return NOT_ENOUGH_DATA;
5065 }
5066
5067 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
5068
5069 // calculate the PTS of the head of the timed buffer queue expressed in
5070 // local time
5071 int64_t headLocalPTS;
5072 {
5073 Mutex::Autolock mttLock(mMediaTimeTransformLock);
5074
Glenn Kasten5798d4e2012-03-08 12:18:35 -08005075 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
John Grossman4ff14ba2012-02-08 16:37:41 -08005076
5077 if (mMediaTimeTransform.a_to_b_denom == 0) {
5078 // the transform represents a pause, so yield silence
John Grossman9fbdee12012-03-26 17:51:46 -07005079 timedYieldSilence_l(buffer->frameCount, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005080 return NO_ERROR;
5081 }
5082
5083 int64_t transformedPTS;
5084 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
5085 &transformedPTS)) {
5086 // the transform failed. this shouldn't happen, but if it does
5087 // then just drop this buffer
5088 ALOGW("timedGetNextBuffer transform failed");
Glenn Kastend5903ec2012-03-18 10:33:27 -07005089 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005090 buffer->frameCount = 0;
John Grossman1c345192012-03-27 14:00:17 -07005091 trimTimedBufferQueueHead_l("getNextBuffer; no transform");
John Grossman4ff14ba2012-02-08 16:37:41 -08005092 return NO_ERROR;
5093 }
5094
5095 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
5096 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
5097 &headLocalPTS)) {
Glenn Kastend5903ec2012-03-18 10:33:27 -07005098 buffer->raw = NULL;
John Grossman4ff14ba2012-02-08 16:37:41 -08005099 buffer->frameCount = 0;
5100 return INVALID_OPERATION;
5101 }
5102 } else {
5103 headLocalPTS = transformedPTS;
5104 }
5105 }
5106
5107 // adjust the head buffer's PTS to reflect the portion of the head buffer
5108 // that has already been consumed
5109 int64_t effectivePTS = headLocalPTS +
5110 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
5111
5112 // Calculate the delta in samples between the head of the input buffer
5113 // queue and the start of the next output buffer that will be written.
5114 // If the transformation fails because of over or underflow, it means
5115 // that the sample's position in the output stream is so far out of
5116 // whack that it should just be dropped.
5117 int64_t sampleDelta;
5118 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
5119 ALOGV("*** head buffer is too far from PTS: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005120 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
5121 " mix");
John Grossman4ff14ba2012-02-08 16:37:41 -08005122 continue;
5123 }
5124 if (!mLocalTimeToSampleTransform.doForwardTransform(
5125 (effectivePTS - pts) << 32, &sampleDelta)) {
John Grossmand3030da2012-04-12 11:56:36 -07005126 ALOGV("*** too late during sample rate transform: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005127 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
John Grossman4ff14ba2012-02-08 16:37:41 -08005128 continue;
5129 }
5130
John Grossman1c345192012-03-27 14:00:17 -07005131 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
5132 " sampleDelta=[%d.%08x]",
5133 head.pts(), head.position(), pts,
5134 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
5135 + (sampleDelta >> 32)),
5136 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
John Grossman4ff14ba2012-02-08 16:37:41 -08005137
5138 // if the delta between the ideal placement for the next input sample and
5139 // the current output position is within this threshold, then we will
5140 // concatenate the next input samples to the previous output
5141 const int64_t kSampleContinuityThreshold =
John Grossman8d314b72012-04-19 12:08:17 -07005142 (static_cast<int64_t>(sampleRate()) << 32) / 250;
John Grossman4ff14ba2012-02-08 16:37:41 -08005143
5144 // if this is the first buffer of audio that we're emitting from this track
5145 // then it should be almost exactly on time.
5146 const int64_t kSampleStartupThreshold = 1LL << 32;
5147
5148 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
John Grossman8d314b72012-04-19 12:08:17 -07005149 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005150 // the next input is close enough to being on time, so concatenate it
5151 // with the last output
John Grossman9fbdee12012-03-26 17:51:46 -07005152 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005153
John Grossman1c345192012-03-27 14:00:17 -07005154 ALOGVV("*** on time: head.pos=%d frameCount=%u",
5155 head.position(), buffer->frameCount);
John Grossman4ff14ba2012-02-08 16:37:41 -08005156 return NO_ERROR;
John Grossman8d314b72012-04-19 12:08:17 -07005157 }
5158
5159 // Looks like our output is not on time. Reset our on timed status.
5160 // Next time we mix samples from our input queue, then should be within
5161 // the StartupThreshold.
5162 mTimedAudioOutputOnTime = false;
5163 if (sampleDelta > 0) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005164 // the gap between the current output position and the proper start of
5165 // the next input sample is too big, so fill it with silence
5166 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
5167
John Grossman9fbdee12012-03-26 17:51:46 -07005168 timedYieldSilence_l(framesUntilNextInput, buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005169 ALOGV("*** silence: frameCount=%u", buffer->frameCount);
5170 return NO_ERROR;
5171 } else {
5172 // the next input sample is late
5173 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
5174 size_t onTimeSamplePosition =
5175 head.position() + lateFrames * mCblk->frameSize;
5176
5177 if (onTimeSamplePosition > head.buffer()->size()) {
5178 // all the remaining samples in the head are too late, so
5179 // drop it and move on
5180 ALOGV("*** too late: dropped buffer");
John Grossman1c345192012-03-27 14:00:17 -07005181 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
John Grossman4ff14ba2012-02-08 16:37:41 -08005182 continue;
5183 } else {
5184 // skip over the late samples
5185 head.setPosition(onTimeSamplePosition);
5186
5187 // yield the available samples
John Grossman9fbdee12012-03-26 17:51:46 -07005188 timedYieldSamples_l(buffer);
John Grossman4ff14ba2012-02-08 16:37:41 -08005189
5190 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
5191 return NO_ERROR;
5192 }
5193 }
5194 }
5195}
5196
5197// Yield samples from the timed buffer queue head up to the given output
5198// buffer's capacity.
5199//
5200// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005201void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005202 AudioBufferProvider::Buffer* buffer) {
5203
5204 const TimedBuffer& head = mTimedBufferQueue[0];
5205
5206 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
5207 head.position());
5208
5209 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
5210 mCblk->frameSize);
5211 size_t framesRequested = buffer->frameCount;
5212 buffer->frameCount = min(framesLeftInHead, framesRequested);
5213
John Grossman9fbdee12012-03-26 17:51:46 -07005214 mQueueHeadInFlight = true;
John Grossman4ff14ba2012-02-08 16:37:41 -08005215 mTimedAudioOutputOnTime = true;
5216}
5217
5218// Yield samples of silence up to the given output buffer's capacity
5219//
5220// Caller must hold mTimedBufferQueueLock
John Grossman9fbdee12012-03-26 17:51:46 -07005221void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
John Grossman4ff14ba2012-02-08 16:37:41 -08005222 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
5223
5224 // lazily allocate a buffer filled with silence
5225 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
5226 delete [] mTimedSilenceBuffer;
5227 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
5228 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
5229 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
5230 }
5231
5232 buffer->raw = mTimedSilenceBuffer;
5233 size_t framesRequested = buffer->frameCount;
5234 buffer->frameCount = min(numFrames, framesRequested);
5235
5236 mTimedAudioOutputOnTime = false;
5237}
5238
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005239// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005240void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
5241 AudioBufferProvider::Buffer* buffer) {
5242
5243 Mutex::Autolock _l(mTimedBufferQueueLock);
5244
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005245 // If the buffer which was just released is part of the buffer at the head
5246 // of the queue, be sure to update the amt of the buffer which has been
5247 // consumed. If the buffer being returned is not part of the head of the
5248 // queue, its either because the buffer is part of the silence buffer, or
5249 // because the head of the timed queue was trimmed after the mixer called
5250 // getNextBuffer but before the mixer called releaseBuffer.
John Grossman9fbdee12012-03-26 17:51:46 -07005251 if (buffer->raw == mTimedSilenceBuffer) {
5252 ALOG_ASSERT(!mQueueHeadInFlight,
5253 "Queue head in flight during release of silence buffer!");
5254 goto done;
5255 }
5256
5257 ALOG_ASSERT(mQueueHeadInFlight,
5258 "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
5259 " head in flight.");
5260
5261 if (mTimedBufferQueue.size()) {
John Grossman4ff14ba2012-02-08 16:37:41 -08005262 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005263
5264 void* start = head.buffer()->pointer();
John Grossman9fbdee12012-03-26 17:51:46 -07005265 void* end = reinterpret_cast<void*>(
5266 reinterpret_cast<uint8_t*>(head.buffer()->pointer())
5267 + head.buffer()->size());
John Grossmanfe5b3ba2012-02-12 17:51:21 -08005268
John Grossman9fbdee12012-03-26 17:51:46 -07005269 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
5270 "released buffer not within the head of the timed buffer"
5271 " queue; qHead = [%p, %p], released buffer = %p",
5272 start, end, buffer->raw);
5273
5274 head.setPosition(head.position() +
5275 (buffer->frameCount * mCblk->frameSize));
5276 mQueueHeadInFlight = false;
5277
John Grossman1c345192012-03-27 14:00:17 -07005278 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
5279 "Bad bookkeeping during releaseBuffer! Should have at"
5280 " least %u queued frames, but we think we have only %u",
5281 buffer->frameCount, mFramesPendingInQueue);
5282
5283 mFramesPendingInQueue -= buffer->frameCount;
5284
John Grossman9fbdee12012-03-26 17:51:46 -07005285 if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
5286 || mTrimQueueHeadOnRelease) {
John Grossman1c345192012-03-27 14:00:17 -07005287 trimTimedBufferQueueHead_l("releaseBuffer");
John Grossman9fbdee12012-03-26 17:51:46 -07005288 mTrimQueueHeadOnRelease = false;
John Grossman4ff14ba2012-02-08 16:37:41 -08005289 }
John Grossman9fbdee12012-03-26 17:51:46 -07005290 } else {
5291 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
5292 " buffers in the timed buffer queue");
John Grossman4ff14ba2012-02-08 16:37:41 -08005293 }
5294
John Grossman9fbdee12012-03-26 17:51:46 -07005295done:
John Grossman4ff14ba2012-02-08 16:37:41 -08005296 buffer->raw = 0;
5297 buffer->frameCount = 0;
5298}
5299
Glenn Kasten288ed212012-04-25 17:52:27 -07005300size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
John Grossman4ff14ba2012-02-08 16:37:41 -08005301 Mutex::Autolock _l(mTimedBufferQueueLock);
John Grossman1c345192012-03-27 14:00:17 -07005302 return mFramesPendingInQueue;
John Grossman4ff14ba2012-02-08 16:37:41 -08005303}
5304
5305AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
5306 : mPTS(0), mPosition(0) {}
5307
5308AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
5309 const sp<IMemory>& buffer, int64_t pts)
5310 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
5311
Mathias Agopian65ab4712010-07-14 17:59:35 -07005312// ----------------------------------------------------------------------------
5313
5314// RecordTrack constructor must be called with AudioFlinger::mLock held
5315AudioFlinger::RecordThread::RecordTrack::RecordTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005316 RecordThread *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005317 const sp<Client>& client,
5318 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005319 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005320 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005321 int frameCount,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005322 int sessionId)
5323 : TrackBase(thread, client, sampleRate, format,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005324 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005325 mOverflow(false)
5326{
5327 if (mCblk != NULL) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005328 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
5329 if (format == AUDIO_FORMAT_PCM_16_BIT) {
5330 mCblk->frameSize = mChannelCount * sizeof(int16_t);
5331 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
5332 mCblk->frameSize = mChannelCount * sizeof(int8_t);
5333 } else {
5334 mCblk->frameSize = sizeof(int8_t);
5335 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005336 }
5337}
5338
5339AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
5340{
Glenn Kasten510a3d62012-07-16 14:24:34 -07005341 ALOGV("%s", __func__);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005342}
5343
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08005344// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08005345status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005346{
5347 audio_track_cblk_t* cblk = this->cblk();
5348 uint32_t framesAvail;
5349 uint32_t framesReq = buffer->frameCount;
5350
Glenn Kastene53b9ea2012-03-12 16:29:55 -07005351 // Check if last stepServer failed, try to step now
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005352 if (mStepServerFailed) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005353 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01005354 ALOGV("stepServer recovered");
Glenn Kasten5cf034d2012-02-21 10:35:56 -08005355 mStepServerFailed = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005356 }
5357
5358 framesAvail = cblk->framesAvailable_l();
5359
Glenn Kastenf6b16782011-12-15 09:51:17 -08005360 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005361 uint32_t s = cblk->server;
5362 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
5363
5364 if (framesReq > framesAvail) {
5365 framesReq = framesAvail;
5366 }
Marco Nelissena1472d92012-03-30 14:36:54 -07005367 if (framesReq > bufferEnd - s) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005368 framesReq = bufferEnd - s;
5369 }
5370
5371 buffer->raw = getBuffer(s, framesReq);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372 buffer->frameCount = framesReq;
5373 return NO_ERROR;
5374 }
5375
5376getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08005377 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005378 buffer->frameCount = 0;
5379 return NOT_ENOUGH_DATA;
5380}
5381
Glenn Kasten3acbd052012-02-28 10:39:56 -08005382status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005383 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005384{
5385 sp<ThreadBase> thread = mThread.promote();
5386 if (thread != 0) {
5387 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten3acbd052012-02-28 10:39:56 -08005388 return recordThread->start(this, event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005389 } else {
5390 return BAD_VALUE;
5391 }
5392}
5393
5394void AudioFlinger::RecordThread::RecordTrack::stop()
5395{
5396 sp<ThreadBase> thread = mThread.promote();
5397 if (thread != 0) {
5398 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten1d491ff2012-07-16 14:28:13 -07005399 recordThread->mLock.lock();
5400 bool doStop = recordThread->stop_l(this);
5401 if (doStop) {
5402 TrackBase::reset();
5403 // Force overrun condition to avoid false overrun callback until first data is
5404 // read from buffer
5405 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
5406 }
5407 recordThread->mLock.unlock();
5408 if (doStop) {
5409 AudioSystem::stopInput(recordThread->id());
5410 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005411 }
5412}
5413
Glenn Kasten510a3d62012-07-16 14:24:34 -07005414/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
5415{
5416 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
5417}
5418
Mathias Agopian65ab4712010-07-14 17:59:35 -07005419void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
5420{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005421 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08005422 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005423 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005424 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005425 mSessionId,
5426 mFrameCount,
5427 mState,
5428 mCblk->sampleRate,
5429 mCblk->server,
5430 mCblk->user);
5431}
5432
5433
5434// ----------------------------------------------------------------------------
5435
5436AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
Glenn Kasten9eaa5572012-01-20 13:32:16 -08005437 PlaybackThread *playbackThread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005438 DuplicatingThread *sourceThread,
5439 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005440 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005441 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005442 int frameCount)
Glenn Kasten73d22752012-03-19 13:38:30 -07005443 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
5444 NULL, 0, IAudioFlinger::TRACK_DEFAULT),
Mathias Agopian65ab4712010-07-14 17:59:35 -07005445 mActive(false), mSourceThread(sourceThread)
5446{
5447
Mathias Agopian65ab4712010-07-14 17:59:35 -07005448 if (mCblk != NULL) {
5449 mCblk->flags |= CBLK_DIRECTION_OUT;
5450 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005451 mOutBuffer.frameCount = 0;
5452 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01005453 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005454 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
5455 mCblk, mBuffer, mCblk->buffers,
5456 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005457 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005458 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005459 }
5460}
5461
5462AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
5463{
5464 clearBufferQueue();
5465}
5466
Glenn Kasten3acbd052012-02-28 10:39:56 -08005467status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07005468 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005469{
Glenn Kasten3acbd052012-02-28 10:39:56 -08005470 status_t status = Track::start(event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005471 if (status != NO_ERROR) {
5472 return status;
5473 }
5474
5475 mActive = true;
5476 mRetryCount = 127;
5477 return status;
5478}
5479
5480void AudioFlinger::PlaybackThread::OutputTrack::stop()
5481{
5482 Track::stop();
5483 clearBufferQueue();
5484 mOutBuffer.frameCount = 0;
5485 mActive = false;
5486}
5487
5488bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
5489{
5490 Buffer *pInBuffer;
5491 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005492 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005493 bool outputBufferFull = false;
5494 inBuffer.frameCount = frames;
5495 inBuffer.i16 = data;
5496
5497 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
5498
5499 if (!mActive && frames != 0) {
Glenn Kasten3acbd052012-02-28 10:39:56 -08005500 start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005501 sp<ThreadBase> thread = mThread.promote();
5502 if (thread != 0) {
5503 MixerThread *mixerThread = (MixerThread *)thread.get();
5504 if (mCblk->frameCount > frames){
5505 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5506 uint32_t startFrames = (mCblk->frameCount - frames);
5507 pInBuffer = new Buffer;
5508 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
5509 pInBuffer->frameCount = startFrames;
5510 pInBuffer->i16 = pInBuffer->mBuffer;
5511 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
5512 mBufferQueue.add(pInBuffer);
5513 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005514 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005515 }
5516 }
5517 }
5518 }
5519
5520 while (waitTimeLeftMs) {
5521 // First write pending buffers, then new data
5522 if (mBufferQueue.size()) {
5523 pInBuffer = mBufferQueue.itemAt(0);
5524 } else {
5525 pInBuffer = &inBuffer;
5526 }
5527
5528 if (pInBuffer->frameCount == 0) {
5529 break;
5530 }
5531
5532 if (mOutBuffer.frameCount == 0) {
5533 mOutBuffer.frameCount = pInBuffer->frameCount;
5534 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08005535 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01005536 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005537 outputBufferFull = true;
5538 break;
5539 }
5540 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
5541 if (waitTimeLeftMs >= waitTimeMs) {
5542 waitTimeLeftMs -= waitTimeMs;
5543 } else {
5544 waitTimeLeftMs = 0;
5545 }
5546 }
5547
5548 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
5549 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
5550 mCblk->stepUser(outFrames);
5551 pInBuffer->frameCount -= outFrames;
5552 pInBuffer->i16 += outFrames * channelCount;
5553 mOutBuffer.frameCount -= outFrames;
5554 mOutBuffer.i16 += outFrames * channelCount;
5555
5556 if (pInBuffer->frameCount == 0) {
5557 if (mBufferQueue.size()) {
5558 mBufferQueue.removeAt(0);
5559 delete [] pInBuffer->mBuffer;
5560 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01005561 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005562 } else {
5563 break;
5564 }
5565 }
5566 }
5567
5568 // If we could not write all frames, allocate a buffer and queue it for next time.
5569 if (inBuffer.frameCount) {
5570 sp<ThreadBase> thread = mThread.promote();
5571 if (thread != 0 && !thread->standby()) {
5572 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
5573 pInBuffer = new Buffer;
5574 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
5575 pInBuffer->frameCount = inBuffer.frameCount;
5576 pInBuffer->i16 = pInBuffer->mBuffer;
5577 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
5578 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01005579 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005580 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005581 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005582 }
5583 }
5584 }
5585
5586 // Calling write() with a 0 length buffer, means that no more data will be written:
5587 // If no more buffers are pending, fill output track buffer to make sure it is started
5588 // by output mixer.
5589 if (frames == 0 && mBufferQueue.size() == 0) {
5590 if (mCblk->user < mCblk->frameCount) {
5591 frames = mCblk->frameCount - mCblk->user;
5592 pInBuffer = new Buffer;
5593 pInBuffer->mBuffer = new int16_t[frames * channelCount];
5594 pInBuffer->frameCount = frames;
5595 pInBuffer->i16 = pInBuffer->mBuffer;
5596 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
5597 mBufferQueue.add(pInBuffer);
5598 } else if (mActive) {
5599 stop();
5600 }
5601 }
5602
5603 return outputBufferFull;
5604}
5605
5606status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
5607{
5608 int active;
5609 status_t result;
5610 audio_track_cblk_t* cblk = mCblk;
5611 uint32_t framesReq = buffer->frameCount;
5612
Steve Block3856b092011-10-20 11:56:00 +01005613// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005614 buffer->frameCount = 0;
5615
5616 uint32_t framesAvail = cblk->framesAvailable();
5617
5618
5619 if (framesAvail == 0) {
5620 Mutex::Autolock _l(cblk->lock);
5621 goto start_loop_here;
5622 while (framesAvail == 0) {
5623 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08005624 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01005625 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08005626 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005627 }
5628 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
5629 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005630 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005631 }
5632 // read the server count again
5633 start_loop_here:
5634 framesAvail = cblk->framesAvailable_l();
5635 }
5636 }
5637
5638// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08005639// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005640// }
5641
5642 if (framesReq > framesAvail) {
5643 framesReq = framesAvail;
5644 }
5645
5646 uint32_t u = cblk->user;
5647 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
5648
Marco Nelissena1472d92012-03-30 14:36:54 -07005649 if (framesReq > bufferEnd - u) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005650 framesReq = bufferEnd - u;
5651 }
5652
5653 buffer->frameCount = framesReq;
5654 buffer->raw = (void *)cblk->buffer(u);
5655 return NO_ERROR;
5656}
5657
5658
5659void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
5660{
5661 size_t size = mBufferQueue.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005662
5663 for (size_t i = 0; i < size; i++) {
Glenn Kastena1117922012-01-26 10:53:32 -08005664 Buffer *pBuffer = mBufferQueue.itemAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005665 delete [] pBuffer->mBuffer;
5666 delete pBuffer;
5667 }
5668 mBufferQueue.clear();
5669}
5670
5671// ----------------------------------------------------------------------------
5672
5673AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
5674 : RefBase(),
5675 mAudioFlinger(audioFlinger),
Glenn Kasten99e53b82012-01-19 08:59:58 -08005676 // 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 -07005677 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
John Grossman4ff14ba2012-02-08 16:37:41 -08005678 mPid(pid),
5679 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005680{
5681 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
5682}
5683
5684// Client destructor must be called with AudioFlinger::mLock held
5685AudioFlinger::Client::~Client()
5686{
5687 mAudioFlinger->removeClient_l(mPid);
5688}
5689
Glenn Kasten435dbe62012-01-30 10:15:48 -08005690sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005691{
5692 return mMemoryDealer;
5693}
5694
John Grossman4ff14ba2012-02-08 16:37:41 -08005695// Reserve one of the limited slots for a timed audio track associated
5696// with this client
5697bool AudioFlinger::Client::reserveTimedTrack()
5698{
5699 const int kMaxTimedTracksPerClient = 4;
5700
5701 Mutex::Autolock _l(mTimedTrackLock);
5702
5703 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
5704 ALOGW("can not create timed track - pid %d has exceeded the limit",
5705 mPid);
5706 return false;
5707 }
5708
5709 mTimedTrackCount++;
5710 return true;
5711}
5712
5713// Release a slot for a timed audio track
5714void AudioFlinger::Client::releaseTimedTrack()
5715{
5716 Mutex::Autolock _l(mTimedTrackLock);
5717 mTimedTrackCount--;
5718}
5719
Mathias Agopian65ab4712010-07-14 17:59:35 -07005720// ----------------------------------------------------------------------------
5721
5722AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
5723 const sp<IAudioFlingerClient>& client,
5724 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005725 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005726{
5727}
5728
5729AudioFlinger::NotificationClient::~NotificationClient()
5730{
Mathias Agopian65ab4712010-07-14 17:59:35 -07005731}
5732
5733void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
5734{
5735 sp<NotificationClient> keep(this);
Glenn Kastena1117922012-01-26 10:53:32 -08005736 mAudioFlinger->removeNotificationClient(mPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005737}
5738
5739// ----------------------------------------------------------------------------
5740
5741AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
5742 : BnAudioTrack(),
5743 mTrack(track)
5744{
5745}
5746
5747AudioFlinger::TrackHandle::~TrackHandle() {
5748 // just stop the track on deletion, associated resources
5749 // will be freed from the main thread once all pending buffers have
5750 // been played. Unless it's not in the active track list, in which
5751 // case we free everything now...
5752 mTrack->destroy();
5753}
5754
Glenn Kasten90716c52012-01-26 13:40:12 -08005755sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
5756 return mTrack->getCblk();
5757}
5758
Glenn Kasten3acbd052012-02-28 10:39:56 -08005759status_t AudioFlinger::TrackHandle::start() {
5760 return mTrack->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005761}
5762
5763void AudioFlinger::TrackHandle::stop() {
5764 mTrack->stop();
5765}
5766
5767void AudioFlinger::TrackHandle::flush() {
5768 mTrack->flush();
5769}
5770
5771void AudioFlinger::TrackHandle::mute(bool e) {
5772 mTrack->mute(e);
5773}
5774
5775void AudioFlinger::TrackHandle::pause() {
5776 mTrack->pause();
5777}
5778
Mathias Agopian65ab4712010-07-14 17:59:35 -07005779status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
5780{
5781 return mTrack->attachAuxEffect(EffectId);
5782}
5783
John Grossman4ff14ba2012-02-08 16:37:41 -08005784status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
5785 sp<IMemory>* buffer) {
5786 if (!mTrack->isTimedTrack())
5787 return INVALID_OPERATION;
5788
5789 PlaybackThread::TimedTrack* tt =
5790 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5791 return tt->allocateTimedBuffer(size, buffer);
5792}
5793
5794status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
5795 int64_t pts) {
5796 if (!mTrack->isTimedTrack())
5797 return INVALID_OPERATION;
5798
5799 PlaybackThread::TimedTrack* tt =
5800 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5801 return tt->queueTimedBuffer(buffer, pts);
5802}
5803
5804status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
5805 const LinearTransform& xform, int target) {
5806
5807 if (!mTrack->isTimedTrack())
5808 return INVALID_OPERATION;
5809
5810 PlaybackThread::TimedTrack* tt =
5811 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
5812 return tt->setMediaTimeTransform(
5813 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
5814}
5815
Mathias Agopian65ab4712010-07-14 17:59:35 -07005816status_t AudioFlinger::TrackHandle::onTransact(
5817 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5818{
5819 return BnAudioTrack::onTransact(code, data, reply, flags);
5820}
5821
5822// ----------------------------------------------------------------------------
5823
5824sp<IAudioRecord> AudioFlinger::openRecord(
5825 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005826 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005827 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005828 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07005829 audio_channel_mask_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005830 int frameCount,
Glenn Kastena075db42012-03-06 11:22:44 -08005831 IAudioFlinger::track_flags_t flags,
Glenn Kasten1879fff2012-07-11 15:36:59 -07005832 pid_t tid,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005833 int *sessionId,
5834 status_t *status)
5835{
5836 sp<RecordThread::RecordTrack> recordTrack;
5837 sp<RecordHandle> recordHandle;
5838 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005839 status_t lStatus;
5840 RecordThread *thread;
5841 size_t inFrameCount;
5842 int lSessionId;
5843
5844 // check calling permissions
5845 if (!recordingAllowed()) {
5846 lStatus = PERMISSION_DENIED;
5847 goto Exit;
5848 }
5849
5850 // add client to list
5851 { // scope for mLock
5852 Mutex::Autolock _l(mLock);
5853 thread = checkRecordThread_l(input);
5854 if (thread == NULL) {
5855 lStatus = BAD_VALUE;
5856 goto Exit;
5857 }
5858
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005859 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005860
5861 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07005862 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005863 lSessionId = *sessionId;
5864 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005865 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005866 if (sessionId != NULL) {
5867 *sessionId = lSessionId;
5868 }
5869 }
5870 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Glenn Kasten1879fff2012-07-11 15:36:59 -07005871 recordTrack = thread->createRecordTrack_l(client, sampleRate, format, channelMask,
5872 frameCount, lSessionId, flags, tid, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005873 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005874 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005875 // remove local strong reference to Client before deleting the RecordTrack so that the Client
5876 // destructor is called by the TrackBase destructor with mLock held
5877 client.clear();
5878 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005879 goto Exit;
5880 }
5881
5882 // return to handle to client
5883 recordHandle = new RecordHandle(recordTrack);
5884 lStatus = NO_ERROR;
5885
5886Exit:
5887 if (status) {
5888 *status = lStatus;
5889 }
5890 return recordHandle;
5891}
5892
5893// ----------------------------------------------------------------------------
5894
5895AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
5896 : BnAudioRecord(),
5897 mRecordTrack(recordTrack)
5898{
5899}
5900
5901AudioFlinger::RecordHandle::~RecordHandle() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005902 stop_nonvirtual();
Glenn Kasten510a3d62012-07-16 14:24:34 -07005903 mRecordTrack->destroy();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005904}
5905
Glenn Kasten90716c52012-01-26 13:40:12 -08005906sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
5907 return mRecordTrack->getCblk();
5908}
5909
Glenn Kasten0ec23ce2012-07-10 12:56:08 -07005910status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event, int triggerSession) {
Steve Block3856b092011-10-20 11:56:00 +01005911 ALOGV("RecordHandle::start()");
Glenn Kasten3acbd052012-02-28 10:39:56 -08005912 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005913}
5914
5915void AudioFlinger::RecordHandle::stop() {
Glenn Kastend96c5722012-04-25 13:44:49 -07005916 stop_nonvirtual();
5917}
5918
5919void AudioFlinger::RecordHandle::stop_nonvirtual() {
Steve Block3856b092011-10-20 11:56:00 +01005920 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005921 mRecordTrack->stop();
5922}
5923
Mathias Agopian65ab4712010-07-14 17:59:35 -07005924status_t AudioFlinger::RecordHandle::onTransact(
5925 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5926{
5927 return BnAudioRecord::onTransact(code, data, reply, flags);
5928}
5929
5930// ----------------------------------------------------------------------------
5931
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005932AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5933 AudioStreamIn *input,
5934 uint32_t sampleRate,
Glenn Kasten254af182012-07-03 14:59:05 -07005935 audio_channel_mask_t channelMask,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005936 audio_io_handle_t id,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07005937 audio_devices_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08005938 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten510a3d62012-07-16 14:24:34 -07005939 mInput(input), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005940 // mRsmpInIndex and mInputBytes set by readInputParameters()
Glenn Kasten254af182012-07-03 14:59:05 -07005941 mReqChannelCount(popcount(channelMask)),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005942 mReqSampleRate(sampleRate)
5943 // mBytesRead is only meaningful while active, and so is cleared in start()
5944 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005945{
Glenn Kasten480b4682012-02-28 12:30:08 -08005946 snprintf(mName, kNameLength, "AudioIn_%X", id);
Eric Laurentfeb0db62011-07-22 09:04:31 -07005947
Mathias Agopian65ab4712010-07-14 17:59:35 -07005948 readInputParameters();
5949}
5950
5951
5952AudioFlinger::RecordThread::~RecordThread()
5953{
5954 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08005955 delete mResampler;
5956 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005957}
5958
5959void AudioFlinger::RecordThread::onFirstRef()
5960{
Eric Laurentfeb0db62011-07-22 09:04:31 -07005961 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005962}
5963
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005964status_t AudioFlinger::RecordThread::readyToRun()
5965{
5966 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00005967 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005968 return status;
5969}
5970
Mathias Agopian65ab4712010-07-14 17:59:35 -07005971bool AudioFlinger::RecordThread::threadLoop()
5972{
5973 AudioBufferProvider::Buffer buffer;
5974 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005975 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005976
Eric Laurent44d98482010-09-30 16:12:31 -07005977 nsecs_t lastWarning = 0;
5978
Glenn Kastene4e2a372012-07-23 12:55:09 -07005979 inputStandBy();
Eric Laurentfeb0db62011-07-22 09:04:31 -07005980 acquireWakeLock();
5981
Mathias Agopian65ab4712010-07-14 17:59:35 -07005982 // start recording
5983 while (!exitPending()) {
5984
5985 processConfigEvents();
5986
5987 { // scope for mLock
5988 Mutex::Autolock _l(mLock);
5989 checkForNewParameters_l();
5990 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07005991 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005992
5993 if (exitPending()) break;
5994
Eric Laurentfeb0db62011-07-22 09:04:31 -07005995 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01005996 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005997 // go to sleep
5998 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005999 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07006000 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006001 continue;
6002 }
6003 if (mActiveTrack != 0) {
6004 if (mActiveTrack->mState == TrackBase::PAUSING) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006005 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006006 mActiveTrack.clear();
6007 mStartStopCond.broadcast();
6008 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
6009 if (mReqChannelCount != mActiveTrack->channelCount()) {
6010 mActiveTrack.clear();
6011 mStartStopCond.broadcast();
6012 } else if (mBytesRead != 0) {
6013 // record start succeeds only if first read from audio input
6014 // succeeds
6015 if (mBytesRead > 0) {
6016 mActiveTrack->mState = TrackBase::ACTIVE;
6017 } else {
6018 mActiveTrack.clear();
6019 }
6020 mStartStopCond.broadcast();
6021 }
6022 mStandby = false;
Glenn Kasten510a3d62012-07-16 14:24:34 -07006023 } else if (mActiveTrack->mState == TrackBase::TERMINATED) {
6024 removeTrack_l(mActiveTrack);
6025 mActiveTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006026 }
6027 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006028 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006029 }
6030
6031 if (mActiveTrack != 0) {
6032 if (mActiveTrack->mState != TrackBase::ACTIVE &&
6033 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006034 unlockEffectChains(effectChains);
6035 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006036 continue;
6037 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006038 for (size_t i = 0; i < effectChains.size(); i ++) {
6039 effectChains[i]->process_l();
6040 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006041
Mathias Agopian65ab4712010-07-14 17:59:35 -07006042 buffer.frameCount = mFrameCount;
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006043 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006044 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08006045 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006046 // no resampling
6047 while (framesOut) {
6048 size_t framesIn = mFrameCount - mRsmpInIndex;
6049 if (framesIn) {
6050 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
6051 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
6052 if (framesIn > framesOut)
6053 framesIn = framesOut;
6054 mRsmpInIndex += framesIn;
6055 framesOut -= framesIn;
6056 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07006057 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006058 memcpy(dst, src, framesIn * mFrameSize);
6059 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006060 if (mChannelCount == 1) {
Glenn Kasten69d79962012-07-19 14:02:22 -07006061 upmix_to_stereo_i16_from_mono_i16((int16_t *)dst,
6062 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006063 } else {
Glenn Kasten69d79962012-07-19 14:02:22 -07006064 downmix_to_mono_i16_from_stereo_i16((int16_t *)dst,
6065 (int16_t *)src, framesIn);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006066 }
6067 }
6068 }
6069 if (framesOut && mFrameCount == mRsmpInIndex) {
6070 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006071 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006072 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006073 framesOut = 0;
6074 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07006075 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006076 mRsmpInIndex = 0;
6077 }
6078 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006079 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006080 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6081 // Force input into standby so that it tries to
6082 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006083 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006084 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006085 }
6086 mRsmpInIndex = mFrameCount;
6087 framesOut = 0;
6088 buffer.frameCount = 0;
6089 }
6090 }
6091 }
6092 } else {
6093 // resampling
6094
6095 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
6096 // alter output frame count as if we were expecting stereo samples
6097 if (mChannelCount == 1 && mReqChannelCount == 1) {
6098 framesOut >>= 1;
6099 }
6100 mResampler->resample(mRsmpOutBuffer, framesOut, this);
6101 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
6102 // are 32 bit aligned which should be always true.
6103 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006104 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006105 // the resampler always outputs stereo samples: do post stereo to mono conversion
Glenn Kasten69d79962012-07-19 14:02:22 -07006106 downmix_to_mono_i16_from_stereo_i16(buffer.i16, (int16_t *)mRsmpOutBuffer,
6107 framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006108 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006109 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006110 }
6111
6112 }
Eric Laurenta011e352012-03-29 15:51:43 -07006113 if (mFramestoDrop == 0) {
6114 mActiveTrack->releaseBuffer(&buffer);
6115 } else {
6116 if (mFramestoDrop > 0) {
6117 mFramestoDrop -= buffer.frameCount;
Eric Laurent29864602012-05-08 18:57:51 -07006118 if (mFramestoDrop <= 0) {
6119 clearSyncStartEvent();
6120 }
6121 } else {
6122 mFramestoDrop += buffer.frameCount;
6123 if (mFramestoDrop >= 0 || mSyncStartEvent == 0 ||
6124 mSyncStartEvent->isCancelled()) {
6125 ALOGW("Synced record %s, session %d, trigger session %d",
6126 (mFramestoDrop >= 0) ? "timed out" : "cancelled",
6127 mActiveTrack->sessionId(),
6128 (mSyncStartEvent != 0) ? mSyncStartEvent->triggerSession() : 0);
6129 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006130 }
6131 }
6132 }
Glenn Kasten04270da2012-07-10 12:55:49 -07006133 mActiveTrack->clearOverflow();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006134 }
6135 // client isn't retrieving buffers fast enough
6136 else {
Eric Laurent44d98482010-09-30 16:12:31 -07006137 if (!mActiveTrack->setOverflow()) {
6138 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08006139 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006140 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07006141 lastWarning = now;
6142 }
6143 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006144 // Release the processor for a while before asking for a new buffer.
6145 // This will give the application more chance to read from the buffer and
6146 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006147 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006148 }
6149 }
Eric Laurentec437d82011-07-26 20:54:46 -07006150 // enable changes in effect chain
6151 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006152 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006153 }
6154
Glenn Kastene4e2a372012-07-23 12:55:09 -07006155 standby();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006156
Glenn Kasten33e6e352012-07-16 15:56:57 -07006157 {
6158 Mutex::Autolock _l(mLock);
6159 mActiveTrack.clear();
6160 mStartStopCond.broadcast();
6161 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006162
Eric Laurentfeb0db62011-07-22 09:04:31 -07006163 releaseWakeLock();
6164
Steve Block3856b092011-10-20 11:56:00 +01006165 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006166 return false;
6167}
6168
Glenn Kastene4e2a372012-07-23 12:55:09 -07006169void AudioFlinger::RecordThread::standby()
6170{
6171 if (!mStandby) {
6172 inputStandBy();
6173 mStandby = true;
6174 }
6175}
6176
6177void AudioFlinger::RecordThread::inputStandBy()
6178{
6179 mInput->stream->common.standby(&mInput->stream->common);
6180}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006181
6182sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
6183 const sp<AudioFlinger::Client>& client,
6184 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08006185 audio_format_t format,
Glenn Kasten254af182012-07-03 14:59:05 -07006186 audio_channel_mask_t channelMask,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006187 int frameCount,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006188 int sessionId,
Glenn Kasten1879fff2012-07-11 15:36:59 -07006189 IAudioFlinger::track_flags_t flags,
6190 pid_t tid,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006191 status_t *status)
6192{
6193 sp<RecordTrack> track;
6194 status_t lStatus;
6195
6196 lStatus = initCheck();
6197 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00006198 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006199 goto Exit;
6200 }
6201
Glenn Kasten1879fff2012-07-11 15:36:59 -07006202 // FIXME use flags and tid similar to createTrack_l()
6203
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006204 { // scope for mLock
6205 Mutex::Autolock _l(mLock);
6206
6207 track = new RecordTrack(this, client, sampleRate,
Glenn Kasten5cf034d2012-02-21 10:35:56 -08006208 format, channelMask, frameCount, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006209
Glenn Kasten7378ca52012-01-20 13:44:40 -08006210 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006211 lStatus = NO_MEMORY;
6212 goto Exit;
6213 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006214 mTracks.add(track);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006215
Eric Laurent59bd0da2011-08-01 09:52:20 -07006216 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006217 bool suspend = audio_is_bluetooth_sco_device(mDevice & AUDIO_DEVICE_IN_ALL) &&
6218 mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07006219 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6220 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006221 }
6222 lStatus = NO_ERROR;
6223
6224Exit:
6225 if (status) {
6226 *status = lStatus;
6227 }
6228 return track;
6229}
6230
Eric Laurenta011e352012-03-29 15:51:43 -07006231status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
Glenn Kasten3acbd052012-02-28 10:39:56 -08006232 AudioSystem::sync_event_t event,
Eric Laurenta011e352012-03-29 15:51:43 -07006233 int triggerSession)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006234{
Glenn Kasten58912562012-04-03 10:45:00 -07006235 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006236 sp<ThreadBase> strongMe = this;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006237 status_t status = NO_ERROR;
Eric Laurenta011e352012-03-29 15:51:43 -07006238
6239 if (event == AudioSystem::SYNC_EVENT_NONE) {
Eric Laurent29864602012-05-08 18:57:51 -07006240 clearSyncStartEvent();
Eric Laurenta011e352012-03-29 15:51:43 -07006241 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
6242 mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
6243 triggerSession,
6244 recordTrack->sessionId(),
6245 syncStartEventCallback,
6246 this);
Eric Laurent29864602012-05-08 18:57:51 -07006247 // Sync event can be cancelled by the trigger session if the track is not in a
6248 // compatible state in which case we start record immediately
6249 if (mSyncStartEvent->isCancelled()) {
6250 clearSyncStartEvent();
6251 } else {
6252 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
6253 mFramestoDrop = - ((AudioSystem::kSyncRecordStartTimeOutMs * mReqSampleRate) / 1000);
6254 }
Eric Laurenta011e352012-03-29 15:51:43 -07006255 }
6256
Mathias Agopian65ab4712010-07-14 17:59:35 -07006257 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08006258 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006259 if (mActiveTrack != 0) {
6260 if (recordTrack != mActiveTrack.get()) {
6261 status = -EBUSY;
6262 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
6263 mActiveTrack->mState = TrackBase::ACTIVE;
6264 }
6265 return status;
6266 }
6267
6268 recordTrack->mState = TrackBase::IDLE;
6269 mActiveTrack = recordTrack;
6270 mLock.unlock();
6271 status_t status = AudioSystem::startInput(mId);
6272 mLock.lock();
6273 if (status != NO_ERROR) {
6274 mActiveTrack.clear();
Eric Laurenta011e352012-03-29 15:51:43 -07006275 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006276 return status;
6277 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006278 mRsmpInIndex = mFrameCount;
6279 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08006280 if (mResampler != NULL) {
6281 mResampler->reset();
6282 }
6283 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006284 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01006285 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006286 mWaitWorkCV.signal();
6287 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08006288 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006289 mActiveTrack.clear();
6290 status = INVALID_OPERATION;
6291 goto startError;
6292 }
6293 mStartStopCond.wait(mLock);
6294 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01006295 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006296 status = BAD_VALUE;
6297 goto startError;
6298 }
Steve Block3856b092011-10-20 11:56:00 +01006299 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006300 return status;
6301 }
6302startError:
6303 AudioSystem::stopInput(mId);
Eric Laurenta011e352012-03-29 15:51:43 -07006304 clearSyncStartEvent();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006305 return status;
6306}
6307
Eric Laurenta011e352012-03-29 15:51:43 -07006308void AudioFlinger::RecordThread::clearSyncStartEvent()
6309{
6310 if (mSyncStartEvent != 0) {
6311 mSyncStartEvent->cancel();
6312 }
6313 mSyncStartEvent.clear();
Eric Laurent29864602012-05-08 18:57:51 -07006314 mFramestoDrop = 0;
Eric Laurenta011e352012-03-29 15:51:43 -07006315}
6316
6317void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6318{
6319 sp<SyncEvent> strongEvent = event.promote();
6320
6321 if (strongEvent != 0) {
6322 RecordThread *me = (RecordThread *)strongEvent->cookie();
6323 me->handleSyncStartEvent(strongEvent);
6324 }
6325}
6326
6327void AudioFlinger::RecordThread::handleSyncStartEvent(const sp<SyncEvent>& event)
6328{
Eric Laurent29864602012-05-08 18:57:51 -07006329 if (event == mSyncStartEvent) {
Eric Laurenta011e352012-03-29 15:51:43 -07006330 // TODO: use actual buffer filling status instead of 2 buffers when info is available
6331 // from audio HAL
6332 mFramestoDrop = mFrameCount * 2;
Eric Laurenta011e352012-03-29 15:51:43 -07006333 }
6334}
6335
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006336bool AudioFlinger::RecordThread::stop_l(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01006337 ALOGV("RecordThread::stop");
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006338 if (recordTrack != mActiveTrack.get() || recordTrack->mState == TrackBase::PAUSING) {
6339 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006340 }
Glenn Kasten1d491ff2012-07-16 14:28:13 -07006341 recordTrack->mState = TrackBase::PAUSING;
6342 // do not wait for mStartStopCond if exiting
6343 if (exitPending()) {
6344 return true;
6345 }
6346 mStartStopCond.wait(mLock);
6347 // if we have been restarted, recordTrack == mActiveTrack.get() here
6348 if (exitPending() || recordTrack != mActiveTrack.get()) {
6349 ALOGV("Record stopped OK");
6350 return true;
6351 }
6352 return false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006353}
6354
Glenn Kasten106e8a42012-08-02 13:37:12 -07006355bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurenta011e352012-03-29 15:51:43 -07006356{
6357 return false;
6358}
6359
6360status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event)
6361{
Glenn Kasten7aa25592012-08-02 16:37:07 -07006362#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 -07006363 if (!isValidSyncEvent(event)) {
6364 return BAD_VALUE;
6365 }
6366
Glenn Kasten510a3d62012-07-16 14:24:34 -07006367 int eventSession = event->triggerSession();
6368 status_t ret = NAME_NOT_FOUND;
6369
Eric Laurenta011e352012-03-29 15:51:43 -07006370 Mutex::Autolock _l(mLock);
6371
Glenn Kasten510a3d62012-07-16 14:24:34 -07006372 for (size_t i = 0; i < mTracks.size(); i++) {
6373 sp<RecordTrack> track = mTracks[i];
6374 if (eventSession == track->sessionId()) {
Glenn Kastend23eedc2012-08-02 13:35:47 -07006375 (void) track->setSyncEvent(event);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006376 ret = NO_ERROR;
6377 }
Eric Laurenta011e352012-03-29 15:51:43 -07006378 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006379 return ret;
Glenn Kasten7aa25592012-08-02 16:37:07 -07006380#else
6381 return BAD_VALUE;
6382#endif
Glenn Kasten510a3d62012-07-16 14:24:34 -07006383}
6384
6385void AudioFlinger::RecordThread::RecordTrack::destroy()
6386{
6387 // see comments at AudioFlinger::PlaybackThread::Track::destroy()
6388 sp<RecordTrack> keep(this);
6389 {
6390 sp<ThreadBase> thread = mThread.promote();
6391 if (thread != 0) {
6392 if (mState == ACTIVE || mState == RESUMING) {
6393 AudioSystem::stopInput(thread->id());
6394 }
6395 AudioSystem::releaseInput(thread->id());
6396 Mutex::Autolock _l(thread->mLock);
6397 RecordThread *recordThread = (RecordThread *) thread.get();
6398 recordThread->destroyTrack_l(this);
6399 }
6400 }
6401}
6402
6403// destroyTrack_l() must be called with ThreadBase::mLock held
6404void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6405{
6406 track->mState = TrackBase::TERMINATED;
6407 // active tracks are removed by threadLoop()
6408 if (mActiveTrack != track) {
6409 removeTrack_l(track);
6410 }
6411}
6412
6413void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6414{
6415 mTracks.remove(track);
6416 // need anything related to effects here?
Eric Laurenta011e352012-03-29 15:51:43 -07006417}
6418
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07006419void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006420{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006421 dumpInternals(fd, args);
6422 dumpTracks(fd, args);
6423 dumpEffectChains(fd, args);
6424}
6425
6426void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6427{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006428 const size_t SIZE = 256;
6429 char buffer[SIZE];
6430 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006431
6432 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
6433 result.append(buffer);
6434
6435 if (mActiveTrack != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006436 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
6437 result.append(buffer);
6438 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
6439 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08006440 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006441 result.append(buffer);
6442 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
6443 result.append(buffer);
6444 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
6445 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006446 } else {
Glenn Kasten510a3d62012-07-16 14:24:34 -07006447 result.append("No active record client\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006448 }
Glenn Kasten510a3d62012-07-16 14:24:34 -07006449
Mathias Agopian65ab4712010-07-14 17:59:35 -07006450 write(fd, result.string(), result.size());
6451
6452 dumpBase(fd, args);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006453}
6454
6455void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args)
6456{
6457 const size_t SIZE = 256;
6458 char buffer[SIZE];
6459 String8 result;
6460
6461 snprintf(buffer, SIZE, "Input thread %p tracks\n", this);
6462 result.append(buffer);
6463 RecordTrack::appendDumpHeader(result);
6464 for (size_t i = 0; i < mTracks.size(); ++i) {
6465 sp<RecordTrack> track = mTracks[i];
6466 if (track != 0) {
6467 track->dump(buffer, SIZE);
6468 result.append(buffer);
6469 }
6470 }
6471
6472 if (mActiveTrack != 0) {
6473 snprintf(buffer, SIZE, "\nInput thread %p active tracks\n", this);
6474 result.append(buffer);
6475 RecordTrack::appendDumpHeader(result);
6476 mActiveTrack->dump(buffer, SIZE);
6477 result.append(buffer);
6478
6479 }
6480 write(fd, result.string(), result.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006481}
6482
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006483// AudioBufferProvider interface
John Grossman4ff14ba2012-02-08 16:37:41 -08006484status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006485{
6486 size_t framesReq = buffer->frameCount;
6487 size_t framesReady = mFrameCount - mRsmpInIndex;
6488 int channelCount;
6489
6490 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006491 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006492 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00006493 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006494 if (mActiveTrack->mState == TrackBase::ACTIVE) {
6495 // Force input into standby so that it tries to
6496 // recover at next read attempt
Glenn Kastene4e2a372012-07-23 12:55:09 -07006497 inputStandBy();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006498 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006499 }
Glenn Kastene0feee32011-12-13 11:53:26 -08006500 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006501 buffer->frameCount = 0;
6502 return NOT_ENOUGH_DATA;
6503 }
6504 mRsmpInIndex = 0;
6505 framesReady = mFrameCount;
6506 }
6507
6508 if (framesReq > framesReady) {
6509 framesReq = framesReady;
6510 }
6511
6512 if (mChannelCount == 1 && mReqChannelCount == 2) {
6513 channelCount = 1;
6514 } else {
6515 channelCount = 2;
6516 }
6517 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
6518 buffer->frameCount = framesReq;
6519 return NO_ERROR;
6520}
6521
Glenn Kasten01c4ebf2012-02-22 10:47:35 -08006522// AudioBufferProvider interface
Mathias Agopian65ab4712010-07-14 17:59:35 -07006523void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
6524{
6525 mRsmpInIndex += buffer->frameCount;
6526 buffer->frameCount = 0;
6527}
6528
6529bool AudioFlinger::RecordThread::checkForNewParameters_l()
6530{
6531 bool reconfig = false;
6532
6533 while (!mNewParameters.isEmpty()) {
6534 status_t status = NO_ERROR;
6535 String8 keyValuePair = mNewParameters[0];
6536 AudioParameter param = AudioParameter(keyValuePair);
6537 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08006538 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006539 int reqSamplingRate = mReqSampleRate;
6540 int reqChannelCount = mReqChannelCount;
6541
6542 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6543 reqSamplingRate = value;
6544 reconfig = true;
6545 }
6546 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08006547 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006548 reconfig = true;
6549 }
6550 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07006551 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006552 reconfig = true;
6553 }
6554 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6555 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten99e53b82012-01-19 08:59:58 -08006556 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006557 // if frame count is changed after track creation
6558 if (mActiveTrack != 0) {
6559 status = INVALID_OPERATION;
6560 } else {
6561 reconfig = true;
6562 }
6563 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006564 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6565 // forward device change to effects that have requested to be
6566 // aware of attached audio device.
6567 for (size_t i = 0; i < mEffectChains.size(); i++) {
6568 mEffectChains[i]->setDevice_l(value);
6569 }
6570 // store input device and output device but do not forward output device to audio HAL.
6571 // Note that status is ignored by the caller for output device
6572 // (see AudioFlinger::setParameters()
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006573 audio_devices_t newDevice = mDevice;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006574 if (value & AUDIO_DEVICE_OUT_ALL) {
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006575 newDevice &= ~(value & AUDIO_DEVICE_OUT_ALL);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006576 status = BAD_VALUE;
6577 } else {
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006578 newDevice &= ~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07006579 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
Glenn Kasten510a3d62012-07-16 14:24:34 -07006580 if (mTracks.size() > 0) {
Eric Laurent59bd0da2011-08-01 09:52:20 -07006581 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07006582 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Glenn Kasten510a3d62012-07-16 14:24:34 -07006583 for (size_t i = 0; i < mTracks.size(); i++) {
6584 sp<RecordTrack> track = mTracks[i];
6585 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
6586 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
6587 }
Eric Laurent59bd0da2011-08-01 09:52:20 -07006588 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006589 }
Glenn Kasten01542f22012-07-02 12:46:15 -07006590 newDevice |= value;
Glenn Kasten5ad92f62012-07-19 10:02:15 -07006591 mDevice = newDevice; // since mDevice is read by other threads, only write to it once
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006592 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006593 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006594 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006595 if (status == INVALID_OPERATION) {
Glenn Kastene4e2a372012-07-23 12:55:09 -07006596 inputStandBy();
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006597 status = mInput->stream->common.set_parameters(&mInput->stream->common,
6598 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006599 }
6600 if (reconfig) {
6601 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006602 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07006603 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07006604 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
Glenn Kasten53d76db2012-03-08 12:32:47 -08006605 popcount(mInput->stream->common.get_channels(&mInput->stream->common)) <= FCC_2 &&
6606 (reqChannelCount <= FCC_2)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006607 status = NO_ERROR;
6608 }
6609 if (status == NO_ERROR) {
6610 readInputParameters();
6611 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
6612 }
6613 }
6614 }
6615
6616 mNewParameters.removeAt(0);
6617
6618 mParamStatus = status;
6619 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07006620 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
6621 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08006622 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006623 }
6624 return reconfig;
6625}
6626
6627String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
6628{
Dima Zavinfce7a472011-04-19 22:30:36 -07006629 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006630 String8 out_s8 = String8();
6631
6632 Mutex::Autolock _l(mLock);
6633 if (initCheck() != NO_ERROR) {
6634 return out_s8;
6635 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006636
Dima Zavin799a70e2011-04-18 16:57:27 -07006637 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07006638 out_s8 = String8(s);
6639 free(s);
6640 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006641}
6642
6643void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
6644 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08006645 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006646
6647 switch (event) {
6648 case AudioSystem::INPUT_OPENED:
6649 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006650 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006651 desc.samplingRate = mSampleRate;
6652 desc.format = mFormat;
6653 desc.frameCount = mFrameCount;
6654 desc.latency = 0;
6655 param2 = &desc;
6656 break;
6657
6658 case AudioSystem::INPUT_CLOSED:
6659 default:
6660 break;
6661 }
6662 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
6663}
6664
6665void AudioFlinger::RecordThread::readInputParameters()
6666{
Glenn Kastene9dd0172012-01-27 18:08:45 -08006667 delete mRsmpInBuffer;
6668 // mRsmpInBuffer is always assigned a new[] below
6669 delete mRsmpOutBuffer;
6670 mRsmpOutBuffer = NULL;
6671 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08006672 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006673
Dima Zavin799a70e2011-04-18 16:57:27 -07006674 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07006675 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
6676 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07006677 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08006678 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07006679 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006680 mFrameCount = mInputBytes / mFrameSize;
Glenn Kasten58912562012-04-03 10:45:00 -07006681 mNormalFrameCount = mFrameCount; // not used by record, but used by input effects
Mathias Agopian65ab4712010-07-14 17:59:35 -07006682 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
6683
Glenn Kasten53d76db2012-03-08 12:32:47 -08006684 if (mSampleRate != mReqSampleRate && mChannelCount <= FCC_2 && mReqChannelCount <= FCC_2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006685 {
6686 int channelCount;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006687 // optimization: if mono to mono, use the resampler in stereo to stereo mode to avoid
6688 // stereo to mono post process as the resampler always outputs stereo.
Mathias Agopian65ab4712010-07-14 17:59:35 -07006689 if (mChannelCount == 1 && mReqChannelCount == 2) {
6690 channelCount = 1;
6691 } else {
6692 channelCount = 2;
6693 }
6694 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
6695 mResampler->setSampleRate(mSampleRate);
6696 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
6697 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
6698
6699 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
6700 if (mChannelCount == 1 && mReqChannelCount == 1) {
6701 mFrameCount >>= 1;
6702 }
6703
6704 }
6705 mRsmpInIndex = mFrameCount;
6706}
6707
6708unsigned int AudioFlinger::RecordThread::getInputFramesLost()
6709{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006710 Mutex::Autolock _l(mLock);
6711 if (initCheck() != NO_ERROR) {
6712 return 0;
6713 }
6714
Dima Zavin799a70e2011-04-18 16:57:27 -07006715 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006716}
6717
Glenn Kasten106e8a42012-08-02 13:37:12 -07006718uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006719{
6720 Mutex::Autolock _l(mLock);
6721 uint32_t result = 0;
6722 if (getEffectChain_l(sessionId) != 0) {
6723 result = EFFECT_SESSION;
6724 }
6725
Glenn Kasten510a3d62012-07-16 14:24:34 -07006726 for (size_t i = 0; i < mTracks.size(); ++i) {
6727 if (sessionId == mTracks[i]->sessionId()) {
6728 result |= TRACK_SESSION;
6729 break;
6730 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006731 }
6732
6733 return result;
6734}
6735
Glenn Kasten106e8a42012-08-02 13:37:12 -07006736KeyedVector<int, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent59bd0da2011-08-01 09:52:20 -07006737{
Glenn Kasten510a3d62012-07-16 14:24:34 -07006738 KeyedVector<int, bool> ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006739 Mutex::Autolock _l(mLock);
Glenn Kasten510a3d62012-07-16 14:24:34 -07006740 for (size_t j = 0; j < mTracks.size(); ++j) {
6741 sp<RecordThread::RecordTrack> track = mTracks[j];
6742 int sessionId = track->sessionId();
6743 if (ids.indexOfKey(sessionId) < 0) {
6744 ids.add(sessionId, true);
6745 }
6746 }
6747 return ids;
Eric Laurent59bd0da2011-08-01 09:52:20 -07006748}
6749
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006750AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
6751{
6752 Mutex::Autolock _l(mLock);
6753 AudioStreamIn *input = mInput;
6754 mInput = NULL;
6755 return input;
6756}
6757
6758// this method must always be called either with ThreadBase mLock held or inside the thread loop
Glenn Kasten0bf65bd2012-02-28 18:32:53 -08006759audio_stream_t* AudioFlinger::RecordThread::stream() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006760{
6761 if (mInput == NULL) {
6762 return NULL;
6763 }
6764 return &mInput->stream->common;
6765}
6766
6767
Mathias Agopian65ab4712010-07-14 17:59:35 -07006768// ----------------------------------------------------------------------------
6769
Eric Laurenta4c5a552012-03-29 10:12:40 -07006770audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
6771{
6772 if (!settingsAllowed()) {
6773 return 0;
6774 }
6775 Mutex::Autolock _l(mLock);
6776 return loadHwModule_l(name);
6777}
6778
6779// loadHwModule_l() must be called with AudioFlinger::mLock held
6780audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
6781{
6782 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
6783 if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {
6784 ALOGW("loadHwModule() module %s already loaded", name);
6785 return mAudioHwDevs.keyAt(i);
6786 }
6787 }
6788
Eric Laurenta4c5a552012-03-29 10:12:40 -07006789 audio_hw_device_t *dev;
6790
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006791 int rc = load_audio_interface(name, &dev);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006792 if (rc) {
6793 ALOGI("loadHwModule() error %d loading module %s ", rc, name);
6794 return 0;
6795 }
6796
6797 mHardwareStatus = AUDIO_HW_INIT;
6798 rc = dev->init_check(dev);
6799 mHardwareStatus = AUDIO_HW_IDLE;
6800 if (rc) {
6801 ALOGI("loadHwModule() init check error %d for module %s ", rc, name);
6802 return 0;
6803 }
6804
John Grossmanee578c02012-07-23 17:05:46 -07006805 // Check and cache this HAL's level of support for master mute and master
6806 // volume. If this is the first HAL opened, and it supports the get
6807 // methods, use the initial values provided by the HAL as the current
6808 // master mute and volume settings.
6809
6810 AudioHwDevice::Flags flags = static_cast<AudioHwDevice::Flags>(0);
6811 { // scope for auto-lock pattern
Eric Laurenta4c5a552012-03-29 10:12:40 -07006812 AutoMutex lock(mHardwareLock);
John Grossmanee578c02012-07-23 17:05:46 -07006813
6814 if (0 == mAudioHwDevs.size()) {
6815 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
6816 if (NULL != dev->get_master_volume) {
6817 float mv;
6818 if (OK == dev->get_master_volume(dev, &mv)) {
6819 mMasterVolume = mv;
6820 }
6821 }
6822
6823 mHardwareStatus = AUDIO_HW_GET_MASTER_MUTE;
6824 if (NULL != dev->get_master_mute) {
6825 bool mm;
6826 if (OK == dev->get_master_mute(dev, &mm)) {
6827 mMasterMute = mm;
6828 }
6829 }
6830 }
6831
Eric Laurenta4c5a552012-03-29 10:12:40 -07006832 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
John Grossmanee578c02012-07-23 17:05:46 -07006833 if ((NULL != dev->set_master_volume) &&
6834 (OK == dev->set_master_volume(dev, mMasterVolume))) {
6835 flags = static_cast<AudioHwDevice::Flags>(flags |
6836 AudioHwDevice::AHWD_CAN_SET_MASTER_VOLUME);
6837 }
6838
6839 mHardwareStatus = AUDIO_HW_SET_MASTER_MUTE;
6840 if ((NULL != dev->set_master_mute) &&
6841 (OK == dev->set_master_mute(dev, mMasterMute))) {
6842 flags = static_cast<AudioHwDevice::Flags>(flags |
6843 AudioHwDevice::AHWD_CAN_SET_MASTER_MUTE);
6844 }
6845
Eric Laurenta4c5a552012-03-29 10:12:40 -07006846 mHardwareStatus = AUDIO_HW_IDLE;
6847 }
6848
6849 audio_module_handle_t handle = nextUniqueId();
John Grossmanee578c02012-07-23 17:05:46 -07006850 mAudioHwDevs.add(handle, new AudioHwDevice(name, dev, flags));
Eric Laurenta4c5a552012-03-29 10:12:40 -07006851
6852 ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006853 name, dev->common.module->name, dev->common.module->id, handle);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006854
6855 return handle;
6856
6857}
6858
6859audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,
6860 audio_devices_t *pDevices,
6861 uint32_t *pSamplingRate,
6862 audio_format_t *pFormat,
6863 audio_channel_mask_t *pChannelMask,
6864 uint32_t *pLatencyMs,
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006865 audio_output_flags_t flags)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006866{
6867 status_t status;
6868 PlaybackThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006869 struct audio_config config = {
6870 sample_rate: pSamplingRate ? *pSamplingRate : 0,
6871 channel_mask: pChannelMask ? *pChannelMask : 0,
6872 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
6873 };
6874 audio_stream_out_t *outStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07006875 AudioHwDevice *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006876
Eric Laurenta4c5a552012-03-29 10:12:40 -07006877 ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
6878 module,
Glenn Kastenbb4350d2012-07-03 15:56:38 -07006879 (pDevices != NULL) ? *pDevices : 0,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006880 config.sample_rate,
6881 config.format,
6882 config.channel_mask,
Eric Laurenta4c5a552012-03-29 10:12:40 -07006883 flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006884
6885 if (pDevices == NULL || *pDevices == 0) {
6886 return 0;
6887 }
Dima Zavin799a70e2011-04-18 16:57:27 -07006888
Mathias Agopian65ab4712010-07-14 17:59:35 -07006889 Mutex::Autolock _l(mLock);
6890
Eric Laurenta4c5a552012-03-29 10:12:40 -07006891 outHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07006892 if (outHwDev == NULL)
6893 return 0;
6894
John Grossmanee578c02012-07-23 17:05:46 -07006895 audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006896 audio_io_handle_t id = nextUniqueId();
6897
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006898 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006899
John Grossmanee578c02012-07-23 17:05:46 -07006900 status = hwDevHal->open_output_stream(hwDevHal,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006901 id,
6902 *pDevices,
6903 (audio_output_flags_t)flags,
6904 &config,
6905 &outStream);
6906
Glenn Kasten8abf44d2012-02-02 14:16:03 -08006907 mHardwareStatus = AUDIO_HW_IDLE;
Steve Block3856b092011-10-20 11:56:00 +01006908 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07006909 outStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006910 config.sample_rate,
6911 config.format,
6912 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006913 status);
6914
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006915 if (status == NO_ERROR && outStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07006916 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Dima Zavin799a70e2011-04-18 16:57:27 -07006917
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006918 if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006919 (config.format != AUDIO_FORMAT_PCM_16_BIT) ||
6920 (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006921 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006922 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006923 } else {
6924 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01006925 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006926 }
6927 mPlaybackThreads.add(id, thread);
6928
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07006929 if (pSamplingRate != NULL) *pSamplingRate = config.sample_rate;
6930 if (pFormat != NULL) *pFormat = config.format;
6931 if (pChannelMask != NULL) *pChannelMask = config.channel_mask;
Glenn Kastena0d68332012-01-27 16:47:15 -08006932 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006933
6934 // notify client processes of the new output creation
6935 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006936
6937 // the first primary output opened designates the primary hw device
Eric Laurent0ca3cf92012-04-18 09:24:29 -07006938 if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {
Eric Laurenta4c5a552012-03-29 10:12:40 -07006939 ALOGI("Using module %d has the primary audio interface", module);
6940 mPrimaryHardwareDev = outHwDev;
6941
6942 AutoMutex lock(mHardwareLock);
6943 mHardwareStatus = AUDIO_HW_SET_MODE;
John Grossmanee578c02012-07-23 17:05:46 -07006944 hwDevHal->set_mode(hwDevHal, mMode);
Eric Laurenta4c5a552012-03-29 10:12:40 -07006945 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta4c5a552012-03-29 10:12:40 -07006946 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006947 return id;
6948 }
6949
6950 return 0;
6951}
6952
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006953audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
6954 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006955{
6956 Mutex::Autolock _l(mLock);
6957 MixerThread *thread1 = checkMixerThread_l(output1);
6958 MixerThread *thread2 = checkMixerThread_l(output2);
6959
6960 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006961 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006962 return 0;
6963 }
6964
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006965 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006966 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
6967 thread->addOutputTrack(thread2);
6968 mPlaybackThreads.add(id, thread);
6969 // notify client processes of the new output creation
6970 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
6971 return id;
6972}
6973
Glenn Kasten72ef00d2012-01-17 11:09:42 -08006974status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006975{
Glenn Kastend96c5722012-04-25 13:44:49 -07006976 return closeOutput_nonvirtual(output);
6977}
6978
6979status_t AudioFlinger::closeOutput_nonvirtual(audio_io_handle_t output)
6980{
Mathias Agopian65ab4712010-07-14 17:59:35 -07006981 // keep strong reference on the playback thread so that
6982 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07006983 sp<PlaybackThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006984 {
6985 Mutex::Autolock _l(mLock);
6986 thread = checkPlaybackThread_l(output);
6987 if (thread == NULL) {
6988 return BAD_VALUE;
6989 }
6990
Steve Block3856b092011-10-20 11:56:00 +01006991 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006992
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006993 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006994 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006995 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006996 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
6997 dupThread->removeOutputTrack((MixerThread *)thread.get());
6998 }
6999 }
7000 }
Glenn Kastena1117922012-01-26 10:53:32 -08007001 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007002 mPlaybackThreads.removeItem(output);
7003 }
7004 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007005 // The thread entity (active unit of execution) is no longer running here,
7006 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007007
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007008 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007009 AudioStreamOut *out = thread->clearOutput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007010 ALOG_ASSERT(out != NULL, "out shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007011 // from now on thread->mOutput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007012 out->hwDev()->close_output_stream(out->hwDev(), out->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007013 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007014 }
7015 return NO_ERROR;
7016}
7017
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007018status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007019{
7020 Mutex::Autolock _l(mLock);
7021 PlaybackThread *thread = checkPlaybackThread_l(output);
7022
7023 if (thread == NULL) {
7024 return BAD_VALUE;
7025 }
7026
Steve Block3856b092011-10-20 11:56:00 +01007027 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007028 thread->suspend();
7029
7030 return NO_ERROR;
7031}
7032
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007033status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007034{
7035 Mutex::Autolock _l(mLock);
7036 PlaybackThread *thread = checkPlaybackThread_l(output);
7037
7038 if (thread == NULL) {
7039 return BAD_VALUE;
7040 }
7041
Steve Block3856b092011-10-20 11:56:00 +01007042 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007043
7044 thread->restore();
7045
7046 return NO_ERROR;
7047}
7048
Eric Laurenta4c5a552012-03-29 10:12:40 -07007049audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,
7050 audio_devices_t *pDevices,
7051 uint32_t *pSamplingRate,
7052 audio_format_t *pFormat,
Glenn Kasten254af182012-07-03 14:59:05 -07007053 audio_channel_mask_t *pChannelMask)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007054{
7055 status_t status;
7056 RecordThread *thread = NULL;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007057 struct audio_config config = {
7058 sample_rate: pSamplingRate ? *pSamplingRate : 0,
7059 channel_mask: pChannelMask ? *pChannelMask : 0,
7060 format: pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT,
7061 };
7062 uint32_t reqSamplingRate = config.sample_rate;
7063 audio_format_t reqFormat = config.format;
7064 audio_channel_mask_t reqChannels = config.channel_mask;
7065 audio_stream_in_t *inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007066 AudioHwDevice *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007067
7068 if (pDevices == NULL || *pDevices == 0) {
7069 return 0;
7070 }
Dima Zavin799a70e2011-04-18 16:57:27 -07007071
Mathias Agopian65ab4712010-07-14 17:59:35 -07007072 Mutex::Autolock _l(mLock);
7073
Eric Laurenta4c5a552012-03-29 10:12:40 -07007074 inHwDev = findSuitableHwDev_l(module, *pDevices);
Dima Zavin799a70e2011-04-18 16:57:27 -07007075 if (inHwDev == NULL)
7076 return 0;
7077
John Grossmanee578c02012-07-23 17:05:46 -07007078 audio_hw_device_t *inHwHal = inHwDev->hwDevice();
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007079 audio_io_handle_t id = nextUniqueId();
7080
John Grossmanee578c02012-07-23 17:05:46 -07007081 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,
Dima Zavin799a70e2011-04-18 16:57:27 -07007082 &inStream);
Eric Laurenta4c5a552012-03-29 10:12:40 -07007083 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07007084 inStream,
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007085 config.sample_rate,
7086 config.format,
7087 config.channel_mask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007088 status);
7089
7090 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
7091 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
7092 // or stereo to mono conversions on 16 bit PCM inputs.
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007093 if (status == BAD_VALUE &&
7094 reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT &&
7095 (config.sample_rate <= 2 * reqSamplingRate) &&
7096 (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {
Glenn Kasten254af182012-07-03 14:59:05 -07007097 ALOGV("openInput() reopening with proposed sampling rate and channel mask");
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007098 inStream = NULL;
John Grossmanee578c02012-07-23 17:05:46 -07007099 status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007100 }
7101
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007102 if (status == NO_ERROR && inStream != NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -07007103 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
7104
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007105 // Start record thread
7106 // RecorThread require both input and output device indication to forward to audio
7107 // pre processing modules
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007108 audio_devices_t device = (*pDevices) | primaryOutputDevice_l();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007109 thread = new RecordThread(this,
7110 input,
7111 reqSamplingRate,
7112 reqChannels,
7113 id,
7114 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007115 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01007116 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08007117 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
Eric Laurentf7ffb8b2012-04-14 09:06:57 -07007118 if (pFormat != NULL) *pFormat = config.format;
Eric Laurenta4c5a552012-03-29 10:12:40 -07007119 if (pChannelMask != NULL) *pChannelMask = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007120
Mathias Agopian65ab4712010-07-14 17:59:35 -07007121 // notify client processes of the new input creation
7122 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
7123 return id;
7124 }
7125
7126 return 0;
7127}
7128
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007129status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007130{
Glenn Kastend96c5722012-04-25 13:44:49 -07007131 return closeInput_nonvirtual(input);
7132}
7133
7134status_t AudioFlinger::closeInput_nonvirtual(audio_io_handle_t input)
7135{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007136 // keep strong reference on the record thread so that
7137 // it is not destroyed while exit() is executed
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007138 sp<RecordThread> thread;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007139 {
7140 Mutex::Autolock _l(mLock);
7141 thread = checkRecordThread_l(input);
Glenn Kastend5903ec2012-03-18 10:33:27 -07007142 if (thread == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007143 return BAD_VALUE;
7144 }
7145
Steve Block3856b092011-10-20 11:56:00 +01007146 ALOGV("closeInput() %d", input);
Glenn Kastena1117922012-01-26 10:53:32 -08007147 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007148 mRecordThreads.removeItem(input);
7149 }
7150 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08007151 // The thread entity (active unit of execution) is no longer running here,
7152 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07007153
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007154 AudioStreamIn *in = thread->clearInput();
Glenn Kasten5798d4e2012-03-08 12:18:35 -08007155 ALOG_ASSERT(in != NULL, "in shouldn't be NULL");
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007156 // from now on thread->mInput is NULL
John Grossmanee578c02012-07-23 17:05:46 -07007157 in->hwDev()->close_input_stream(in->hwDev(), in->stream);
Dima Zavin799a70e2011-04-18 16:57:27 -07007158 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007159
7160 return NO_ERROR;
7161}
7162
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007163status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007164{
7165 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007166 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007167
7168 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7169 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent22167852012-06-20 12:26:32 -07007170 thread->invalidateTracks(stream);
Eric Laurentde070132010-07-13 04:45:46 -07007171 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007172
7173 return NO_ERROR;
7174}
7175
7176
7177int AudioFlinger::newAudioSessionId()
7178{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007179 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007180}
7181
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007182void AudioFlinger::acquireAudioSessionId(int audioSession)
7183{
7184 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007185 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007186 ALOGV("acquiring %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007187 size_t num = mAudioSessionRefs.size();
7188 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007189 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007190 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7191 ref->mCnt++;
7192 ALOGV(" incremented refcount to %d", ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007193 return;
7194 }
7195 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08007196 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
7197 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007198}
7199
7200void AudioFlinger::releaseAudioSessionId(int audioSession)
7201{
7202 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08007203 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01007204 ALOGV("releasing %d from %d", audioSession, caller);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08007205 size_t num = mAudioSessionRefs.size();
7206 for (size_t i = 0; i< num; i++) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007207 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007208 if (ref->mSessionid == audioSession && ref->mPid == caller) {
7209 ref->mCnt--;
7210 ALOGV(" decremented refcount to %d", ref->mCnt);
7211 if (ref->mCnt == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007212 mAudioSessionRefs.removeAt(i);
7213 delete ref;
7214 purgeStaleEffects_l();
7215 }
7216 return;
7217 }
7218 }
Steve Block5ff1dd52012-01-05 23:22:43 +00007219 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007220}
7221
7222void AudioFlinger::purgeStaleEffects_l() {
7223
Steve Block3856b092011-10-20 11:56:00 +01007224 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007225
7226 Vector< sp<EffectChain> > chains;
7227
7228 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7229 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
7230 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7231 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07007232 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
7233 chains.push(ec);
7234 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007235 }
7236 }
7237 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7238 sp<RecordThread> t = mRecordThreads.valueAt(i);
7239 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
7240 sp<EffectChain> ec = t->mEffectChains[j];
7241 chains.push(ec);
7242 }
7243 }
7244
7245 for (size_t i = 0; i < chains.size(); i++) {
7246 sp<EffectChain> ec = chains[i];
7247 int sessionid = ec->sessionId();
7248 sp<ThreadBase> t = ec->mThread.promote();
7249 if (t == 0) {
7250 continue;
7251 }
7252 size_t numsessionrefs = mAudioSessionRefs.size();
7253 bool found = false;
7254 for (size_t k = 0; k < numsessionrefs; k++) {
7255 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
Glenn Kasten012ca6b2012-03-06 11:22:01 -08007256 if (ref->mSessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01007257 ALOGV(" session %d still exists for %d with %d refs",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007258 sessionid, ref->mPid, ref->mCnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007259 found = true;
7260 break;
7261 }
7262 }
7263 if (!found) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007264 Mutex::Autolock _l (t->mLock);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007265 // remove all effects from the chain
7266 while (ec->mEffects.size()) {
7267 sp<EffectModule> effect = ec->mEffects[0];
7268 effect->unPin();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007269 t->removeEffect_l(effect);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007270 if (effect->purgeHandles()) {
7271 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007272 }
7273 AudioSystem::unregisterEffect(effect->id());
7274 }
7275 }
7276 }
7277 return;
7278}
7279
Mathias Agopian65ab4712010-07-14 17:59:35 -07007280// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007281AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007282{
Glenn Kastena1117922012-01-26 10:53:32 -08007283 return mPlaybackThreads.valueFor(output).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007284}
7285
7286// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007287AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007288{
7289 PlaybackThread *thread = checkPlaybackThread_l(output);
Glenn Kastena1117922012-01-26 10:53:32 -08007290 return thread != NULL && thread->type() != ThreadBase::DIRECT ? (MixerThread *) thread : NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007291}
7292
7293// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007294AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007295{
Glenn Kastena1117922012-01-26 10:53:32 -08007296 return mRecordThreads.valueFor(input).get();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007297}
7298
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007299uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07007300{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007301 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007302}
7303
Glenn Kasten02fe1bf2012-02-24 15:42:17 -08007304AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007305{
7306 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7307 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07007308 AudioStreamOut *output = thread->getOutput();
John Grossmanee578c02012-07-23 17:05:46 -07007309 if (output != NULL && output->audioHwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007310 return thread;
7311 }
7312 }
7313 return NULL;
7314}
7315
Glenn Kastenbb4350d2012-07-03 15:56:38 -07007316audio_devices_t AudioFlinger::primaryOutputDevice_l() const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007317{
7318 PlaybackThread *thread = primaryPlaybackThread_l();
7319
7320 if (thread == NULL) {
7321 return 0;
7322 }
7323
7324 return thread->device();
7325}
7326
Eric Laurenta011e352012-03-29 15:51:43 -07007327sp<AudioFlinger::SyncEvent> AudioFlinger::createSyncEvent(AudioSystem::sync_event_t type,
7328 int triggerSession,
7329 int listenerSession,
7330 sync_event_callback_t callBack,
7331 void *cookie)
7332{
7333 Mutex::Autolock _l(mLock);
7334
7335 sp<SyncEvent> event = new SyncEvent(type, triggerSession, listenerSession, callBack, cookie);
7336 status_t playStatus = NAME_NOT_FOUND;
7337 status_t recStatus = NAME_NOT_FOUND;
7338 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7339 playStatus = mPlaybackThreads.valueAt(i)->setSyncEvent(event);
7340 if (playStatus == NO_ERROR) {
7341 return event;
7342 }
7343 }
7344 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7345 recStatus = mRecordThreads.valueAt(i)->setSyncEvent(event);
7346 if (recStatus == NO_ERROR) {
7347 return event;
7348 }
7349 }
7350 if (playStatus == NAME_NOT_FOUND || recStatus == NAME_NOT_FOUND) {
7351 mPendingSyncEvents.add(event);
7352 } else {
7353 ALOGV("createSyncEvent() invalid event %d", event->type());
7354 event.clear();
7355 }
7356 return event;
7357}
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007358
Mathias Agopian65ab4712010-07-14 17:59:35 -07007359// ----------------------------------------------------------------------------
7360// Effect management
7361// ----------------------------------------------------------------------------
7362
7363
Glenn Kastenf587ba52012-01-26 16:25:10 -08007364status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007365{
7366 Mutex::Autolock _l(mLock);
7367 return EffectQueryNumberEffects(numEffects);
7368}
7369
Glenn Kastenf587ba52012-01-26 16:25:10 -08007370status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007371{
7372 Mutex::Autolock _l(mLock);
7373 return EffectQueryEffect(index, descriptor);
7374}
7375
Glenn Kasten5e92a782012-01-30 07:40:52 -08007376status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08007377 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07007378{
7379 Mutex::Autolock _l(mLock);
7380 return EffectGetDescriptor(pUuid, descriptor);
7381}
7382
7383
Mathias Agopian65ab4712010-07-14 17:59:35 -07007384sp<IEffect> AudioFlinger::createEffect(pid_t pid,
7385 effect_descriptor_t *pDesc,
7386 const sp<IEffectClient>& effectClient,
7387 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007388 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007389 int sessionId,
7390 status_t *status,
7391 int *id,
7392 int *enabled)
7393{
7394 status_t lStatus = NO_ERROR;
7395 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007396 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007397
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007398 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007399 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007400
7401 if (pDesc == NULL) {
7402 lStatus = BAD_VALUE;
7403 goto Exit;
7404 }
7405
Eric Laurent84e9a102010-09-23 16:10:16 -07007406 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007407 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007408 lStatus = PERMISSION_DENIED;
7409 goto Exit;
7410 }
7411
Dima Zavinfce7a472011-04-19 22:30:36 -07007412 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07007413 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08007414 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007415 lStatus = PERMISSION_DENIED;
7416 goto Exit;
7417 }
7418
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007419 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07007420 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007421 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07007422 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07007423 lStatus = BAD_VALUE;
7424 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07007425 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07007426 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007427 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07007428 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007429 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07007430 }
7431 }
7432
Mathias Agopian65ab4712010-07-14 17:59:35 -07007433 {
7434 Mutex::Autolock _l(mLock);
7435
Mathias Agopian65ab4712010-07-14 17:59:35 -07007436
7437 if (!EffectIsNullUuid(&pDesc->uuid)) {
7438 // if uuid is specified, request effect descriptor
7439 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
7440 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007441 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007442 goto Exit;
7443 }
7444 } else {
7445 // if uuid is not specified, look for an available implementation
7446 // of the required type in effect factory
7447 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007448 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007449 lStatus = BAD_VALUE;
7450 goto Exit;
7451 }
7452 uint32_t numEffects = 0;
7453 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007454 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07007455 bool found = false;
7456
7457 lStatus = EffectQueryNumberEffects(&numEffects);
7458 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007459 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007460 goto Exit;
7461 }
7462 for (uint32_t i = 0; i < numEffects; i++) {
7463 lStatus = EffectQueryEffect(i, &desc);
7464 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007465 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007466 continue;
7467 }
7468 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
7469 // If matching type found save effect descriptor. If the session is
7470 // 0 and the effect is not auxiliary, continue enumeration in case
7471 // an auxiliary version of this effect type is available
7472 found = true;
Glenn Kastena189a682012-02-20 12:16:30 -08007473 d = desc;
Dima Zavinfce7a472011-04-19 22:30:36 -07007474 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07007475 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7476 break;
7477 }
7478 }
7479 }
7480 if (!found) {
7481 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00007482 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007483 goto Exit;
7484 }
7485 // For same effect type, chose auxiliary version over insert version if
7486 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07007487 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007488 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kastena189a682012-02-20 12:16:30 -08007489 desc = d;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007490 }
7491 }
7492
7493 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07007494 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07007495 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7496 lStatus = INVALID_OPERATION;
7497 goto Exit;
7498 }
7499
Eric Laurent59255e42011-07-27 19:49:51 -07007500 // check recording permission for visualizer
7501 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
7502 !recordingAllowed()) {
7503 lStatus = PERMISSION_DENIED;
7504 goto Exit;
7505 }
7506
Mathias Agopian65ab4712010-07-14 17:59:35 -07007507 // return effect descriptor
Glenn Kastena189a682012-02-20 12:16:30 -08007508 *pDesc = desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007509
7510 // If output is not specified try to find a matching audio session ID in one of the
7511 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07007512 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
7513 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007514 // Note: io is never 0 when creating an effect on an input
7515 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007516 // look for the thread where the specified audio session is present
Eric Laurent84e9a102010-09-23 16:10:16 -07007517 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
7518 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007519 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07007520 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07007521 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007522 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007523 if (io == 0) {
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007524 for (size_t i = 0; i < mRecordThreads.size(); i++) {
7525 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
7526 io = mRecordThreads.keyAt(i);
7527 break;
7528 }
7529 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007530 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007531 // If no output thread contains the requested session ID, default to
7532 // first output. The effect chain will be moved to the correct output
7533 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007534 if (io == 0 && mPlaybackThreads.size()) {
7535 io = mPlaybackThreads.keyAt(0);
7536 }
Steve Block3856b092011-10-20 11:56:00 +01007537 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007538 }
7539 ThreadBase *thread = checkRecordThread_l(io);
7540 if (thread == NULL) {
7541 thread = checkPlaybackThread_l(io);
7542 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00007543 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007544 lStatus = BAD_VALUE;
7545 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07007546 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007547 }
Eric Laurent84e9a102010-09-23 16:10:16 -07007548
Glenn Kasten98ec94c2012-01-25 14:28:29 -08007549 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007550
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007551 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07007552 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
7553 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007554 if (handle != 0 && id != NULL) {
7555 *id = handle->id();
7556 }
7557 }
7558
7559Exit:
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007560 if (status != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007561 *status = lStatus;
7562 }
7563 return handle;
7564}
7565
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007566status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
7567 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07007568{
Steve Block3856b092011-10-20 11:56:00 +01007569 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07007570 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007571 Mutex::Autolock _l(mLock);
7572 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007573 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007574 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007575 }
Eric Laurentde070132010-07-13 04:45:46 -07007576 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
7577 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007578 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007579 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007580 }
Eric Laurentde070132010-07-13 04:45:46 -07007581 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
7582 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007583 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07007584 return BAD_VALUE;
7585 }
7586
7587 Mutex::Autolock _dl(dstThread->mLock);
7588 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07007589 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07007590
Mathias Agopian65ab4712010-07-14 17:59:35 -07007591 return NO_ERROR;
7592}
7593
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007594// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07007595status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07007596 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07007597 AudioFlinger::PlaybackThread *dstThread,
7598 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07007599{
Steve Block3856b092011-10-20 11:56:00 +01007600 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007601 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07007602
Eric Laurent59255e42011-07-27 19:49:51 -07007603 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007604 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007605 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07007606 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07007607 return INVALID_OPERATION;
7608 }
7609
Eric Laurent39e94f82010-07-28 01:32:47 -07007610 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07007611 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07007612 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07007613 // removed.
7614 srcThread->removeEffectChain_l(chain);
7615
7616 // transfer all effects one by one so that new effect chain is created on new thread with
7617 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08007618 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07007619 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007620 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07007621 sp<EffectModule> effect = chain->getEffectFromId_l(0);
7622 while (effect != 0) {
7623 srcThread->removeEffect_l(effect);
7624 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07007625 // removeEffect_l() has stopped the effect if it was active so it must be restarted
7626 if (effect->state() == EffectModule::ACTIVE ||
7627 effect->state() == EffectModule::STOPPING) {
7628 effect->start();
7629 }
Eric Laurent39e94f82010-07-28 01:32:47 -07007630 // if the move request is not received from audio policy manager, the effect must be
7631 // re-registered with the new strategy and output
7632 if (dstChain == 0) {
7633 dstChain = effect->chain().promote();
7634 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007635 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07007636 srcThread->addEffect_l(effect);
7637 return NO_INIT;
7638 }
7639 strategy = dstChain->strategy();
7640 }
7641 if (reRegister) {
7642 AudioSystem::unregisterEffect(effect->id());
7643 AudioSystem::registerEffect(&effect->desc(),
7644 dstOutput,
7645 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07007646 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07007647 effect->id());
7648 }
Eric Laurentde070132010-07-13 04:45:46 -07007649 effect = chain->getEffectFromId_l(0);
7650 }
7651
7652 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007653}
7654
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007655
Mathias Agopian65ab4712010-07-14 17:59:35 -07007656// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007657sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07007658 const sp<AudioFlinger::Client>& client,
7659 const sp<IEffectClient>& effectClient,
7660 int32_t priority,
7661 int sessionId,
7662 effect_descriptor_t *desc,
7663 int *enabled,
7664 status_t *status
7665 )
7666{
7667 sp<EffectModule> effect;
7668 sp<EffectHandle> handle;
7669 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007670 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07007671 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007672 bool effectCreated = false;
7673 bool effectRegistered = false;
7674
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007675 lStatus = initCheck();
7676 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007677 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007678 goto Exit;
7679 }
7680
7681 // Do not allow effects with session ID 0 on direct output or duplicating threads
7682 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07007683 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007684 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07007685 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007686 lStatus = BAD_VALUE;
7687 goto Exit;
7688 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007689 // Only Pre processor effects are allowed on input threads and only on input threads
Glenn Kastena1117922012-01-26 10:53:32 -08007690 if ((mType == RECORD) != ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007691 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007692 desc->name, desc->flags, mType);
7693 lStatus = BAD_VALUE;
7694 goto Exit;
7695 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007696
Steve Block3856b092011-10-20 11:56:00 +01007697 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007698
7699 { // scope for mLock
7700 Mutex::Autolock _l(mLock);
7701
7702 // check for existing effect chain with the requested audio session
7703 chain = getEffectChain_l(sessionId);
7704 if (chain == 0) {
7705 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007706 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007707 chain = new EffectChain(this, sessionId);
7708 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07007709 chain->setStrategy(getStrategyForSession_l(sessionId));
7710 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007711 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07007712 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007713 }
7714
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08007715 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007716
7717 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007718 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007719 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07007720 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007721 if (lStatus != NO_ERROR) {
7722 goto Exit;
7723 }
7724 effectRegistered = true;
7725 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07007726 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007727 lStatus = effect->status();
7728 if (lStatus != NO_ERROR) {
7729 goto Exit;
7730 }
Eric Laurentcab11242010-07-15 12:50:15 -07007731 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007732 if (lStatus != NO_ERROR) {
7733 goto Exit;
7734 }
7735 effectCreated = true;
7736
7737 effect->setDevice(mDevice);
7738 effect->setMode(mAudioFlinger->getMode());
7739 }
7740 // create effect handle and connect it to effect module
7741 handle = new EffectHandle(effect, client, effectClient, priority);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007742 lStatus = effect->addHandle(handle.get());
Glenn Kastena0d68332012-01-27 16:47:15 -08007743 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007744 *enabled = (int)effect->isEnabled();
7745 }
7746 }
7747
7748Exit:
7749 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07007750 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007751 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07007752 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007753 }
7754 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07007755 AudioSystem::unregisterEffect(effect->id());
7756 }
7757 if (chainCreated) {
7758 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007759 }
7760 handle.clear();
7761 }
7762
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
Eric Laurent717e1282012-06-29 16:36:52 -07007769sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(int sessionId, int effectId)
7770{
7771 Mutex::Autolock _l(mLock);
7772 return getEffect_l(sessionId, effectId);
7773}
7774
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007775sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
7776{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007777 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08007778 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007779}
7780
Eric Laurentde070132010-07-13 04:45:46 -07007781// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
7782// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007783status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07007784{
7785 // check for existing effect chain with the requested audio session
7786 int sessionId = effect->sessionId();
7787 sp<EffectChain> chain = getEffectChain_l(sessionId);
7788 bool chainCreated = false;
7789
7790 if (chain == 0) {
7791 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01007792 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07007793 chain = new EffectChain(this, sessionId);
7794 addEffectChain_l(chain);
7795 chain->setStrategy(getStrategyForSession_l(sessionId));
7796 chainCreated = true;
7797 }
Steve Block3856b092011-10-20 11:56:00 +01007798 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007799
7800 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007801 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07007802 this, effect->desc().name, chain.get());
7803 return BAD_VALUE;
7804 }
7805
7806 status_t status = chain->addEffect_l(effect);
7807 if (status != NO_ERROR) {
7808 if (chainCreated) {
7809 removeEffectChain_l(chain);
7810 }
7811 return status;
7812 }
7813
7814 effect->setDevice(mDevice);
7815 effect->setMode(mAudioFlinger->getMode());
7816 return NO_ERROR;
7817}
7818
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007819void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07007820
Steve Block3856b092011-10-20 11:56:00 +01007821 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007822 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07007823 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7824 detachAuxEffect_l(effect->id());
7825 }
7826
7827 sp<EffectChain> chain = effect->chain().promote();
7828 if (chain != 0) {
7829 // remove effect chain if removing last effect
7830 if (chain->removeEffect_l(effect) == 0) {
7831 removeEffectChain_l(chain);
7832 }
7833 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00007834 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07007835 }
7836}
7837
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007838void AudioFlinger::ThreadBase::lockEffectChains_l(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007839 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007840{
7841 effectChains = mEffectChains;
7842 for (size_t i = 0; i < mEffectChains.size(); i++) {
7843 mEffectChains[i]->lock();
7844 }
7845}
7846
7847void AudioFlinger::ThreadBase::unlockEffectChains(
Glenn Kastene53b9ea2012-03-12 16:29:55 -07007848 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007849{
7850 for (size_t i = 0; i < effectChains.size(); i++) {
7851 effectChains[i]->unlock();
7852 }
7853}
7854
7855sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
7856{
7857 Mutex::Autolock _l(mLock);
7858 return getEffectChain_l(sessionId);
7859}
7860
Glenn Kasten106e8a42012-08-02 13:37:12 -07007861sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId) const
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007862{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007863 size_t size = mEffectChains.size();
7864 for (size_t i = 0; i < size; i++) {
7865 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007866 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007867 }
7868 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007869 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007870}
7871
Glenn Kastenf78aee72012-01-04 11:00:47 -08007872void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007873{
7874 Mutex::Autolock _l(mLock);
7875 size_t size = mEffectChains.size();
7876 for (size_t i = 0; i < size; i++) {
7877 mEffectChains[i]->setMode_l(mode);
7878 }
7879}
7880
7881void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurenta5f44eb2012-06-25 11:38:29 -07007882 EffectHandle *handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08007883 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07007884
Mathias Agopian65ab4712010-07-14 17:59:35 -07007885 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01007886 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007887 // delete the effect module if removing last handle on it
7888 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08007889 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007890 removeEffect_l(effect);
7891 AudioSystem::unregisterEffect(effect->id());
7892 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007893 }
7894}
7895
7896status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
7897{
7898 int session = chain->sessionId();
7899 int16_t *buffer = mMixBuffer;
7900 bool ownsBuffer = false;
7901
Steve Block3856b092011-10-20 11:56:00 +01007902 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007903 if (session > 0) {
7904 // Only one effect chain can be present in direct output thread and it uses
7905 // the mix buffer as input
7906 if (mType != DIRECT) {
Glenn Kasten58912562012-04-03 10:45:00 -07007907 size_t numSamples = mNormalFrameCount * mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007908 buffer = new int16_t[numSamples];
7909 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01007910 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007911 ownsBuffer = true;
7912 }
7913
7914 // Attach all tracks with same session ID to this chain.
7915 for (size_t i = 0; i < mTracks.size(); ++i) {
7916 sp<Track> track = mTracks[i];
7917 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007918 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007919 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007920 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007921 }
7922 }
7923
7924 // indicate all active tracks in the chain
7925 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7926 sp<Track> track = mActiveTracks[i].promote();
7927 if (track == 0) continue;
7928 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007929 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07007930 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007931 }
7932 }
7933 }
7934
7935 chain->setInBuffer(buffer, ownsBuffer);
7936 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07007937 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07007938 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07007939 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
7940 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007941 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07007942 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
7943 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07007944 // Effect chain for other sessions are inserted at beginning of effect
7945 // chains list to be processed before output mix effects. Relative order between other
7946 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07007947 size_t size = mEffectChains.size();
7948 size_t i = 0;
7949 for (i = 0; i < size; i++) {
7950 if (mEffectChains[i]->sessionId() < session) break;
7951 }
7952 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07007953 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007954
7955 return NO_ERROR;
7956}
7957
7958size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
7959{
7960 int session = chain->sessionId();
7961
Steve Block3856b092011-10-20 11:56:00 +01007962 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007963
7964 for (size_t i = 0; i < mEffectChains.size(); i++) {
7965 if (chain == mEffectChains[i]) {
7966 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07007967 // detach all active tracks from the chain
7968 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
7969 sp<Track> track = mActiveTracks[i].promote();
7970 if (track == 0) continue;
7971 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01007972 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07007973 chain.get(), session);
7974 chain->decActiveTrackCnt();
7975 }
7976 }
7977
Mathias Agopian65ab4712010-07-14 17:59:35 -07007978 // detach all tracks with same session ID from this chain
7979 for (size_t i = 0; i < mTracks.size(); ++i) {
7980 sp<Track> track = mTracks[i];
7981 if (session == track->sessionId()) {
7982 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07007983 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007984 }
7985 }
Eric Laurentde070132010-07-13 04:45:46 -07007986 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007987 }
7988 }
7989 return mEffectChains.size();
7990}
7991
Eric Laurentde070132010-07-13 04:45:46 -07007992status_t AudioFlinger::PlaybackThread::attachAuxEffect(
7993 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007994{
7995 Mutex::Autolock _l(mLock);
7996 return attachAuxEffect_l(track, EffectId);
7997}
7998
Eric Laurentde070132010-07-13 04:45:46 -07007999status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
8000 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008001{
8002 status_t status = NO_ERROR;
8003
8004 if (EffectId == 0) {
8005 track->setAuxBuffer(0, NULL);
8006 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07008007 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
8008 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008009 if (effect != 0) {
8010 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8011 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
8012 } else {
8013 status = INVALID_OPERATION;
8014 }
8015 } else {
8016 status = BAD_VALUE;
8017 }
8018 }
8019 return status;
8020}
8021
8022void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
8023{
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008024 for (size_t i = 0; i < mTracks.size(); ++i) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008025 sp<Track> track = mTracks[i];
8026 if (track->auxEffectId() == effectId) {
8027 attachAuxEffect_l(track, 0);
8028 }
8029 }
8030}
8031
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008032status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8033{
8034 // only one chain per input thread
8035 if (mEffectChains.size() != 0) {
8036 return INVALID_OPERATION;
8037 }
Steve Block3856b092011-10-20 11:56:00 +01008038 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008039
8040 chain->setInBuffer(NULL);
8041 chain->setOutBuffer(NULL);
8042
Eric Laurent59255e42011-07-27 19:49:51 -07008043 checkSuspendOnAddEffectChain_l(chain);
8044
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008045 mEffectChains.add(chain);
8046
8047 return NO_ERROR;
8048}
8049
8050size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8051{
Steve Block3856b092011-10-20 11:56:00 +01008052 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00008053 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008054 "removeEffectChain_l() %p invalid chain size %d on thread %p",
8055 chain.get(), mEffectChains.size(), this);
8056 if (mEffectChains.size() == 1) {
8057 mEffectChains.removeAt(0);
8058 }
8059 return 0;
8060}
8061
Mathias Agopian65ab4712010-07-14 17:59:35 -07008062// ----------------------------------------------------------------------------
8063// EffectModule implementation
8064// ----------------------------------------------------------------------------
8065
8066#undef LOG_TAG
8067#define LOG_TAG "AudioFlinger::EffectModule"
8068
Glenn Kasten9eaa5572012-01-20 13:32:16 -08008069AudioFlinger::EffectModule::EffectModule(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008070 const wp<AudioFlinger::EffectChain>& chain,
8071 effect_descriptor_t *desc,
8072 int id,
8073 int sessionId)
Glenn Kasten415fa752012-07-02 16:11:18 -07008074 : mPinned(sessionId > AUDIO_SESSION_OUTPUT_MIX),
8075 mThread(thread), mChain(chain), mId(id), mSessionId(sessionId),
Glenn Kastencd2d6102012-07-18 16:49:32 -07008076 mDescriptor(*desc),
Glenn Kasten415fa752012-07-02 16:11:18 -07008077 // mConfig is set by configure() and not used before then
8078 mEffectInterface(NULL),
8079 mStatus(NO_INIT), mState(IDLE),
8080 // mMaxDisableWaitCnt is set by configure() and not used before then
8081 // mDisableWaitCnt is set by process() and updateState() and not used before then
8082 mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008083{
Steve Block3856b092011-10-20 11:56:00 +01008084 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008085 int lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008086
8087 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008088 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008089
8090 if (mStatus != NO_ERROR) {
8091 return;
8092 }
8093 lStatus = init();
8094 if (lStatus < 0) {
8095 mStatus = lStatus;
8096 goto Error;
8097 }
8098
Steve Block3856b092011-10-20 11:56:00 +01008099 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008100 return;
8101Error:
8102 EffectRelease(mEffectInterface);
8103 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01008104 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008105}
8106
8107AudioFlinger::EffectModule::~EffectModule()
8108{
Steve Block3856b092011-10-20 11:56:00 +01008109 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008110 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008111 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8112 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
8113 sp<ThreadBase> thread = mThread.promote();
8114 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008115 audio_stream_t *stream = thread->stream();
8116 if (stream != NULL) {
8117 stream->remove_audio_effect(stream, mEffectInterface);
8118 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008119 }
8120 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008121 // release effect engine
8122 EffectRelease(mEffectInterface);
8123 }
8124}
8125
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008126status_t AudioFlinger::EffectModule::addHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008127{
8128 status_t status;
8129
8130 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008131 int priority = handle->priority();
8132 size_t size = mHandles.size();
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008133 EffectHandle *controlHandle = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008134 size_t i;
8135 for (i = 0; i < size; i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008136 EffectHandle *h = mHandles[i];
8137 if (h == NULL || h->destroyed_l()) continue;
8138 // first non destroyed handle is considered in control
8139 if (controlHandle == NULL)
8140 controlHandle = h;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008141 if (h->priority() <= priority) break;
8142 }
8143 // if inserted in first place, move effect control from previous owner to this handle
8144 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07008145 bool enabled = false;
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008146 if (controlHandle != NULL) {
8147 enabled = controlHandle->enabled();
8148 controlHandle->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008149 }
Eric Laurent59255e42011-07-27 19:49:51 -07008150 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008151 status = NO_ERROR;
8152 } else {
8153 status = ALREADY_EXISTS;
8154 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008155 ALOGV("addHandle() %p added handle %p in position %d", this, handle, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008156 mHandles.insertAt(handle, i);
8157 return status;
8158}
8159
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008160size_t AudioFlinger::EffectModule::removeHandle(EffectHandle *handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008161{
8162 Mutex::Autolock _l(mLock);
8163 size_t size = mHandles.size();
8164 size_t i;
8165 for (i = 0; i < size; i++) {
8166 if (mHandles[i] == handle) break;
8167 }
8168 if (i == size) {
8169 return size;
8170 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008171 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle, i);
Eric Laurent59255e42011-07-27 19:49:51 -07008172
Mathias Agopian65ab4712010-07-14 17:59:35 -07008173 mHandles.removeAt(i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008174 // if removed from first place, move effect control from this handle to next in line
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008175 if (i == 0) {
8176 EffectHandle *h = controlHandle_l();
8177 if (h != NULL) {
8178 h->setControl(true /*hasControl*/, true /*signal*/ , handle->enabled() /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008179 }
8180 }
8181
Eric Laurentec437d82011-07-26 20:54:46 -07008182 // Prevent calls to process() and other functions on effect interface from now on.
8183 // The effect engine will be released by the destructor when the last strong reference on
8184 // this object is released which can happen after next process is called.
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008185 if (mHandles.size() == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07008186 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07008187 }
8188
Eric Laurente65c8912012-07-20 15:57:23 -07008189 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008190}
8191
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008192// must be called with EffectModule::mLock held
8193AudioFlinger::EffectHandle *AudioFlinger::EffectModule::controlHandle_l()
Eric Laurent59255e42011-07-27 19:49:51 -07008194{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008195 // the first valid handle in the list has control over the module
8196 for (size_t i = 0; i < mHandles.size(); i++) {
8197 EffectHandle *h = mHandles[i];
8198 if (h != NULL && !h->destroyed_l()) {
8199 return h;
8200 }
8201 }
8202
8203 return NULL;
Eric Laurent59255e42011-07-27 19:49:51 -07008204}
8205
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008206size_t AudioFlinger::EffectModule::disconnect(EffectHandle *handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008207{
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008208 ALOGV("disconnect() %p handle %p", this, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008209 // keep a strong reference on this EffectModule to avoid calling the
8210 // destructor before we exit
8211 sp<EffectModule> keep(this);
8212 {
8213 sp<ThreadBase> thread = mThread.promote();
8214 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08008215 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008216 }
8217 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008218 return mHandles.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008219}
8220
8221void AudioFlinger::EffectModule::updateState() {
8222 Mutex::Autolock _l(mLock);
8223
8224 switch (mState) {
8225 case RESTART:
8226 reset_l();
8227 // FALL THROUGH
8228
8229 case STARTING:
8230 // clear auxiliary effect input buffer for next accumulation
8231 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
8232 memset(mConfig.inputCfg.buffer.raw,
8233 0,
8234 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
8235 }
8236 start_l();
8237 mState = ACTIVE;
8238 break;
8239 case STOPPING:
8240 stop_l();
8241 mDisableWaitCnt = mMaxDisableWaitCnt;
8242 mState = STOPPED;
8243 break;
8244 case STOPPED:
8245 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
8246 // turn off sequence.
8247 if (--mDisableWaitCnt == 0) {
8248 reset_l();
8249 mState = IDLE;
8250 }
8251 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008252 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07008253 break;
8254 }
8255}
8256
8257void AudioFlinger::EffectModule::process()
8258{
8259 Mutex::Autolock _l(mLock);
8260
Eric Laurentec437d82011-07-26 20:54:46 -07008261 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07008262 mConfig.inputCfg.buffer.raw == NULL ||
8263 mConfig.outputCfg.buffer.raw == NULL) {
8264 return;
8265 }
8266
Eric Laurent8f45bd72010-08-31 13:50:07 -07008267 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008268 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
8269 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08008270 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07008271 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07008272 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008273 }
8274
8275 // do the actual processing in the effect engine
8276 int ret = (*mEffectInterface)->process(mEffectInterface,
8277 &mConfig.inputCfg.buffer,
8278 &mConfig.outputCfg.buffer);
8279
8280 // force transition to IDLE state when engine is ready
8281 if (mState == STOPPED && ret == -ENODATA) {
8282 mDisableWaitCnt = 1;
8283 }
8284
8285 // clear auxiliary effect input buffer for next accumulation
8286 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08008287 memset(mConfig.inputCfg.buffer.raw, 0,
8288 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008289 }
8290 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08008291 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8292 // If an insert effect is idle and input buffer is different from output buffer,
8293 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07008294 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07008295 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08008296 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
8297 int16_t *in = mConfig.inputCfg.buffer.s16;
8298 int16_t *out = mConfig.outputCfg.buffer.s16;
8299 for (size_t i = 0; i < frameCnt; i++) {
8300 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008301 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008302 }
8303 }
8304}
8305
8306void AudioFlinger::EffectModule::reset_l()
8307{
8308 if (mEffectInterface == NULL) {
8309 return;
8310 }
8311 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
8312}
8313
8314status_t AudioFlinger::EffectModule::configure()
8315{
Mathias Agopian65ab4712010-07-14 17:59:35 -07008316 if (mEffectInterface == NULL) {
8317 return NO_INIT;
8318 }
8319
8320 sp<ThreadBase> thread = mThread.promote();
8321 if (thread == 0) {
8322 return DEAD_OBJECT;
8323 }
8324
8325 // TODO: handle configuration of effects replacing track process
Glenn Kasten254af182012-07-03 14:59:05 -07008326 audio_channel_mask_t channelMask = thread->channelMask();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008327
8328 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07008329 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008330 } else {
Glenn Kasten254af182012-07-03 14:59:05 -07008331 mConfig.inputCfg.channels = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008332 }
Glenn Kasten254af182012-07-03 14:59:05 -07008333 mConfig.outputCfg.channels = channelMask;
Eric Laurente1315cf2011-05-17 19:16:02 -07008334 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
8335 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008336 mConfig.inputCfg.samplingRate = thread->sampleRate();
8337 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
8338 mConfig.inputCfg.bufferProvider.cookie = NULL;
8339 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
8340 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
8341 mConfig.outputCfg.bufferProvider.cookie = NULL;
8342 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
8343 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
8344 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
8345 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07008346 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07008347 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07008348 // - in other sessions:
8349 // last effect in the chain accumulates in output buffer: input buffer != output buffer
8350 // other effect: overwrites output buffer: input buffer == output buffer
8351 // Auxiliary effect:
8352 // accumulates in output buffer: input buffer != output buffer
8353 // Therefore: accumulate <=> input buffer != output buffer
8354 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
8355 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
8356 } else {
8357 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
8358 }
8359 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
8360 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
8361 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
8362 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
8363
Steve Block3856b092011-10-20 11:56:00 +01008364 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07008365 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
8366
Mathias Agopian65ab4712010-07-14 17:59:35 -07008367 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008368 uint32_t size = sizeof(int);
8369 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08008370 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07008371 sizeof(effect_config_t),
8372 &mConfig,
8373 &size,
8374 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008375 if (status == 0) {
8376 status = cmdStatus;
8377 }
8378
Marco Nelissenf06c2ed2012-06-06 09:52:31 -07008379 if (status == 0 &&
8380 (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) {
8381 uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2];
8382 effect_param_t *p = (effect_param_t *)buf32;
8383
8384 p->psize = sizeof(uint32_t);
8385 p->vsize = sizeof(uint32_t);
8386 size = sizeof(int);
8387 *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY;
8388
8389 uint32_t latency = 0;
8390 PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId);
8391 if (pbt != NULL) {
8392 latency = pbt->latency_l();
8393 }
8394
8395 *((int32_t *)p->data + 1)= latency;
8396 (*mEffectInterface)->command(mEffectInterface,
8397 EFFECT_CMD_SET_PARAM,
8398 sizeof(effect_param_t) + 8,
8399 &buf32,
8400 &size,
8401 &cmdStatus);
8402 }
8403
Mathias Agopian65ab4712010-07-14 17:59:35 -07008404 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
8405 (1000 * mConfig.outputCfg.buffer.frameCount);
8406
8407 return status;
8408}
8409
8410status_t AudioFlinger::EffectModule::init()
8411{
8412 Mutex::Autolock _l(mLock);
8413 if (mEffectInterface == NULL) {
8414 return NO_INIT;
8415 }
8416 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008417 uint32_t size = sizeof(status_t);
8418 status_t status = (*mEffectInterface)->command(mEffectInterface,
8419 EFFECT_CMD_INIT,
8420 0,
8421 NULL,
8422 &size,
8423 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008424 if (status == 0) {
8425 status = cmdStatus;
8426 }
8427 return status;
8428}
8429
Eric Laurentec35a142011-10-05 17:42:25 -07008430status_t AudioFlinger::EffectModule::start()
8431{
8432 Mutex::Autolock _l(mLock);
8433 return start_l();
8434}
8435
Mathias Agopian65ab4712010-07-14 17:59:35 -07008436status_t AudioFlinger::EffectModule::start_l()
8437{
8438 if (mEffectInterface == NULL) {
8439 return NO_INIT;
8440 }
8441 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008442 uint32_t size = sizeof(status_t);
8443 status_t status = (*mEffectInterface)->command(mEffectInterface,
8444 EFFECT_CMD_ENABLE,
8445 0,
8446 NULL,
8447 &size,
8448 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008449 if (status == 0) {
8450 status = cmdStatus;
8451 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008452 if (status == 0 &&
8453 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8454 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8455 sp<ThreadBase> thread = mThread.promote();
8456 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008457 audio_stream_t *stream = thread->stream();
8458 if (stream != NULL) {
8459 stream->add_audio_effect(stream, mEffectInterface);
8460 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008461 }
8462 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008463 return status;
8464}
8465
Eric Laurentec437d82011-07-26 20:54:46 -07008466status_t AudioFlinger::EffectModule::stop()
8467{
8468 Mutex::Autolock _l(mLock);
8469 return stop_l();
8470}
8471
Mathias Agopian65ab4712010-07-14 17:59:35 -07008472status_t AudioFlinger::EffectModule::stop_l()
8473{
8474 if (mEffectInterface == NULL) {
8475 return NO_INIT;
8476 }
8477 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008478 uint32_t size = sizeof(status_t);
8479 status_t status = (*mEffectInterface)->command(mEffectInterface,
8480 EFFECT_CMD_DISABLE,
8481 0,
8482 NULL,
8483 &size,
8484 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008485 if (status == 0) {
8486 status = cmdStatus;
8487 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008488 if (status == 0 &&
8489 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
8490 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
8491 sp<ThreadBase> thread = mThread.promote();
8492 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07008493 audio_stream_t *stream = thread->stream();
8494 if (stream != NULL) {
8495 stream->remove_audio_effect(stream, mEffectInterface);
8496 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008497 }
8498 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008499 return status;
8500}
8501
Eric Laurent25f43952010-07-28 05:40:18 -07008502status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
8503 uint32_t cmdSize,
8504 void *pCmdData,
8505 uint32_t *replySize,
8506 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008507{
8508 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01008509// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008510
Eric Laurentec437d82011-07-26 20:54:46 -07008511 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008512 return NO_INIT;
8513 }
Eric Laurent25f43952010-07-28 05:40:18 -07008514 status_t status = (*mEffectInterface)->command(mEffectInterface,
8515 cmdCode,
8516 cmdSize,
8517 pCmdData,
8518 replySize,
8519 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008520 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07008521 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008522 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008523 EffectHandle *h = mHandles[i];
8524 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008525 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
8526 }
8527 }
8528 }
8529 return status;
8530}
8531
8532status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
8533{
8534 Mutex::Autolock _l(mLock);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008535 return setEnabled_l(enabled);
8536}
8537
8538// must be called with EffectModule::mLock held
8539status_t AudioFlinger::EffectModule::setEnabled_l(bool enabled)
8540{
8541
Steve Block3856b092011-10-20 11:56:00 +01008542 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008543
8544 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008545 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
8546 if (enabled && status != NO_ERROR) {
8547 return status;
8548 }
8549
Mathias Agopian65ab4712010-07-14 17:59:35 -07008550 switch (mState) {
8551 // going from disabled to enabled
8552 case IDLE:
8553 mState = STARTING;
8554 break;
8555 case STOPPED:
8556 mState = RESTART;
8557 break;
8558 case STOPPING:
8559 mState = ACTIVE;
8560 break;
8561
8562 // going from enabled to disabled
8563 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008564 mState = STOPPED;
8565 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008566 case STARTING:
8567 mState = IDLE;
8568 break;
8569 case ACTIVE:
8570 mState = STOPPING;
8571 break;
Eric Laurentec437d82011-07-26 20:54:46 -07008572 case DESTROYED:
8573 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07008574 }
8575 for (size_t i = 1; i < mHandles.size(); i++) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008576 EffectHandle *h = mHandles[i];
8577 if (h != NULL && !h->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008578 h->setEnabled(enabled);
8579 }
8580 }
8581 }
8582 return NO_ERROR;
8583}
8584
Glenn Kastenc59c0042012-02-02 14:06:11 -08008585bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07008586{
8587 switch (mState) {
8588 case RESTART:
8589 case STARTING:
8590 case ACTIVE:
8591 return true;
8592 case IDLE:
8593 case STOPPING:
8594 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07008595 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07008596 default:
8597 return false;
8598 }
8599}
8600
Glenn Kastenc59c0042012-02-02 14:06:11 -08008601bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07008602{
8603 switch (mState) {
8604 case RESTART:
8605 case ACTIVE:
8606 case STOPPING:
8607 case STOPPED:
8608 return true;
8609 case IDLE:
8610 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07008611 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07008612 default:
8613 return false;
8614 }
8615}
8616
Mathias Agopian65ab4712010-07-14 17:59:35 -07008617status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
8618{
8619 Mutex::Autolock _l(mLock);
8620 status_t status = NO_ERROR;
8621
8622 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
8623 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07008624 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07008625 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
8626 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008627 status_t cmdStatus;
8628 uint32_t volume[2];
8629 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07008630 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008631 volume[0] = *left;
8632 volume[1] = *right;
8633 if (controller) {
8634 pVolume = volume;
8635 }
Eric Laurent25f43952010-07-28 05:40:18 -07008636 status = (*mEffectInterface)->command(mEffectInterface,
8637 EFFECT_CMD_SET_VOLUME,
8638 size,
8639 volume,
8640 &size,
8641 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008642 if (controller && status == NO_ERROR && size == sizeof(volume)) {
8643 *left = volume[0];
8644 *right = volume[1];
8645 }
8646 }
8647 return status;
8648}
8649
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008650status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008651{
8652 Mutex::Autolock _l(mLock);
8653 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008654 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
8655 // audio pre processing modules on RecordThread can receive both output and
8656 // input device indication in the same call
Glenn Kastenbb4350d2012-07-03 15:56:38 -07008657 audio_devices_t dev = device & AUDIO_DEVICE_OUT_ALL;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07008658 if (dev) {
8659 status_t cmdStatus;
8660 uint32_t size = sizeof(status_t);
8661
8662 status = (*mEffectInterface)->command(mEffectInterface,
8663 EFFECT_CMD_SET_DEVICE,
8664 sizeof(uint32_t),
8665 &dev,
8666 &size,
8667 &cmdStatus);
8668 if (status == NO_ERROR) {
8669 status = cmdStatus;
8670 }
8671 }
8672 dev = device & AUDIO_DEVICE_IN_ALL;
8673 if (dev) {
8674 status_t cmdStatus;
8675 uint32_t size = sizeof(status_t);
8676
8677 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
8678 EFFECT_CMD_SET_INPUT_DEVICE,
8679 sizeof(uint32_t),
8680 &dev,
8681 &size,
8682 &cmdStatus);
8683 if (status2 == NO_ERROR) {
8684 status2 = cmdStatus;
8685 }
8686 if (status == NO_ERROR) {
8687 status = status2;
8688 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008689 }
8690 }
8691 return status;
8692}
8693
Glenn Kastenf78aee72012-01-04 11:00:47 -08008694status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008695{
8696 Mutex::Autolock _l(mLock);
8697 status_t status = NO_ERROR;
8698 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008699 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07008700 uint32_t size = sizeof(status_t);
8701 status = (*mEffectInterface)->command(mEffectInterface,
8702 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08008703 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07008704 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07008705 &size,
8706 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008707 if (status == NO_ERROR) {
8708 status = cmdStatus;
8709 }
8710 }
8711 return status;
8712}
8713
Eric Laurent59255e42011-07-27 19:49:51 -07008714void AudioFlinger::EffectModule::setSuspended(bool suspended)
8715{
8716 Mutex::Autolock _l(mLock);
8717 mSuspended = suspended;
8718}
Glenn Kastena3a85482012-01-04 11:01:11 -08008719
8720bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07008721{
8722 Mutex::Autolock _l(mLock);
8723 return mSuspended;
8724}
8725
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008726bool AudioFlinger::EffectModule::purgeHandles()
8727{
8728 bool enabled = false;
8729 Mutex::Autolock _l(mLock);
8730 for (size_t i = 0; i < mHandles.size(); i++) {
8731 EffectHandle *handle = mHandles[i];
8732 if (handle != NULL && !handle->destroyed_l()) {
8733 handle->effect().clear();
8734 if (handle->hasControl()) {
8735 enabled = handle->enabled();
8736 }
8737 }
8738 }
8739 return enabled;
8740}
8741
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07008742void AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008743{
8744 const size_t SIZE = 256;
8745 char buffer[SIZE];
8746 String8 result;
8747
8748 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
8749 result.append(buffer);
8750
8751 bool locked = tryLock(mLock);
8752 // failed to lock - AudioFlinger is probably deadlocked
8753 if (!locked) {
8754 result.append("\t\tCould not lock Fx mutex:\n");
8755 }
8756
8757 result.append("\t\tSession Status State Engine:\n");
8758 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
8759 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
8760 result.append(buffer);
8761
8762 result.append("\t\tDescriptor:\n");
8763 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8764 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
8765 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
8766 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
8767 result.append(buffer);
8768 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
8769 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
8770 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
8771 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
8772 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07008773 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07008774 mDescriptor.apiVersion,
8775 mDescriptor.flags);
8776 result.append(buffer);
8777 snprintf(buffer, SIZE, "\t\t- name: %s\n",
8778 mDescriptor.name);
8779 result.append(buffer);
8780 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
8781 mDescriptor.implementor);
8782 result.append(buffer);
8783
8784 result.append("\t\t- Input configuration:\n");
8785 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8786 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8787 (uint32_t)mConfig.inputCfg.buffer.raw,
8788 mConfig.inputCfg.buffer.frameCount,
8789 mConfig.inputCfg.samplingRate,
8790 mConfig.inputCfg.channels,
8791 mConfig.inputCfg.format);
8792 result.append(buffer);
8793
8794 result.append("\t\t- Output configuration:\n");
8795 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
8796 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
8797 (uint32_t)mConfig.outputCfg.buffer.raw,
8798 mConfig.outputCfg.buffer.frameCount,
8799 mConfig.outputCfg.samplingRate,
8800 mConfig.outputCfg.channels,
8801 mConfig.outputCfg.format);
8802 result.append(buffer);
8803
8804 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
8805 result.append(buffer);
8806 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
8807 for (size_t i = 0; i < mHandles.size(); ++i) {
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008808 EffectHandle *handle = mHandles[i];
8809 if (handle != NULL && !handle->destroyed_l()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008810 handle->dump(buffer, SIZE);
8811 result.append(buffer);
8812 }
8813 }
8814
8815 result.append("\n");
8816
8817 write(fd, result.string(), result.length());
8818
8819 if (locked) {
8820 mLock.unlock();
8821 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008822}
8823
8824// ----------------------------------------------------------------------------
8825// EffectHandle implementation
8826// ----------------------------------------------------------------------------
8827
8828#undef LOG_TAG
8829#define LOG_TAG "AudioFlinger::EffectHandle"
8830
8831AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
8832 const sp<AudioFlinger::Client>& client,
8833 const sp<IEffectClient>& effectClient,
8834 int32_t priority)
8835 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008836 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008837 mPriority(priority), mHasControl(false), mEnabled(false), mDestroyed(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008838{
Steve Block3856b092011-10-20 11:56:00 +01008839 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008840
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008841 if (client == 0) {
8842 return;
8843 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008844 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
8845 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
8846 if (mCblkMemory != 0) {
8847 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
8848
Glenn Kastena0d68332012-01-27 16:47:15 -08008849 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07008850 new(mCblk) effect_param_cblk_t();
8851 mBuffer = (uint8_t *)mCblk + bufOffset;
Glenn Kastene53b9ea2012-03-12 16:29:55 -07008852 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07008853 } else {
Steve Block29357bc2012-01-06 19:20:56 +00008854 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07008855 return;
8856 }
8857}
8858
8859AudioFlinger::EffectHandle::~EffectHandle()
8860{
Steve Block3856b092011-10-20 11:56:00 +01008861 ALOGV("Destructor %p", this);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008862
8863 if (mEffect == 0) {
8864 mDestroyed = true;
8865 return;
8866 }
8867 mEffect->lock();
8868 mDestroyed = true;
8869 mEffect->unlock();
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008870 disconnect(false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008871}
8872
8873status_t AudioFlinger::EffectHandle::enable()
8874{
Steve Block3856b092011-10-20 11:56:00 +01008875 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008876 if (!mHasControl) return INVALID_OPERATION;
8877 if (mEffect == 0) return DEAD_OBJECT;
8878
Eric Laurentdb7c0792011-08-10 10:37:50 -07008879 if (mEnabled) {
8880 return NO_ERROR;
8881 }
8882
Eric Laurent59255e42011-07-27 19:49:51 -07008883 mEnabled = true;
8884
8885 sp<ThreadBase> thread = mEffect->thread().promote();
8886 if (thread != 0) {
8887 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
8888 }
8889
8890 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
8891 if (mEffect->suspended()) {
8892 return NO_ERROR;
8893 }
8894
Eric Laurentdb7c0792011-08-10 10:37:50 -07008895 status_t status = mEffect->setEnabled(true);
8896 if (status != NO_ERROR) {
8897 if (thread != 0) {
8898 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8899 }
8900 mEnabled = false;
8901 }
8902 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008903}
8904
8905status_t AudioFlinger::EffectHandle::disable()
8906{
Steve Block3856b092011-10-20 11:56:00 +01008907 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008908 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07008909 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008910
Eric Laurentdb7c0792011-08-10 10:37:50 -07008911 if (!mEnabled) {
8912 return NO_ERROR;
8913 }
Eric Laurent59255e42011-07-27 19:49:51 -07008914 mEnabled = false;
8915
8916 if (mEffect->suspended()) {
8917 return NO_ERROR;
8918 }
8919
8920 status_t status = mEffect->setEnabled(false);
8921
8922 sp<ThreadBase> thread = mEffect->thread().promote();
8923 if (thread != 0) {
8924 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8925 }
8926
8927 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008928}
8929
8930void AudioFlinger::EffectHandle::disconnect()
8931{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008932 disconnect(true);
8933}
8934
Glenn Kasten58123c32012-02-03 10:32:24 -08008935void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008936{
Glenn Kasten58123c32012-02-03 10:32:24 -08008937 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008938 if (mEffect == 0) {
8939 return;
8940 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07008941 // restore suspended effects if the disconnected handle was enabled and the last one.
8942 if ((mEffect->disconnect(this, unpinIfLast) == 0) && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008943 sp<ThreadBase> thread = mEffect->thread().promote();
8944 if (thread != 0) {
8945 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
8946 }
Eric Laurent59255e42011-07-27 19:49:51 -07008947 }
8948
Mathias Agopian65ab4712010-07-14 17:59:35 -07008949 // release sp on module => module destructor can be called now
8950 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07008951 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08008952 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08008953 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008954 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
8955 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08008956 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08008957 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07008958 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
8959 mClient.clear();
8960 }
8961}
8962
Eric Laurent25f43952010-07-28 05:40:18 -07008963status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
8964 uint32_t cmdSize,
8965 void *pCmdData,
8966 uint32_t *replySize,
8967 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07008968{
Steve Block3856b092011-10-20 11:56:00 +01008969// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07008970// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07008971
8972 // only get parameter command is permitted for applications not controlling the effect
8973 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
8974 return INVALID_OPERATION;
8975 }
8976 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07008977 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07008978
8979 // handle commands that are not forwarded transparently to effect engine
8980 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
8981 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
8982 // no risk to block the whole media server process or mixer threads is we are stuck here
8983 Mutex::Autolock _l(mCblk->lock);
8984 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
8985 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
8986 mCblk->serverIndex = 0;
8987 mCblk->clientIndex = 0;
8988 return BAD_VALUE;
8989 }
8990 status_t status = NO_ERROR;
8991 while (mCblk->serverIndex < mCblk->clientIndex) {
8992 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07008993 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07008994 int *p = (int *)(mBuffer + mCblk->serverIndex);
8995 int size = *p++;
8996 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00008997 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07008998 break;
8999 }
9000 effect_param_t *param = (effect_param_t *)p;
9001 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009002 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07009003 mCblk->serverIndex += size;
9004 continue;
9005 }
Eric Laurent25f43952010-07-28 05:40:18 -07009006 uint32_t psize = sizeof(effect_param_t) +
9007 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
9008 param->vsize;
9009 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
9010 psize,
9011 p,
9012 &rsize,
9013 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07009014 // stop at first error encountered
9015 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009016 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07009017 *(int *)pReplyData = reply;
9018 break;
9019 } else if (reply != NO_ERROR) {
9020 *(int *)pReplyData = reply;
9021 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009022 }
9023 mCblk->serverIndex += size;
9024 }
9025 mCblk->serverIndex = 0;
9026 mCblk->clientIndex = 0;
9027 return status;
9028 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009029 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009030 return enable();
9031 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07009032 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009033 return disable();
9034 }
9035
9036 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9037}
9038
Eric Laurent59255e42011-07-27 19:49:51 -07009039void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009040{
Steve Block3856b092011-10-20 11:56:00 +01009041 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009042
9043 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07009044 mEnabled = enabled;
9045
Mathias Agopian65ab4712010-07-14 17:59:35 -07009046 if (signal && mEffectClient != 0) {
9047 mEffectClient->controlStatusChanged(hasControl);
9048 }
9049}
9050
Eric Laurent25f43952010-07-28 05:40:18 -07009051void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
9052 uint32_t cmdSize,
9053 void *pCmdData,
9054 uint32_t replySize,
9055 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009056{
9057 if (mEffectClient != 0) {
9058 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
9059 }
9060}
9061
9062
9063
9064void AudioFlinger::EffectHandle::setEnabled(bool enabled)
9065{
9066 if (mEffectClient != 0) {
9067 mEffectClient->enableStatusChanged(enabled);
9068 }
9069}
9070
9071status_t AudioFlinger::EffectHandle::onTransact(
9072 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9073{
9074 return BnEffect::onTransact(code, data, reply, flags);
9075}
9076
9077
9078void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
9079{
Glenn Kastena0d68332012-01-27 16:47:15 -08009080 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009081
9082 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08009083 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07009084 mPriority,
9085 mHasControl,
9086 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07009087 mCblk ? mCblk->clientIndex : 0,
9088 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07009089 );
9090
9091 if (locked) {
9092 mCblk->lock.unlock();
9093 }
9094}
9095
9096#undef LOG_TAG
9097#define LOG_TAG "AudioFlinger::EffectChain"
9098
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009099AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009100 int sessionId)
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009101 : mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07009102 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
9103 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009104{
Dima Zavinfce7a472011-04-19 22:30:36 -07009105 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Glenn Kasten9eaa5572012-01-20 13:32:16 -08009106 if (thread == NULL) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009107 return;
9108 }
9109 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
9110 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009111}
9112
9113AudioFlinger::EffectChain::~EffectChain()
9114{
9115 if (mOwnInBuffer) {
9116 delete mInBuffer;
9117 }
9118
9119}
9120
Eric Laurent59255e42011-07-27 19:49:51 -07009121// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009122sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009123{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009124 size_t size = mEffects.size();
9125
9126 for (size_t i = 0; i < size; i++) {
9127 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009128 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009129 }
9130 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009131 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009132}
9133
Eric Laurent59255e42011-07-27 19:49:51 -07009134// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07009135sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009136{
Mathias Agopian65ab4712010-07-14 17:59:35 -07009137 size_t size = mEffects.size();
9138
9139 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07009140 // by convention, return first effect if id provided is 0 (0 is never a valid id)
9141 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009142 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07009143 }
9144 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009145 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009146}
9147
Eric Laurent59255e42011-07-27 19:49:51 -07009148// getEffectFromType_l() must be called with ThreadBase::mLock held
9149sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
9150 const effect_uuid_t *type)
9151{
Eric Laurent59255e42011-07-27 19:49:51 -07009152 size_t size = mEffects.size();
9153
9154 for (size_t i = 0; i < size; i++) {
9155 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08009156 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07009157 }
9158 }
Glenn Kasten090f0192012-01-30 13:00:02 -08009159 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009160}
9161
Eric Laurent91b14c42012-05-30 12:30:29 -07009162void AudioFlinger::EffectChain::clearInputBuffer()
9163{
9164 Mutex::Autolock _l(mLock);
9165 sp<ThreadBase> thread = mThread.promote();
9166 if (thread == 0) {
9167 ALOGW("clearInputBuffer(): cannot promote mixer thread");
9168 return;
9169 }
9170 clearInputBuffer_l(thread);
9171}
9172
9173// Must be called with EffectChain::mLock locked
9174void AudioFlinger::EffectChain::clearInputBuffer_l(sp<ThreadBase> thread)
9175{
9176 size_t numSamples = thread->frameCount() * thread->channelCount();
9177 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
9178
9179}
9180
Mathias Agopian65ab4712010-07-14 17:59:35 -07009181// Must be called with EffectChain::mLock locked
9182void AudioFlinger::EffectChain::process_l()
9183{
Eric Laurentdac69112010-09-28 14:09:57 -07009184 sp<ThreadBase> thread = mThread.promote();
9185 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009186 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07009187 return;
9188 }
Dima Zavinfce7a472011-04-19 22:30:36 -07009189 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
9190 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009191 // always process effects unless no more tracks are on the session and the effect tail
9192 // has been rendered
9193 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07009194 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08009195 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07009196
Eric Laurent544fe9b2011-11-11 15:42:52 -08009197 if (!tracksOnSession && mTailBufferCount == 0) {
9198 doProcess = false;
9199 }
9200
9201 if (activeTrackCnt() == 0) {
9202 // if no track is active and the effect tail has not been rendered,
9203 // the input buffer must be cleared here as the mixer process will not do it
9204 if (tracksOnSession || mTailBufferCount > 0) {
Eric Laurent91b14c42012-05-30 12:30:29 -07009205 clearInputBuffer_l(thread);
Eric Laurent544fe9b2011-11-11 15:42:52 -08009206 if (mTailBufferCount > 0) {
9207 mTailBufferCount--;
9208 }
9209 }
9210 }
Eric Laurentdac69112010-09-28 14:09:57 -07009211 }
9212
Mathias Agopian65ab4712010-07-14 17:59:35 -07009213 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08009214 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07009215 for (size_t i = 0; i < size; i++) {
9216 mEffects[i]->process();
9217 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009218 }
9219 for (size_t i = 0; i < size; i++) {
9220 mEffects[i]->updateState();
9221 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009222}
9223
Eric Laurentcab11242010-07-15 12:50:15 -07009224// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07009225status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009226{
9227 effect_descriptor_t desc = effect->desc();
9228 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
9229
9230 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07009231 effect->setChain(this);
9232 sp<ThreadBase> thread = mThread.promote();
9233 if (thread == 0) {
9234 return NO_INIT;
9235 }
9236 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009237
9238 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
9239 // Auxiliary effects are inserted at the beginning of mEffects vector as
9240 // they are processed first and accumulated in chain input buffer
9241 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07009242
Mathias Agopian65ab4712010-07-14 17:59:35 -07009243 // the input buffer for auxiliary effect contains mono samples in
9244 // 32 bit format. This is to avoid saturation in AudoMixer
9245 // accumulation stage. Saturation is done in EffectModule::process() before
9246 // calling the process in effect engine
9247 size_t numSamples = thread->frameCount();
9248 int32_t *buffer = new int32_t[numSamples];
9249 memset(buffer, 0, numSamples * sizeof(int32_t));
9250 effect->setInBuffer((int16_t *)buffer);
9251 // auxiliary effects output samples to chain input buffer for further processing
9252 // by insert effects
9253 effect->setOutBuffer(mInBuffer);
9254 } else {
9255 // Insert effects are inserted at the end of mEffects vector as they are processed
9256 // after track and auxiliary effects.
9257 // Insert effect order as a function of indicated preference:
9258 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
9259 // another effect is present
9260 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
9261 // last effect claiming first position
9262 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
9263 // first effect claiming last position
9264 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
9265 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
9266 // already present
9267
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009268 size_t size = mEffects.size();
9269 size_t idx_insert = size;
9270 ssize_t idx_insert_first = -1;
9271 ssize_t idx_insert_last = -1;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009272
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009273 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009274 effect_descriptor_t d = mEffects[i]->desc();
9275 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
9276 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
9277 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
9278 // check invalid effect chaining combinations
9279 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
9280 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009281 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009282 return INVALID_OPERATION;
9283 }
9284 // remember position of first insert effect and by default
9285 // select this as insert position for new effect
9286 if (idx_insert == size) {
9287 idx_insert = i;
9288 }
9289 // remember position of last insert effect claiming
9290 // first position
9291 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
9292 idx_insert_first = i;
9293 }
9294 // remember position of first insert effect claiming
9295 // last position
9296 if (iPref == EFFECT_FLAG_INSERT_LAST &&
9297 idx_insert_last == -1) {
9298 idx_insert_last = i;
9299 }
9300 }
9301 }
9302
9303 // modify idx_insert from first position if needed
9304 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
9305 if (idx_insert_last != -1) {
9306 idx_insert = idx_insert_last;
9307 } else {
9308 idx_insert = size;
9309 }
9310 } else {
9311 if (idx_insert_first != -1) {
9312 idx_insert = idx_insert_first + 1;
9313 }
9314 }
9315
9316 // always read samples from chain input buffer
9317 effect->setInBuffer(mInBuffer);
9318
9319 // if last effect in the chain, output samples to chain
9320 // output buffer, otherwise to chain input buffer
9321 if (idx_insert == size) {
9322 if (idx_insert != 0) {
9323 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
9324 mEffects[idx_insert-1]->configure();
9325 }
9326 effect->setOutBuffer(mOutBuffer);
9327 } else {
9328 effect->setOutBuffer(mInBuffer);
9329 }
9330 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009331
Steve Block3856b092011-10-20 11:56:00 +01009332 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009333 }
9334 effect->configure();
9335 return NO_ERROR;
9336}
9337
Eric Laurentcab11242010-07-15 12:50:15 -07009338// removeEffect_l() must be called with PlaybackThread::mLock held
9339size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009340{
9341 Mutex::Autolock _l(mLock);
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009342 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009343 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
9344
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009345 for (size_t i = 0; i < size; i++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009346 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07009347 // calling stop here will remove pre-processing effect from the audio HAL.
9348 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
9349 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07009350 if (mEffects[i]->state() == EffectModule::ACTIVE ||
9351 mEffects[i]->state() == EffectModule::STOPPING) {
9352 mEffects[i]->stop();
9353 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009354 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
9355 delete[] effect->inBuffer();
9356 } else {
9357 if (i == size - 1 && i != 0) {
9358 mEffects[i - 1]->setOutBuffer(mOutBuffer);
9359 mEffects[i - 1]->configure();
9360 }
9361 }
9362 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01009363 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07009364 break;
9365 }
9366 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009367
9368 return mEffects.size();
9369}
9370
Eric Laurentcab11242010-07-15 12:50:15 -07009371// setDevice_l() must be called with PlaybackThread::mLock held
Glenn Kastenbb4350d2012-07-03 15:56:38 -07009372void AudioFlinger::EffectChain::setDevice_l(audio_devices_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009373{
9374 size_t size = mEffects.size();
9375 for (size_t i = 0; i < size; i++) {
9376 mEffects[i]->setDevice(device);
9377 }
9378}
9379
Eric Laurentcab11242010-07-15 12:50:15 -07009380// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08009381void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009382{
9383 size_t size = mEffects.size();
9384 for (size_t i = 0; i < size; i++) {
9385 mEffects[i]->setMode(mode);
9386 }
9387}
9388
Eric Laurentcab11242010-07-15 12:50:15 -07009389// setVolume_l() must be called with PlaybackThread::mLock held
9390bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009391{
9392 uint32_t newLeft = *left;
9393 uint32_t newRight = *right;
9394 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07009395 int ctrlIdx = -1;
9396 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07009397
Eric Laurentcab11242010-07-15 12:50:15 -07009398 // first update volume controller
9399 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07009400 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07009401 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
9402 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07009403 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07009404 break;
9405 }
9406 }
9407
9408 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07009409 if (hasControl) {
9410 *left = mNewLeftVolume;
9411 *right = mNewRightVolume;
9412 }
9413 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07009414 }
9415
9416 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07009417 mLeftVolume = newLeft;
9418 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009419
9420 // second get volume update from volume controller
9421 if (ctrlIdx >= 0) {
9422 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07009423 mNewLeftVolume = newLeft;
9424 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07009425 }
9426 // then indicate volume to all other effects in chain.
9427 // Pass altered volume to effects before volume controller
9428 // and requested volume to effects after controller
9429 uint32_t lVol = newLeft;
9430 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07009431
Mathias Agopian65ab4712010-07-14 17:59:35 -07009432 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07009433 if ((int)i == ctrlIdx) continue;
9434 // this also works for ctrlIdx == -1 when there is no volume controller
9435 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07009436 lVol = *left;
9437 rVol = *right;
9438 }
9439 mEffects[i]->setVolume(&lVol, &rVol, false);
9440 }
9441 *left = newLeft;
9442 *right = newRight;
9443
9444 return hasControl;
9445}
9446
Glenn Kastenbe5f05e2012-07-18 15:24:02 -07009447void AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
Mathias Agopian65ab4712010-07-14 17:59:35 -07009448{
9449 const size_t SIZE = 256;
9450 char buffer[SIZE];
9451 String8 result;
9452
9453 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
9454 result.append(buffer);
9455
9456 bool locked = tryLock(mLock);
9457 // failed to lock - AudioFlinger is probably deadlocked
9458 if (!locked) {
9459 result.append("\tCould not lock mutex:\n");
9460 }
9461
Eric Laurentcab11242010-07-15 12:50:15 -07009462 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
9463 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07009464 mEffects.size(),
9465 (uint32_t)mInBuffer,
9466 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07009467 mActiveTrackCnt);
9468 result.append(buffer);
9469 write(fd, result.string(), result.size());
9470
9471 for (size_t i = 0; i < mEffects.size(); ++i) {
9472 sp<EffectModule> effect = mEffects[i];
9473 if (effect != 0) {
9474 effect->dump(fd, args);
9475 }
9476 }
9477
9478 if (locked) {
9479 mLock.unlock();
9480 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07009481}
9482
Eric Laurent59255e42011-07-27 19:49:51 -07009483// must be called with ThreadBase::mLock held
9484void AudioFlinger::EffectChain::setEffectSuspended_l(
9485 const effect_uuid_t *type, bool suspend)
9486{
9487 sp<SuspendedEffectDesc> desc;
9488 // use effect type UUID timelow as key as there is no real risk of identical
9489 // timeLow fields among effect type UUIDs.
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009490 ssize_t index = mSuspendedEffects.indexOfKey(type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009491 if (suspend) {
9492 if (index >= 0) {
9493 desc = mSuspendedEffects.valueAt(index);
9494 } else {
9495 desc = new SuspendedEffectDesc();
Glenn Kastena189a682012-02-20 12:16:30 -08009496 desc->mType = *type;
Eric Laurent59255e42011-07-27 19:49:51 -07009497 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01009498 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009499 }
9500 if (desc->mRefCount++ == 0) {
9501 sp<EffectModule> effect = getEffectIfEnabled(type);
9502 if (effect != 0) {
9503 desc->mEffect = effect;
9504 effect->setSuspended(true);
9505 effect->setEnabled(false);
9506 }
9507 }
9508 } else {
9509 if (index < 0) {
9510 return;
9511 }
9512 desc = mSuspendedEffects.valueAt(index);
9513 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009514 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009515 desc->mRefCount = 1;
9516 }
9517 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01009518 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009519 if (desc->mEffect != 0) {
9520 sp<EffectModule> effect = desc->mEffect.promote();
9521 if (effect != 0) {
9522 effect->setSuspended(false);
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009523 effect->lock();
9524 EffectHandle *handle = effect->controlHandle_l();
9525 if (handle != NULL && !handle->destroyed_l()) {
9526 effect->setEnabled_l(handle->enabled());
Eric Laurent59255e42011-07-27 19:49:51 -07009527 }
Eric Laurenta5f44eb2012-06-25 11:38:29 -07009528 effect->unlock();
Eric Laurent59255e42011-07-27 19:49:51 -07009529 }
9530 desc->mEffect.clear();
9531 }
9532 mSuspendedEffects.removeItemsAt(index);
9533 }
9534 }
9535}
9536
9537// must be called with ThreadBase::mLock held
9538void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
9539{
9540 sp<SuspendedEffectDesc> desc;
9541
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009542 ssize_t index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
Eric Laurent59255e42011-07-27 19:49:51 -07009543 if (suspend) {
9544 if (index >= 0) {
9545 desc = mSuspendedEffects.valueAt(index);
9546 } else {
9547 desc = new SuspendedEffectDesc();
9548 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01009549 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07009550 }
9551 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08009552 Vector< sp<EffectModule> > effects;
9553 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07009554 for (size_t i = 0; i < effects.size(); i++) {
9555 setEffectSuspended_l(&effects[i]->desc().type, true);
9556 }
9557 }
9558 } else {
9559 if (index < 0) {
9560 return;
9561 }
9562 desc = mSuspendedEffects.valueAt(index);
9563 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009564 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07009565 desc->mRefCount = 1;
9566 }
9567 if (--desc->mRefCount == 0) {
9568 Vector<const effect_uuid_t *> types;
9569 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
9570 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
9571 continue;
9572 }
9573 types.add(&mSuspendedEffects.valueAt(i)->mType);
9574 }
9575 for (size_t i = 0; i < types.size(); i++) {
9576 setEffectSuspended_l(types[i], false);
9577 }
Steve Block3856b092011-10-20 11:56:00 +01009578 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07009579 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
9580 }
9581 }
9582}
9583
Eric Laurent6bffdb82011-09-23 08:40:41 -07009584
9585// The volume effect is used for automated tests only
9586#ifndef OPENSL_ES_H_
9587static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
9588 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
9589const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
9590#endif //OPENSL_ES_H_
9591
Eric Laurentdb7c0792011-08-10 10:37:50 -07009592bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
9593{
9594 // auxiliary effects and visualizer are never suspended on output mix
9595 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
9596 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07009597 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
9598 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07009599 return false;
9600 }
9601 return true;
9602}
9603
Glenn Kastend0539712012-01-30 12:56:03 -08009604void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07009605{
Glenn Kastend0539712012-01-30 12:56:03 -08009606 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07009607 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08009608 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
9609 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07009610 }
Eric Laurent59255e42011-07-27 19:49:51 -07009611 }
Eric Laurent59255e42011-07-27 19:49:51 -07009612}
9613
9614sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
9615 const effect_uuid_t *type)
9616{
Glenn Kasten090f0192012-01-30 13:00:02 -08009617 sp<EffectModule> effect = getEffectFromType_l(type);
9618 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07009619}
9620
9621void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
9622 bool enabled)
9623{
Glenn Kasten8d6a2442012-02-08 14:04:28 -08009624 ssize_t index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009625 if (enabled) {
9626 if (index < 0) {
9627 // if the effect is not suspend check if all effects are suspended
9628 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
9629 if (index < 0) {
9630 return;
9631 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07009632 if (!isEffectEligibleForSuspend(effect->desc())) {
9633 return;
9634 }
Eric Laurent59255e42011-07-27 19:49:51 -07009635 setEffectSuspended_l(&effect->desc().type, enabled);
9636 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07009637 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00009638 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07009639 return;
9640 }
Eric Laurent59255e42011-07-27 19:49:51 -07009641 }
Steve Block3856b092011-10-20 11:56:00 +01009642 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009643 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009644 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9645 // if effect is requested to suspended but was not yet enabled, supend it now.
9646 if (desc->mEffect == 0) {
9647 desc->mEffect = effect;
9648 effect->setEnabled(false);
9649 effect->setSuspended(true);
9650 }
9651 } else {
9652 if (index < 0) {
9653 return;
9654 }
Steve Block3856b092011-10-20 11:56:00 +01009655 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Glenn Kastene53b9ea2012-03-12 16:29:55 -07009656 effect->desc().type.timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07009657 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
9658 desc->mEffect.clear();
9659 effect->setSuspended(false);
9660 }
9661}
9662
Mathias Agopian65ab4712010-07-14 17:59:35 -07009663#undef LOG_TAG
9664#define LOG_TAG "AudioFlinger"
9665
9666// ----------------------------------------------------------------------------
9667
9668status_t AudioFlinger::onTransact(
9669 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
9670{
9671 return BnAudioFlinger::onTransact(code, data, reply, flags);
9672}
9673
Mathias Agopian65ab4712010-07-14 17:59:35 -07009674}; // namespace android